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/appearance.py ADDED
@@ -0,0 +1,707 @@
1
+ """R-like physical layout over the unchanged numerical heatmap engine."""
2
+ import base64
3
+ import copy
4
+ import io
5
+ import math
6
+ import os
7
+ from pathlib import Path
8
+ import warnings
9
+ from xml.sax.saxutils import escape
10
+
11
+ import cv2
12
+ import numpy as np
13
+ from .slice_geometry import slice_gaps
14
+ import pandas as pd
15
+
16
+ from .annotation import SimpleAnnotation
17
+ from .style import Appearance, ColorMapping, text_width
18
+
19
+
20
+ def initialize(plotter, options):
21
+ p=plotter
22
+ p.style=options.get('style','complexheatmap')
23
+ if p.style not in ('complexheatmap','legacy'):
24
+ raise ValueError('style must be complexheatmap or legacy')
25
+ p._visual_options=dict(options)
26
+ p.dpi=float(300 if options.get('dpi') is None else options['dpi'])
27
+ if not np.isfinite(p.dpi) or p.dpi<=0:raise ValueError('dpi must be positive and finite')
28
+ if options.get('width_mm') is not None and options.get('output_width') is not None:
29
+ raise ValueError('width_mm and output_width cannot both specify the body width')
30
+ width_mm=float(180 if options.get('width_mm') is None else options['width_mm'])
31
+ if not np.isfinite(width_mm) or width_mm<=0:raise ValueError('width_mm must be positive and finite')
32
+ from .style import resolved_font_family
33
+ p._requested_font_family=options.get('font_family','DejaVu Sans')
34
+ p._appearance=Appearance(p.dpi,width_mm,resolved_font_family(p._requested_font_family))
35
+ p._font_fallback_reported=False
36
+ p.heatmap_name=str('matrix' if options.get('heatmap_name') is None else options['heatmap_name'])
37
+ p.show_heatmap_legend=bool(options.get('show_heatmap_legend',True))
38
+ p.row_title=options.get('row_title')
39
+ p.column_title=options.get('column_title')
40
+ p.row_names_side=options.get('row_names_side','right')
41
+ p.column_names_side=options.get('column_names_side','bottom')
42
+ if p.row_names_side not in ('left','right'):raise ValueError('row_names_side must be left or right')
43
+ if p.column_names_side not in ('top','bottom'):raise ValueError('column_names_side must be top or bottom')
44
+ p.row_names_rot=float(options.get('row_names_rot',0))
45
+ p.column_names_rot=float(options.get('column_names_rot',90))
46
+ from .graphics import validate_gp
47
+ p._dend_gp={}
48
+ for axis in ('row','column'):
49
+ gp=validate_gp(options.get(axis+'_dend_gp'),{'col','lwd'})
50
+ p._dend_gp[axis]=gp
51
+ from .tree_styles import validate_nodes
52
+ p._dend_node_gp={axis:validate_nodes(options.get(axis+'_dend_node_gp')) for axis in ('row','column')}
53
+ if not np.isfinite([p.row_names_rot,p.column_names_rot]).all():raise ValueError('name rotations must be finite')
54
+ p.row_dend_side=options.get('row_dend_side','left')
55
+ p.column_dend_side=options.get('column_dend_side','top')
56
+ if p.row_dend_side not in ('left','right') or p.column_dend_side not in ('top','bottom'):raise ValueError('invalid dendrogram side')
57
+ p.label_policy=options.get('label_policy','auto')
58
+ if p.label_policy not in ('auto','all'):raise ValueError('label_policy must be auto or all')
59
+ p.max_canvas_pixels=int(options.get('max_canvas_pixels',20_000_000))
60
+ p.max_canvas_dimension=int(options.get('max_canvas_dimension',10_000))
61
+ if min(p.max_canvas_pixels,p.max_canvas_dimension)<=0:raise ValueError('canvas budgets must be positive')
62
+ p._annotation_sources=None
63
+ from .text_styles import initialize as initialize_text_styles
64
+ initialize_text_styles(p)
65
+ p._body_border_gp=validate_gp(options.get('body_border_gp'),{'col','lwd'})
66
+ p._rect_gp=validate_gp(options.get('rect_gp'),{'col','lwd'})
67
+ for gp in (p._body_border_gp,p._rect_gp):
68
+ if any(isinstance(v,(list,tuple,np.ndarray)) for v in gp.values()):raise ValueError('rectangle gp uses one uniform style')
69
+ for new,old in [('row_gap_mm','row_split_gap'),('column_gap_mm','col_split_gap')]:
70
+ if options.get(new) is not None and options.get(old) is not None:raise ValueError(f'{new} and {old} conflict; choose one')
71
+
72
+
73
+ def prepare(p):
74
+ from .text_styles import bind_name_ids
75
+ bind_name_ids(p)
76
+ if p._annotation_sources is None:
77
+ # Private copies keep both caller-owned objects and later exports stable.
78
+ originals=p.all_annotations
79
+ copies=[]
80
+ for ha in originals:
81
+ h=copy.copy(ha)
82
+ if getattr(ha,'df',None) is not None:
83
+ h.df=ha.df.copy(deep=True)
84
+ if getattr(ha,'_positional',False):
85
+ names=p.df.index if ha.side in ('left','right') else p.df.columns
86
+ if len(h.df)!=len(names):raise ValueError('positional annotation length does not match heatmap axis')
87
+ h._bind_item_ids(names)
88
+ else:h.df.index=h.df.index.map(str)
89
+ copies.append(h)
90
+ p.all_annotations=copies
91
+ for side in ('top','bottom','left','right'):
92
+ setattr(p,side+'_annotations',[h for h in copies if h.side==side])
93
+ p._annotation_sources=[None if h.df is None else h.df.copy(deep=True) for h in copies]
94
+ p._compute_clustering()
95
+ # Reconstruct views from stable identifiers, not from previously permuted views.
96
+ for ha,source in zip(p.all_annotations,p._annotation_sources):
97
+ if source is None:continue
98
+ names=p.row_names if ha.side in ('left','right') else p.col_names
99
+ ha.df=source.reindex(pd.Index(names).map(str)).copy()
100
+
101
+
102
+ def _label_indices(n,cell,font,policy):
103
+ if policy=='all':return np.arange(n)
104
+ step=max(1,int(math.ceil(font*1.15/max(cell,1e-12))))
105
+ return np.arange(0,n,step)
106
+
107
+
108
+ def label_text(p,axis,i):
109
+ names=p.row_names if axis=='row' else p.col_names
110
+ labels=p._visual_options.get('row_labels' if axis=='row' else 'column_labels')
111
+ if labels is None:return str(names[i])
112
+ if isinstance(labels,dict):return str(labels.get(str(names[i]),names[i]))
113
+ original=p.df.index if axis=='row' else p.df.columns
114
+ lookup=dict(zip(original.map(str),labels))
115
+ return str(lookup.get(str(names[i]),names[i]))
116
+
117
+
118
+ def compute_layout(p):
119
+ from .r_layout_controls import constrained_layout
120
+ return constrained_layout(p,_compute_layout_native)
121
+
122
+
123
+ def _compute_layout_native(p):
124
+ prepare(p)
125
+ a=p._appearance
126
+ if not p._font_fallback_reported and p._requested_font_family.casefold()!=a.font_family.casefold():
127
+ warnings.warn(f'font family {p._requested_font_family!r} resolves to {a.font_family!r}; using the resolved family for measurements and all exports',UserWarning,stacklevel=2)
128
+ p._font_fallback_reported=True
129
+ if getattr(p,'_category_colors',None) is not None:
130
+ p._category_colors=dict(p._category_colors)
131
+ p._category_colors[0]=p._visual_options.get('na_col','#BEBEBE')
132
+ nr,nc=p._matrix_sorted.shape
133
+ opt=p._visual_options
134
+ body_w=float(opt['output_width']) if opt.get('output_width') is not None else a.mm(a.body_width_mm)
135
+ if hasattr(p,"_shared_body"):
136
+ body_w,body_h=p._shared_body
137
+ elif p.autoscale:
138
+ ar=p.aspect_ratio or 1
139
+ cw=max(1,round(nr/(ar*nc))) if nr>ar*nc else 1
140
+ ch=max(1,round(ar*nc/nr)) if nr<=ar*nc else 1
141
+ k=max(1,math.ceil(body_w/(nc*cw)))
142
+ body_w=min(float(p.autoscale_max_width),float(nc*cw*k))
143
+ body_h=nr*ch*k
144
+ else:body_h=a.mm(opt['height_mm']) if opt.get('height_mm') is not None else body_w*(p.aspect_ratio or .75)
145
+ if p.autoscale and opt.get('height_mm') is not None:raise ValueError('height_mm conflicts with autoscale')
146
+ if not np.isfinite([body_w,body_h]).all() or body_w<=0 or body_h<=0:raise ValueError('heatmap body dimensions must be positive and finite')
147
+ p.col_gap_pixels=a.mm(1) if opt.get('col_split_gap') is None else float(opt['col_split_gap'])*10
148
+ p.row_gap_pixels=a.mm(1) if opt.get('row_split_gap') is None else float(opt['row_split_gap'])*10
149
+ from .slice_geometry import configure,gap_total
150
+ rg=configure(p,'row',opt.get('row_gap_mm'),p.row_breaks)
151
+ cg=configure(p,'column',opt.get('column_gap_mm'),p.col_breaks)
152
+ if p._rect_gp:
153
+ p.heatmap_element_border=p._rect_gp.get('col') is not None
154
+ p.heatmap_element_border_color=p._rect_gp.get('col') or '#000000'
155
+ p.heatmap_element_border_width=a.pt(float(p._rect_gp.get('lwd',.75)))
156
+ if not np.isfinite([p.col_gap_pixels,p.row_gap_pixels]).all() or min(p.col_gap_pixels,p.row_gap_pixels)<0:raise ValueError('slice gaps must be finite and nonnegative')
157
+ if gap_total(cg,len(p.col_breaks))>=body_w or gap_total(rg,len(p.row_breaks))>=body_h:
158
+ raise ValueError('slice gaps exceed the heatmap body; increase width_mm/output_width or reduce row_split_gap/col_split_gap')
159
+ p._annot_gap_px=a.pt(1)
160
+ p._cell_w=max(1e-12,(body_w-gap_total(cg,len(p.col_breaks)))/nc)
161
+ p._cell_h=max(1e-12,(body_h-gap_total(rg,len(p.row_breaks)))/nr)
162
+ p._font_ref=a.pt(10);p._font_min=1;p._border_scale=1
163
+ p._phys_short=min(body_w,body_h)
164
+ for key,pt in [('row_fontsize',getattr(p,'_default_row_fontsize_pt',12)),('col_fontsize',12),('legend_fontsize',10),('scoring_fontsize',10),('cluster_label_fontsize',10)]:
165
+ setattr(p,key,float(opt[key]) if opt.get(key) is not None else a.pt(pt))
166
+ if not np.isfinite(getattr(p,key)) or getattr(p,key)<0:raise ValueError(f'{key} must be finite and nonnegative')
167
+ # Annotation explicit heights/font sizes retain their existing pixel units.
168
+ def thickness(side):
169
+ from .annotation_layout import thickness as band_thickness
170
+ return band_thickness(p,getattr(p,side+'_annotations'))
171
+ top,bottom,left,right=(thickness(s) for s in ('top','bottom','left','right'))
172
+ gap=a.mm(1);pad=a.mm(2)
173
+ axis_space=dict(left=0.,right=0.,top=0.,bottom=0.)
174
+ for ha in p.all_annotations:
175
+ if hasattr(ha,'axis_padding'):
176
+ for side,extent in ha.axis_padding(p).items():axis_space[side]=max(axis_space[side],extent)
177
+ dend_sizes=[6 if opt.get(k) is None else float(opt[k]) for k in ('row_dend_width_mm','column_dend_height_mm')]
178
+ if not np.isfinite(dend_sizes).all() or min(dend_sizes)<0:raise ValueError('dendrogram dimensions must be finite and nonnegative')
179
+ from .parent_dendrogram import display_linkage
180
+ p._display_row_linkage=display_linkage(p,'row') if p.row_dendro and dend_sizes[0] else None
181
+ p._display_col_linkage=display_linkage(p,'col') if p.col_dendro and dend_sizes[1] else None
182
+ rd=a.mm(dend_sizes[0]) if p.row_dendro and p._display_row_linkage is not None else 0
183
+ cd=a.mm(dend_sizes[1]) if p.col_dendro and p._display_col_linkage is not None else 0
184
+ from .tree_styles import marker_padding
185
+ rp=marker_padding(p,'row') if rd else 0.
186
+ cp=marker_padding(p,'column') if cd else 0.
187
+ if rp:
188
+ axis_space['top']=max(axis_space['top'],rp);axis_space['bottom']=max(axis_space['bottom'],rp)
189
+ if cp:
190
+ axis_space['left']=max(axis_space['left'],cp);axis_space['right']=max(axis_space['right'],cp)
191
+ dendro_gap=a.mm(.5)
192
+ left_extent=left+(gap if left else 0)+((rd+2*rp+dendro_gap) if rd and p.row_dend_side=='left' else 0)
193
+ right_extent=right+(gap if right else 0)+((rd+2*rp+dendro_gap) if rd and p.row_dend_side=='right' else 0)
194
+ top_extent=top+(gap if top else 0)+((cd+2*cp+dendro_gap) if cd and p.column_dend_side=='top' else 0)
195
+ bottom_extent=bottom+(gap if bottom else 0)+((cd+2*cp+dendro_gap) if cd and p.column_dend_side=='bottom' else 0)
196
+ from .name_layout import track,move,envelope,union
197
+ rids,row_nodes,rnw=track(p,'row',p._cell_h,p.row_breaks,slice_gaps(p,'row'),label_text)
198
+ cids,col_nodes,cnh=track(p,'col',p._cell_w,p.col_breaks,slice_gaps(p,'column'),label_text)
199
+ inside_names=bool(getattr(p,'_row_names_before_annotation',False) and rnw)
200
+ p._annotation_offsets={'left':0.,'right':0.}
201
+ if inside_names:
202
+ p._annotation_offsets[p.row_names_side]=rnw+gap
203
+ if p.row_names_side=='left':left_extent+=rnw+gap
204
+ else:right_extent+=rnw+gap
205
+ if len(rids) and len(rids)<nr:warnings.warn(f'dense row labels: showing {len(rids)} of {nr}; label_policy="all" shows every name',UserWarning,stacklevel=2)
206
+ if len(cids) and len(cids)<nc:warnings.warn(f'dense column labels: showing {len(cids)} of {nc}; label_policy="all" shows every name',UserWarning,stacklevel=2)
207
+ title_h=0
208
+ title_w=0
209
+ # Existing annotation implementations draw track labels beside their bands.
210
+ track_label_w=max((text_width(c,a.pt(10),family=a.font_family) for h in p.top_annotations if not isinstance(h,SimpleAnnotation) for c in (h.df.columns if h.df is not None else [h.label or ''])),default=0)
211
+ x=pad+title_w+max(left_extent,track_label_w+gap)
212
+ x+=axis_space['left']
213
+ y=pad+max(title_h+top_extent,axis_space['top'])
214
+ if p.row_names_side=='left' and rnw and not inside_names:x+=rnw+gap
215
+ if p.column_names_side=='top' and cnh:y+=cnh+gap
216
+ right_names=rnw if p.row_names_side=='right' and not inside_names else 0
217
+ bottom_names=cnh if p.column_names_side=='bottom' else 0
218
+ from .annotation_names import name_extent
219
+ side_name_h=max((name_extent(ha,p,label) for ha in p.left_annotations+p.right_annotations for label in (list(ha.df.columns) if isinstance(ha,SimpleAnnotation) and ha.df is not None else [ha.label or ''])),default=0)
220
+ top_name_w=max((name_extent(ha,p,label) for ha in p.top_annotations+p.bottom_annotations for label in (list(ha.df.columns) if isinstance(ha,SimpleAnnotation) and ha.df is not None else [ha.label or ''])),default=0)
221
+
222
+ legend=legend_entries(p)
223
+ from .legends import heatmap_legend_scenes
224
+ legend_scenes,legend_objects=heatmap_legend_scenes(p,legend_entries(p,with_source=True),body_w,body_h)
225
+ if getattr(p,'_composition_no_legends',False):legend_scenes=[]
226
+ # Bottom-band labels are drawn to the right by the original protocol.
227
+ bottom_label_w=max((text_width(c,a.pt(10),family=a.font_family) for h in p.bottom_annotations for c in (h.df.columns if h.df is not None else [h.label or ''])),default=0)
228
+ full_w=x+body_w+right_extent+right_names+(gap if right_names else 0)+max(bottom_label_w+gap,top_name_w,axis_space['right'])+pad
229
+ full_h=y+body_h+bottom_extent+max(bottom_names,side_name_h,axis_space['bottom'])+(gap if bottom_names or side_name_h or axis_space['bottom'] else 0)+pad
230
+ from .annotation_names import figure_name_bounds
231
+ name_bounds=figure_name_bounds(p,body_w,body_h,gap)
232
+ if name_bounds is not None:
233
+ minx,miny,maxx,maxy=name_bounds
234
+ dx=max(0.,pad-(x+minx));dy=max(0.,pad-(y+miny))
235
+ x+=dx;y+=dy;full_w+=dx;full_h+=dy
236
+ full_w=max(full_w,x+maxx+pad);full_h=max(full_h,y+maxy+pad)
237
+ row_nodes=move(row_nodes,x+body_w+(0 if inside_names else right_extent)+gap if p.row_names_side=='right' else x-(0 if inside_names else left_extent)-gap,y)
238
+ col_nodes=move(col_nodes,x,y+body_h+bottom_extent+gap if p.column_names_side=='bottom' else y-top_extent-gap)
239
+ rb=union(envelope(n,a.font_family) for n in row_nodes)
240
+ cb=union(envelope(n,a.font_family) for n in col_nodes)
241
+ if rb and cb and min(rb[2],cb[2])>max(rb[0],cb[0]) and min(rb[3],cb[3])>max(rb[1],cb[1]):
242
+ shift=rb[1]-gap-cb[3] if p.column_names_side=='top' else rb[3]+gap-cb[1]
243
+ col_nodes=move(col_nodes,0,shift)
244
+ cb=union(envelope(n,a.font_family) for n in col_nodes)
245
+ title_nodes=[]
246
+ occupied=[(x-left_extent,y-top_extent,x+body_w+right_extent,y+body_h+bottom_extent)]+[box for box in (rb,cb) if box]
247
+ if name_bounds is not None:occupied.append((x+name_bounds[0],y+name_bounds[1],x+name_bounds[2],y+name_bounds[3]))
248
+ cluster_nodes=[]
249
+ cluster_labels=getattr(p,'_col_cluster_labels',None)
250
+ if p.show_cluster_labels and p.cluster_label_fontsize>0 and cluster_labels is not None and len(cluster_labels):
251
+ from .name_layout import fit_text
252
+ top_edge=min(b[1] for b in occupied)
253
+ for begin,end in p._get_bounds(nc,p.col_breaks):
254
+ text=fit_text(str(cluster_labels[begin]),p.cluster_label_fontsize,a.mm(60),a.font_family)
255
+ xx=x+_coord(begin,p._cell_w,p.col_breaks,slice_gaps(p,'column'))+(end-begin)*p._cell_w/2
256
+ node=dict(text=text,x=xx,y=0.,size=p.cluster_label_fontsize,anchor='start',rotation=-90)
257
+ box=envelope(node,a.font_family);node['y']=top_edge-gap-box[3]
258
+ cluster_nodes.append(node)
259
+ occupied.extend(envelope(n,a.font_family) for n in cluster_nodes)
260
+ from .titles import title_nodes as resolve_titles
261
+ title_nodes=resolve_titles(p,x,y,body_w,body_h,occupied)
262
+ text_bounds=union(envelope(n,a.font_family) for n in row_nodes+col_nodes+title_nodes+cluster_nodes)
263
+ if text_bounds is not None:
264
+ minx,miny,maxx,maxy=text_bounds
265
+ dx=max(0.,pad-minx);dy=max(0.,pad-miny)
266
+ row_nodes=move(row_nodes,dx,dy);col_nodes=move(col_nodes,dx,dy);title_nodes=move(title_nodes,dx,dy)
267
+ cluster_nodes=move(cluster_nodes,dx,dy)
268
+ x+=dx;y+=dy;full_w=max(full_w+dx,maxx+dx+pad);full_h=max(full_h+dy,maxy+dy+pad)
269
+ # Pack outside the measured content, including diagonal labels/titles.
270
+ content=[(x-left_extent-axis_space['left'],y-top_extent-axis_space['top'],x+body_w+right_extent+axis_space['right'],y+body_h+bottom_extent+axis_space['bottom'])]
271
+ content.extend(envelope(n,a.font_family) for n in row_nodes+col_nodes+title_nodes+cluster_nodes)
272
+ if name_bounds is not None:content.append((x+name_bounds[0],y+name_bounds[1],x+name_bounds[2],y+name_bounds[3]))
273
+ cbounds=union(content);vertical=[]
274
+ for scene in legend_scenes:
275
+ side=scene['side'];_,_,sw,sh=scene['box']
276
+ if side in ('left','right'):
277
+ sx=cbounds[0]-a.mm(2)-sw if side=='left' else cbounds[2]+a.mm(2)
278
+ sy=y+body_h/2-sh/2;scene['box']=(sx,sy,sw,sh);vertical.append(scene['box'])
279
+ for scene in legend_scenes:
280
+ side=scene['side'];_,_,sw,sh=scene['box']
281
+ if side in ('top','bottom'):
282
+ top=min([cbounds[1]]+[b[1] for b in vertical]);bottom=max([cbounds[3]]+[b[1]+b[3] for b in vertical])
283
+ scene['box']=(x+body_w/2-sw/2,top-a.mm(2)-sh if side=='top' else bottom+a.mm(2),sw,sh)
284
+ all_bounds=union(content+[(sx,sy,sx+sw,sy+sh) for sx,sy,sw,sh in (s['box'] for s in legend_scenes)])
285
+ dx=max(0.,pad-all_bounds[0]);dy=max(0.,pad-all_bounds[1])
286
+ row_nodes=move(row_nodes,dx,dy);col_nodes=move(col_nodes,dx,dy);title_nodes=move(title_nodes,dx,dy);cluster_nodes=move(cluster_nodes,dx,dy)
287
+ x+=dx;y+=dy;full_w=max(full_w+dx,all_bounds[2]+dx+pad);full_h=max(full_h+dy,all_bounds[3]+dy+pad)
288
+ for scene in legend_scenes:
289
+ sx,sy,sw,sh=scene['box'];scene['box']=(sx+dx,sy+dy,sw,sh)
290
+ if not getattr(p,'_r_layout_trial',False) and (full_w*full_h>p.max_canvas_pixels or max(full_w,full_h)>p.max_canvas_dimension):
291
+ if opt.get('dpi') is not None or opt.get('output_width') is not None or p.autoscale:
292
+ raise ValueError(f'canvas {math.ceil(full_w)}x{math.ceil(full_h)} exceeds pixel budget; lower dpi/output_width or increase max_canvas_pixels/max_canvas_dimension')
293
+ factor=min(math.sqrt(p.max_canvas_pixels/(full_w*full_h)),p.max_canvas_dimension/max(full_w,full_h))*.99
294
+ newdpi=p.dpi*factor
295
+ if newdpi<12:raise ValueError('labels/legends cannot fit canvas budget; select fewer legend entries or increase budget')
296
+ warnings.warn(f'canvas budget: reducing export resolution from {p.dpi:g} to {newdpi:g} DPI',UserWarning,stacklevel=2)
297
+ p.dpi=newdpi;p._appearance=Appearance(newdpi,a.body_width_mm,a.font_family)
298
+ if getattr(p,'_r_component_constraints',None) and hasattr(p,'_shared_body'):
299
+ p._shared_body=tuple(value*factor for value in p._shared_body)
300
+ return compute_layout(p)
301
+ p.canvas_width=math.ceil(full_w);p.canvas_height=math.ceil(full_h)
302
+ layout=dict(n_rows=nr,n_cols=nc,cell_w=p._cell_w,cell_h=p._cell_h,heatmap_w=body_w,heatmap_h=body_h,top_h=top,bottom_h=bottom,left_w=left,right_w=right,left_extent=left_extent,right_extent=right_extent,top_extent=top_extent,bottom_extent=bottom_extent,heatmap_x=x,heatmap_y=y,dendro_size=max(rd,cd),row_dendro_w=rd,col_dendro_h=cd,row_names_w=rnw,full_w=p.canvas_width,full_h=p.canvas_height,row_label_indices=rids,col_label_indices=cids,legend_x=x+body_w+right_extent+right_names+(gap if right_names else 0)+a.mm(2),legend_entries=legend)
303
+ layout.update(row_name_nodes=row_nodes,column_name_nodes=col_nodes,title_nodes=title_nodes,cluster_label_nodes=cluster_nodes)
304
+ layout.update(legend_scenes=legend_scenes,legend_objects=legend_objects)
305
+ layout['heatmap_component_box']=(cbounds[0]+dx,cbounds[1]+dy,cbounds[2]-cbounds[0],cbounds[3]-cbounds[1])
306
+ if legend_scenes:layout['legend_x']=legend_scenes[0]['box'][0]
307
+ for key,nodes in [('row_names_box',row_nodes),('column_names_box',col_nodes)]:
308
+ box=union(envelope(n,a.font_family) for n in nodes)
309
+ layout[key]=(box[0],box[1],box[2]-box[0],box[3]-box[1]) if box else (x,y,0.,0.)
310
+ layout['row_dend_box']=(x-left_extent+rp if p.row_dend_side=='left' else x+body_w+right_extent-rd-rp,y,rd,body_h)
311
+ layout['column_dend_box']=(x,y-top_extent+cp if p.column_dend_side=='top' else y+body_h+bottom_extent-cd-cp,body_w,cd)
312
+ for axis,padding in [('row',rp),('column',cp)]:
313
+ dx,dy,dw,dh=layout[axis+'_dend_box']
314
+ layout[axis+'_dend_component_box']=(dx-padding,dy-padding,dw+2*padding,dh+2*padding)
315
+ p._last_layout=layout
316
+ return layout
317
+
318
+
319
+ def legend_entries(p,with_source=False):
320
+ entries=[]
321
+ seen_bar_legends=set()
322
+ for h in p.all_annotations:
323
+ def entry(kind,title,value):return (kind,title,value,h) if with_source else (kind,title,value)
324
+ if not getattr(h,'_show_legend',True):continue
325
+ if hasattr(h,'legend_colors'):
326
+ from matplotlib.colors import to_hex
327
+ identity=(str(h.label or 'Type'),tuple((str(k),to_hex(v)) for k,v in h.legend_colors.items()))
328
+ if identity in seen_bar_legends:continue
329
+ seen_bar_legends.add(identity)
330
+ entries.append(entry('title',str(h.label or 'Type'),None))
331
+ entries.extend(entry('key',str(k),to_hex(v)) for k,v in h.legend_colors.items())
332
+ continue
333
+ if not isinstance(h,SimpleAnnotation) or h.df is None:continue
334
+ if not getattr(h,'_show_legend',True):continue
335
+ for col in h.df.columns:
336
+ if hasattr(h,'color_mappings'):
337
+ entries.append(entry('continuous',str(col),h.color_mappings[col]))
338
+ continue
339
+ series=h.df[col]
340
+ observed=set(series.dropna().astype(str))
341
+ vals=[str(v) for v in series.cat.categories if getattr(h,'_include_unused_levels',False) or str(v) in observed] if isinstance(series.dtype,pd.CategoricalDtype) else sorted(observed)
342
+ colors=p._map_colors(np.asarray(vals),h.colors,palette=h.cmap)
343
+ entries.append(entry('title',str(col),None))
344
+ entries.extend(entry('key',v,'#%02x%02x%02x'%tuple(reversed(c))) for v,c in zip(vals,colors))
345
+ return entries
346
+
347
+
348
+ def draw_simple_annotation(ha,f,start_x,start_y,pixel,bounds,gap,direction,p):
349
+ from matplotlib.colors import to_rgb
350
+ from .slice_geometry import gap_total,gap_at
351
+ vertical=direction in ('left','right')
352
+ cursor=start_x if vertical else start_y
353
+ height=p._annot_height(ha)
354
+ columns=list(ha.df.columns) if ha.df is not None else [None]
355
+ if direction in ('up','left'):columns=columns[::-1]
356
+ span=sum((e-b)*pixel for b,e in bounds)+gap_total(gap,max(0,len(bounds)-1))
357
+ for col in columns:
358
+ values=ha.df[col].to_numpy() if col is not None else np.nanmean(p._matrix_sorted,axis=1 if vertical else 0)
359
+ if hasattr(ha,'color_mappings'):
360
+ rgb=ha.color_mappings[col](values,bytes=True)
361
+ else:
362
+ rgb=np.asarray(p._map_colors(np.asarray(values).astype(str),ha.colors,palette=ha.cmap),dtype=np.uint8)[:,::-1]
363
+ if hasattr(ha,'na_col'):
364
+ rgb[pd.isna(values)]=np.rint(np.asarray(to_rgb(ha.na_col))*255).astype(np.uint8)
365
+ along=start_y if vertical else start_x
366
+ cross=cursor-height if direction in ('up','left') else cursor
367
+ for slice_index,(b,e) in enumerate(bounds):
368
+ length=(e-b)*pixel
369
+ n=max(1,math.ceil(length))
370
+ selected=np.minimum(e-1,b+((np.arange(n)+.5)*(e-b)/n).astype(int))
371
+ data=rgb[selected]
372
+ arr=np.repeat(data[:,None,:],max(1,round(height)),axis=1) if vertical else np.repeat(data[None,:,:],max(1,round(height)),axis=0)
373
+ arr=np.ascontiguousarray(arr[:,:,::-1])
374
+ xx,yy,ww,hh=(cross,along,height,length) if vertical else (along,cross,length,height)
375
+ ok,buf=cv2.imencode('.png',arr,[cv2.IMWRITE_PNG_COMPRESSION,1])
376
+ if not ok:raise RuntimeError('annotation PNG encoding failed')
377
+ if hasattr(f,'write_image'):f.write_image(xx,yy,ww,hh,buf.tobytes())
378
+ else:
379
+ b64=base64.b64encode(buf).decode()
380
+ f.write(f'<image x="{xx}" y="{yy}" width="{ww}" height="{hh}" preserveAspectRatio="none" href="data:image/png;base64,{b64}" xlink:href="data:image/png;base64,{b64}"/>')
381
+ gp=getattr(ha,'_simple_gp',{})
382
+ markers=getattr(ha,'_simple_pch',None)
383
+ if gp or markers is not None:
384
+ from .graphics import gp_value,draw_marker,color
385
+ identities=getattr(ha,'_graphical_ids',None)
386
+ for item in range(b,e):
387
+ index=int(identities.get(str(ha.df.index[item]),item)) if identities is not None else item
388
+ pos=along+(item-b)*pixel
389
+ bx,by,bw,bh=(cross,pos,height,pixel) if vertical else (pos,cross,pixel,height)
390
+ if gp:
391
+ stroke=color(gp_value(gp,'col',index))
392
+ f.write(f'<rect x="{bx}" y="{by}" width="{bw}" height="{bh}" fill="none" stroke="{stroke}" stroke-width="{p._appearance.pt(float(gp_value(gp,"lwd",index,1)))}"/>')
393
+ if markers is not None:
394
+ marker=markers[index%len(markers)]
395
+ if marker is not None and not pd.isna(marker):
396
+ style=ha._point_gp
397
+ draw_marker(f,bx+bw/2,by+bh/2,p._appearance.mm(ha._simple_pt_size)/2,marker,col=gp_value(style,'col',index,'black'),fill=gp_value(style,'fill',index),linewidth=p._appearance.pt(float(gp_value(style,'lwd',index,.75))))
398
+ if ha.element_border:
399
+ for i in range(e-b+1):
400
+ pos=along+i*pixel
401
+ x1,y1,x2,y2=(cross,pos,cross+height,pos) if vertical else (pos,cross,pos,cross+height)
402
+ f.write(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{ha.element_border_color or p.heatmap_element_border_color}" stroke-width="{ha.element_border_width if ha.element_border_width is not None else p.heatmap_element_border_width}"/>')
403
+ if getattr(ha,'border',False):
404
+ f.write(f'<rect x="{xx}" y="{yy}" width="{ww}" height="{hh}" fill="none" stroke="#000000" stroke-width="{p._appearance.pt(.75)}"/>')
405
+ along+=length+gap_at(gap,slice_index)
406
+ from .annotation_names import draw_name
407
+ label=str(col if col is not None else ha.label or '')
408
+ draw_name(ha,f,p,start_y if vertical else start_x,(start_y if vertical else start_x)+span,cross,height,vertical,label)
409
+ cursor+=(-1 if direction in ('up','left') else 1)*(height+p._annot_gap_px)
410
+
411
+
412
+ def nice_ticks(lo,hi,n=5):
413
+ if hi<=lo:return np.array([lo])
414
+ raw=(hi-lo)/max(1,n-1)
415
+ exponent=10**math.floor(math.log10(raw))
416
+ normalized=raw/exponent
417
+ step=min((1,2,2.5,5,10),key=lambda v:abs(v-normalized))*exponent
418
+ ticks=np.arange(math.ceil(lo/step),math.floor(hi/step)+.5)*step
419
+ ticks[np.abs(ticks)<step*1e-10]=0
420
+ return ticks if len(ticks) else np.array([lo,hi])
421
+
422
+
423
+ def primary_legend_geometry(p):
424
+ """Compatibility measurement wrapper over the common legend engine."""
425
+ from .legends import heatmap_legend_scenes
426
+ a=p._appearance;layout=getattr(p,'_last_layout',None) or {}
427
+ _,objects=heatmap_legend_scenes(p,[],layout.get('heatmap_w',a.mm(a.body_width_mm)),layout.get('heatmap_h',a.mm(60)))
428
+ primary=next((lg for kind,lg,side in objects if kind=='heatmap'),None)
429
+ if primary is None:return dict(width=0,height=0,size=p.legend_fontsize,bw=0,bh=0)
430
+ l=primary._layout(a)
431
+ return dict(width=l['width'],height=l['height'],size=a.pt(primary.label_size),bw=a.mm(primary.grid_width),bh=a.mm(primary.legend_height))
432
+
433
+
434
+ def _coord(i,cell,breaks,gap):
435
+ from .slice_geometry import gap_offset
436
+ return i*cell+gap_offset(gap,int(np.searchsorted(breaks,i,side='right')))
437
+
438
+
439
+ def _write_color_tile(f, x, y, width, height, pixels):
440
+ ok, enc = cv2.imencode('.png', pixels, [cv2.IMWRITE_PNG_COMPRESSION, 1])
441
+ if not ok:
442
+ raise RuntimeError('colour tile PNG encoding failed')
443
+ if hasattr(f, 'write_image'):
444
+ f.write_image(x, y, width, height, enc.tobytes())
445
+ else:
446
+ b64 = base64.b64encode(enc).decode('ascii')
447
+ f.write(f'<image x="{x}" y="{y}" width="{width}" height="{height}" preserveAspectRatio="none" href="data:image/png;base64,{b64}" xlink:href="data:image/png;base64,{b64}"/>')
448
+
449
+
450
+ def write_blocks(p,f,x,y,cw,ch):
451
+ if getattr(p,'_dot_heatmap',False):
452
+ from .dot_heatmap import write_dots
453
+ return write_dots(p,f,x,y,cw,ch)
454
+ categorical=getattr(p,'_category_colors',None) is not None
455
+ # Categorical codes use their exact palette below; sampling a continuous
456
+ # lookup table would evaluate arbitrary fractions as category identifiers.
457
+ lut=None if categorical else p._generate_lut().reshape(-1,3)
458
+ lo,hi=float(p.vmin),float(p.vmax)
459
+ if hi<=lo:hi=lo+1e-6
460
+ if categorical:
461
+ from matplotlib.colors import to_rgb
462
+ palette=np.asarray([np.rint(np.asarray(to_rgb(p._category_colors.get(k,'grey')))[::-1]*255).astype(np.uint8) for k in range(max(p._category_colors)+1)])
463
+ mask = getattr(p, '_cell_mask', None)
464
+ states = None if mask is None else mask.displayed(p)
465
+ if mask is not None:
466
+ state_colors = mask.colors(p)
467
+ state_bgr = [tuple(bytes.fromhex(color[1:])[::-1]) for color in state_colors]
468
+ raster=p.rasterized is not False
469
+ quality=getattr(p,'_r_raster_quality',1.)
470
+ from .r_raster import resolved_reducer, sampled_tile
471
+ reducer=resolved_reducer(p)
472
+ sampled_pixels=0
473
+ cuda = None
474
+ p.render_report.update(gpu_tiles=0,cpu_tiles=0,uploaded_bytes=0,max_upload_bytes=0,fallback_reason=None)
475
+ if p.render_backend == 'cuda' and raster and not categorical and reducer is False:
476
+ from .gpu_raster import CudaRaster
477
+ cuda = CudaRaster(p.render_report)
478
+ elif p.render_backend == 'cuda':
479
+ p.render_report['fallback_reason']='categorical, vector or reducer output uses the existing CPU path'
480
+ # Explicit vector override remains available; only dense output defaults to raster.
481
+ for r0,r1 in p._get_bounds(p._matrix_sorted.shape[0],p.row_breaks):
482
+ by=y+_coord(r0,ch,p.row_breaks,slice_gaps(p,'row'))
483
+ for c0,c1 in p._get_bounds(p._matrix_sorted.shape[1],p.col_breaks):
484
+ bx=x+_coord(c0,cw,p.col_breaks,slice_gaps(p,'column'))
485
+ w=(c1-c0)*cw;h=(r1-r0)*ch
486
+ if not raster:
487
+ write_grid = getattr(f, 'write_vector_grid', None)
488
+ if write_grid is not None and not categorical and mask is None and not p.heatmap_element_border:
489
+ if write_grid(bx, by, cw, ch, p._matrix_sorted[r0:r1, c0:c1], lo, hi, lut[:, ::-1]) is not False:
490
+ continue
491
+ for r in range(r0,r1):
492
+ for c in range(c0,c1):
493
+ state = 0 if states is None else states[r, c]
494
+ if state:
495
+ color = state_colors[state - 1]
496
+ else:
497
+ v=p._matrix_sorted[r,c]
498
+ idx=0 if not np.isfinite(v) else int(np.clip((v-lo)/(hi-lo)*254+1,1,255))
499
+ rgb=palette[int(v),::-1] if categorical and np.isfinite(v) else lut[idx,::-1]
500
+ color='#%02x%02x%02x'%tuple(rgb)
501
+ xx=bx+(c-c0)*cw;yy=by+(r-r0)*ch
502
+ border=f' stroke="{p.heatmap_element_border_color}" stroke-width="{p.heatmap_element_border_width}"' if p.heatmap_element_border else ''
503
+ f.write(f'<rect x="{xx}" y="{yy}" width="{cw}" height="{ch}" fill="{color}"{border}/>')
504
+ else:
505
+ dw=max(1,math.ceil(w));dh=max(1,math.ceil(h))
506
+ if quality!=1:
507
+ dw=math.ceil(dw*quality);dh=math.ceil(dh*quality)
508
+ sampled_pixels+=dw*dh
509
+ if max(dw,dh)>p.max_canvas_dimension or sampled_pixels>p.max_canvas_pixels:
510
+ raise MemoryError('raster_quality exceeds embedded raster pixel budget')
511
+ # Gather only one bounded display tile before color expansion.
512
+ tile_edge=getattr(p,'_source_tile_edge',1024)
513
+ if reducer is True or isinstance(reducer,str) and reducer=='area':
514
+ budget=min(getattr(p,'workspace_bytes',64*1024**2),64*1024**2)
515
+ tile_edge=min(tile_edge,max(1,math.isqrt(budget//64)))
516
+ for ty in range(0,dh,tile_edge):
517
+ th=min(tile_edge,dh-ty)
518
+ rr=np.minimum(r1-1,r0+((np.arange(ty,ty+th)+.5)*(r1-r0)/dh).astype(int))
519
+ for tx in range(0,dw,tile_edge):
520
+ tw=min(tile_edge,dw-tx)
521
+ cc=np.minimum(c1-1,c0+((np.arange(tx,tx+tw)+.5)*(c1-c0)/dw).astype(int))
522
+ indices = cuda.indices(p._matrix_sorted,rr,cc,lo,hi) if cuda is not None else None
523
+ if indices is not None:
524
+ data = None
525
+ elif quality!=1 or reducer is not False:
526
+ data=sampled_tile(p,(r0,r1,c0,c1),(dh,dw),ty,th,tx,tw,reducer=reducer)
527
+ else:data=p._matrix_sorted[np.ix_(rr,cc)]
528
+ px=bx+tx*w/dw;py=by+ty*h/dh;pw=tw*w/dw;ph=th*h/dh
529
+ tile_states = None if states is None else states[np.ix_(rr, cc)]
530
+ has_states = tile_states is not None and tile_states.any()
531
+ if categorical:
532
+ pixels=palette[np.clip(np.nan_to_num(data,nan=0).astype(int),0,len(palette)-1)]
533
+ elif indices is None:
534
+ p.render_report['cpu_tiles']+=1
535
+ normalized=np.clip(np.nan_to_num((data-lo)/(hi-lo),nan=0),0,1)
536
+ indices=(normalized*254+1).astype(np.uint8)
537
+ indices[~np.isfinite(data)]=0
538
+ if categorical or has_states:
539
+ if not categorical:
540
+ pixels = lut[indices]
541
+ if has_states:
542
+ for state, color in enumerate(state_bgr, start=1):
543
+ pixels[tile_states == state] = color
544
+ _write_color_tile(f, px, py, pw, ph, pixels)
545
+ elif hasattr(f,'write_indexed_raster'):
546
+ f.write_indexed_raster(px,py,pw,ph,indices,lut[:,::-1])
547
+ else:
548
+ ok,enc=cv2.imencode('.png',lut[indices],[cv2.IMWRITE_PNG_COMPRESSION,1])
549
+ if not ok:raise RuntimeError('OpenCV PNG encoding failed')
550
+ b64=base64.b64encode(enc).decode('ascii')
551
+ f.write(f'<image x="{px}" y="{py}" width="{pw}" height="{ph}" preserveAspectRatio="none" style="image-rendering:pixelated" href="data:image/png;base64,{b64}" xlink:href="data:image/png;base64,{b64}"/>')
552
+ if p.heatmap_element_border:
553
+ # Grid is vector geometry; do not expand a source-sized color image.
554
+ color=p.heatmap_element_border_color;sw=p.heatmap_element_border_width
555
+ for c in range(c1-c0+1):
556
+ xx=bx+c*cw;f.write(f'<line x1="{xx}" x2="{xx}" y1="{by}" y2="{by+h}" stroke="{color}" stroke-width="{sw}"/>')
557
+ for r in range(r1-r0+1):
558
+ yy=by+r*ch;f.write(f'<line x1="{bx}" x2="{bx+w}" y1="{yy}" y2="{yy}" stroke="{color}" stroke-width="{sw}"/>')
559
+ if p.cluster_border_width>0:f.write(f'<rect x="{bx}" y="{by}" width="{w}" height="{h}" fill="none" stroke="black" stroke-width="{p.cluster_border_width}"/>')
560
+ border=p._visual_options.get('body_border',False)
561
+ if border is not False and border is not None:
562
+ from .graphics import color
563
+ gp=p._body_border_gp;stroke=color(border if isinstance(border,str) else gp.get('col','black'))
564
+ f.write(f'<rect x="{bx}" y="{by}" width="{w}" height="{h}" fill="none" stroke="{stroke}" stroke-width="{p._appearance.pt(float(gp.get("lwd",.75)))}"/>')
565
+ write_callbacks(p,f,x,y,cw,ch,cell_states=states)
566
+
567
+
568
+ def write_callbacks(p,f,x,y,cw,ch,*,cell_states=None):
569
+ callback=p._visual_options.get('layer_fun')
570
+ if callback is not None:
571
+ nr,nc=p._matrix_sorted.shape
572
+ ii,jj=np.indices((nr,nc))
573
+ if cell_states is None:
574
+ callback(jj.ravel(),ii.ravel(),f,p._last_layout)
575
+ else:
576
+ visible = cell_states[ii, jj] == 0
577
+ if visible.any():
578
+ callback(jj[visible], ii[visible], f, p._last_layout)
579
+ cell=p._visual_options.get('cell_fun')
580
+ if cell is not None:
581
+ for i in range(p._matrix_sorted.shape[0]):
582
+ for j in range(p._matrix_sorted.shape[1]):
583
+ if cell_states is not None and cell_states[i, j]:
584
+ continue
585
+ xx=x+_coord(j,cw,p.col_breaks,slice_gaps(p,'column'));yy=y+_coord(i,ch,p.row_breaks,slice_gaps(p,'row'))
586
+ cell(j,i,xx+cw/2,yy+ch/2,cw,ch,f)
587
+ from .slice_drawing import draw_slices
588
+ draw_slices(p,f,x,y,cw,ch)
589
+
590
+
591
+ def _text(f,x,y,text,size,anchor='start',bold=False,rotation=None,color=None,italic=False,family=None):
592
+ if size==0:return
593
+ rot=f' transform="rotate({rotation},{x},{y})"' if rotation is not None else ''
594
+ fill=(f' fill="{escape(color)}"' if color is not None else '')+(' font-style="italic"' if italic else '')
595
+ if family is not None:fill+=' font-family="'+escape(family,{'"':'&quot;'})+'"'
596
+ f.write(f'<text x="{x}" y="{y}"{fill} font-size="{size}" text-anchor="{anchor}" font-weight="{"bold" if bold else "normal"}" dominant-baseline="middle"{rot}>{escape(str(text))}</text>')
597
+
598
+
599
+ def _fit(text,size,maxwidth,p):
600
+ from .name_layout import fit_text
601
+ return fit_text(text,size,maxwidth,p._appearance.font_family)
602
+
603
+
604
+ class FontSink:
605
+ """Normalize legacy annotation font fragments without changing their APIs."""
606
+ def __init__(self,sink,family,plotter=None):self.sink=sink;self.family=family;self.plotter=plotter
607
+ def write(self,fragment):
608
+ return self.sink.write(fragment.replace('font-family="Arial"',f'font-family="{self.family}"'))
609
+ def __getattr__(self,name):return getattr(self.sink,name)
610
+
611
+
612
+ def draw_body(p,f,layout):
613
+ a=p._appearance
614
+ f=FontSink(f,a.font_family,p)
615
+ x,y=layout['heatmap_x'],layout['heatmap_y'];w,h=layout['heatmap_w'],layout['heatmap_h']
616
+ cw,ch=layout['cell_w'],layout['cell_h'];gap=a.mm(1)
617
+ f.write(f'<g font-family="{a.font_family}" fill="#000000">')
618
+ f.write(f'<rect x="0" y="0" width="{layout["full_w"]}" height="{layout["full_h"]}" fill="white"/>')
619
+ if not getattr(p,"_annotation_only",False):write_blocks(p,f,x,y,cw,ch)
620
+ offsets=getattr(p,'_annotation_offsets',{})
621
+ for side,args in [('top',(x,y-gap,cw,layout['n_cols'],'up')),('bottom',(x,y+h+gap,cw,layout['n_cols'],'down')),('left',(x-gap-offsets.get('left',0),y,ch,layout['n_rows'],'left')),('right',(x+w+gap+offsets.get('right',0),y,ch,layout['n_rows'],'right'))]:
622
+ from .annotation_layout import draw as draw_bands
623
+ draw_bands(p,f,getattr(p,side+'_annotations'),*args)
624
+ from .graphics import color,gp_value
625
+ from .tree_styles import branch_options
626
+ if layout['col_dendro_h']:
627
+ gp=p._dend_gp['column']
628
+ f.write(f'<g stroke="{color(gp_value(gp,"col",0,"black"))}" stroke-width="{a.pt(gp_value(gp,"lwd",0,.75))}" fill="none">')
629
+ dx,dy,dw,dh=layout['column_dend_box']
630
+ p._write_dendro_paths(f,p._display_col_linkage,dw,dh,p.column_dend_side,dx,dy,cell_size=cw,breaks=p.col_breaks,gap_pixels=slice_gaps(p,'column'),**branch_options(p,"column"))
631
+ f.write('</g>')
632
+ if layout['row_dendro_w']:
633
+ gp=p._dend_gp['row']
634
+ f.write(f'<g stroke="{color(gp_value(gp,"col",0,"black"))}" stroke-width="{a.pt(gp_value(gp,"lwd",0,.75))}" fill="none">')
635
+ dx,dy,dw,dh=layout['row_dend_box']
636
+ p._write_dendro_paths(f,p._display_row_linkage,dw,dh,p.row_dend_side,dx,dy,cell_size=ch,breaks=p.row_breaks,gap_pixels=slice_gaps(p,'row'),**branch_options(p,"row"))
637
+ f.write('</g>')
638
+ for node in layout['row_name_nodes']+layout['column_name_nodes']+layout['cluster_label_nodes']+layout['title_nodes']:
639
+ from .titles import draw_title
640
+ draw_title(p,f,node)
641
+ for scene in layout['legend_scenes']:
642
+ sx,sy,_,_=scene['box'];scene['packed']._draw(f,sx,sy,a,scene['layout'])
643
+ from .decorations import render_decorations
644
+ render_decorations(p,f)
645
+ post=getattr(p,'_post_fun',None)
646
+ if post is not None:post(p,f,layout)
647
+ f.write('</g>')
648
+ return layout['full_w'],layout['full_h']
649
+
650
+
651
+ def _draw_legend_subset(p,f,x,y,entries,kind=None):
652
+ from .legends import heatmap_legend_scenes,PackedLegends
653
+ layout=p._last_layout
654
+ _,objects=heatmap_legend_scenes(p,entries,layout['heatmap_w'],layout['heatmap_h'])
655
+ legends=[lg for k,lg,side in objects if kind is None or k==kind]
656
+ if legends:
657
+ packed=PackedLegends(*legends);l=packed._layout(p._appearance,padding_mm=0)
658
+ packed._draw(f,x,y,p._appearance,l)
659
+
660
+
661
+ def draw_legend(p,f,x,y,entries):
662
+ return _draw_legend_subset(p,f,x,y,entries)
663
+
664
+
665
+ def draw_annotation_legends(p,f,x,y,entries):
666
+ return _draw_legend_subset(p,f,x,y,entries,kind='annotation')
667
+
668
+
669
+ def render_svg(p,output_path=None):
670
+ layout=compute_layout(p)
671
+ f=io.StringIO();w,h=layout['full_w'],layout['full_h']
672
+ family=p._appearance.font_family
673
+ f.write(f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{w/p.dpi*25.4}mm" height="{h/p.dpi*25.4}mm" viewBox="0 0 {w} {h}" font-family="{family}">')
674
+ draw_body(p,f,layout)
675
+ f.write('</svg>')
676
+ return f.getvalue(),w,h
677
+
678
+
679
+ def save(p,output_path,fmt=None):
680
+ path=Path(output_path)
681
+ fmt=(fmt or path.suffix.lstrip('.') or 'svg').lower()
682
+ if fmt not in ('svg','png','jpg','jpeg','tiff','tif','pdf'):raise ValueError(f'Unsupported format: {fmt}')
683
+ path.parent.mkdir(parents=True,exist_ok=True)
684
+ if fmt=='svg':
685
+ if p.rasterized is False or getattr(p, '_dot_heatmap', False):
686
+ from .streaming_svg import save_vector_svg
687
+ layout=compute_layout(p)
688
+ save_vector_svg(path,layout['full_w'],layout['full_h'],p.dpi,p._appearance.font_family,
689
+ lambda sink: draw_body(p,sink,layout))
690
+ return
691
+ svg,_,_=render_svg(p,str(path));path.write_text(svg,encoding='utf-8');return
692
+ layout=compute_layout(p);w,h=layout['full_w'],layout['full_h']
693
+ if fmt=='pdf':
694
+ if p.rasterized is False or getattr(p, '_dot_heatmap', False):
695
+ from .streaming_pdf import save_vector_pdf
696
+ save_vector_pdf(path, w, h, p.dpi, p._appearance.font_family, lambda sink: draw_body(p, sink, layout))
697
+ return
698
+ from .unicode_pdf import UnicodePdfSink
699
+ sink=UnicodePdfSink(w,h,p.dpi,p._appearance.font_family)
700
+ draw_body(p,sink,layout);sink.finalize(str(path),w,h)
701
+ else:
702
+ from .png_renderer import OrderedPngSink
703
+ sink=OrderedPngSink(w,h)
704
+ sink.font_family=p._appearance.font_family
705
+ sink.dpi=p.dpi
706
+ if p.png_compression is not None:sink.png_compression=p.png_compression
707
+ draw_body(p,sink,layout);sink.finalize(str(path),w,h,fmt=fmt)