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/api.py ADDED
@@ -0,0 +1,861 @@
1
+ """Python composition API using the existing numerical engine and fast sinks.
2
+
3
+ R-style constructor names are mapped explicitly. R graphical-parameter/unit
4
+ objects are not accepted as Python objects; unsupported keywords raise errors.
5
+ """
6
+ import copy
7
+ import io
8
+ from pathlib import Path
9
+ from dataclasses import fields
10
+ from xml.sax.saxutils import escape
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ from matplotlib.colors import to_rgb
15
+
16
+ from .renderer import ClusterMapPlotter, _generate_distinct_colors
17
+ from .annotation import AnnotationBase, SimpleAnnotation, ColorAnnotation, ExpressionAnnotation, BoxplotAnnotation
18
+ from .config import HeatmapConfig
19
+ from .style import ColorMapping, Appearance
20
+
21
+
22
+ class _DefaultAnnotationNA(str):
23
+ """Keep the visible grey default while detecting an explicit NA override."""
24
+
25
+ _DEFAULT_ANNOTATION_NA = _DefaultAnnotationNA('grey')
26
+
27
+
28
+ class HeatmapAnnotation(list):
29
+ """Collection of simple tracks and custom annotation objects."""
30
+ def __init__(self,df=None,col=None,which='column',side=None,na_col=_DEFAULT_ANNOTATION_NA,show_legend=True,show_annotation_name=True,border=False,annotation_name_gp=None,annotation_name_rot=None,annotation_name_offset=1,annotation_legend_param=None,simple_anno_size=None,annotation_height=None,annotation_width=None,gap=None,annotation_label=None,annotation_name_side=None,height=None,width=None,gp=None,annotation_name_align=False,discrete_palette=None,**tracks):
31
+ super().__init__()
32
+ from .graphics import validate_gp,gp_value
33
+ reserved=set(tracks)&{'name','simple_anno_size_adjust'}
34
+ if reserved:raise TypeError('unsupported HeatmapAnnotation options: '+', '.join(sorted(reserved))+'; data tracks with reserved names can be supplied through df')
35
+ name_gp=validate_gp(annotation_name_gp,{'col','fontsize','fontface','fontfamily'})
36
+ if 'fontfamily' in name_gp:
37
+ family=name_gp['fontfamily'];families=[family] if isinstance(family,str) else list(family) if isinstance(family,(list,tuple,np.ndarray)) else [family]
38
+ if not families or any(not isinstance(v,str) or not v.strip() for v in families):raise ValueError('annotation_name_gp fontfamily must contain nonempty family names')
39
+ if not np.isfinite(annotation_name_offset) or annotation_name_offset<0:raise ValueError('annotation_name_offset must be finite and nonnegative mm')
40
+ side=side or ('left' if which=='row' else 'top')
41
+ self.which=which
42
+ if which not in ('row','column'):raise ValueError('which must be row or column')
43
+ if side not in ('top','bottom','left','right') or (side in ('left','right'))!=(which=='row'):raise ValueError('annotation side conflicts with which')
44
+ if df is not None:
45
+ df=pd.DataFrame(df)
46
+ for c in df:
47
+ if pd.api.types.is_numeric_dtype(df[c]):
48
+ obj=ColorAnnotation(df=df[[c]],color_mappings={c:(col or {}).get(c)},side=side,label=str(c),border=False)
49
+ else:obj=SimpleAnnotation(df=df[[c]],colors=(col or {}).get(c,{}),cmap=discrete_palette,side=side,label=str(c),border=False)
50
+ self.append(obj)
51
+ for name,value in tracks.items():
52
+ if isinstance(value,AnnotationBase):
53
+ obj=copy.copy(value);obj.side=side
54
+ if obj.label is None:
55
+ obj.label=name
56
+ if isinstance(obj,SimpleAnnotation) and obj.df is not None and obj.df.shape[1]==1:
57
+ column=obj.df.columns[0];obj.df=obj.df.rename(columns={column:name})
58
+ if hasattr(obj,'color_mappings'):obj.color_mappings={name:obj.color_mappings[column]}
59
+ else:
60
+ series=value if isinstance(value,pd.Series) else pd.Series(value)
61
+ if pd.api.types.is_numeric_dtype(series):
62
+ obj=ColorAnnotation(df=series.to_frame(name),color_mappings={name:(col or {}).get(name)},side=side,label=name)
63
+ else:obj=SimpleAnnotation(df=series.to_frame(name),colors=(col or {}).get(name,{}),cmap=discrete_palette,side=side,label=name)
64
+ obj._positional=not isinstance(value,pd.Series)
65
+ self.append(obj)
66
+ from collections.abc import Mapping
67
+ if annotation_legend_param is not None:
68
+ if not isinstance(annotation_legend_param,Mapping) or any(not isinstance(v,Mapping) for v in annotation_legend_param.values()):raise TypeError('annotation_legend_param must map track names to parameter mappings')
69
+ unknown=set(annotation_legend_param)-{str(o.label) for o in self}
70
+ if unknown:raise ValueError('unknown annotation legend tracks: '+', '.join(sorted(unknown)))
71
+ from .annotation_layout import _values
72
+ names=[str(obj.label) for obj in self]
73
+ missing=object()
74
+ if show_legend is None:raise TypeError('show_legend must be boolean, vector or mapping')
75
+ if border is None:raise TypeError('border must be boolean, vector or mapping')
76
+ legends=_values(show_legend,names,'show_legend',missing)
77
+ borders=_values(border,names,'border',missing)
78
+ for label,values in [('show_legend',legends),('border',borders)]:
79
+ for value in values:
80
+ if value is not missing and not isinstance(value,(bool,np.bool_)):
81
+ raise TypeError(label+' values must be boolean')
82
+ explicit_na=na_col is not _DEFAULT_ANNOTATION_NA
83
+ na_rgb=np.asarray(to_rgb(na_col))*255
84
+ override_border=not isinstance(border,(bool,np.bool_)) or bool(border)
85
+ for i,obj in enumerate(self):
86
+ obj._annotation_legend_param=copy.deepcopy((annotation_legend_param or {}).get(str(obj.label),{}))
87
+ obj._annotation_name_gp={key:gp_value(name_gp,key,i) for key in name_gp}
88
+ if annotation_name_rot is not None:
89
+ rotation=float(gp_value({'rot':annotation_name_rot},'rot',i))
90
+ if not np.isfinite(rotation):raise ValueError('annotation_name_rot must be finite')
91
+ obj._annotation_name_rot=rotation
92
+ obj._annotation_name_offset=float(annotation_name_offset)
93
+ obj._show_legend=bool(getattr(obj,'_show_legend',True) and (True if legends[i] is missing else legends[i]))
94
+ if not isinstance(show_legend,(bool,np.bool_)) and legends[i] is not missing:obj._show_legend=bool(legends[i])
95
+ if override_border and borders[i] is not missing:
96
+ if not hasattr(obj,'border') and borders[i]:raise ValueError('border requires a track with native border support')
97
+ obj.border=bool(borders[i])
98
+ obj._show_annotation_name=show_annotation_name
99
+ if explicit_na or not hasattr(obj,'na_col'):obj.na_col=str(na_col)
100
+ if explicit_na and hasattr(obj,'color_mappings'):
101
+ obj.color_mappings=copy.deepcopy(obj.color_mappings)
102
+ for mapping in obj.color_mappings.values():mapping.na_color=na_rgb.copy()
103
+ from .annotation_layout import configure
104
+ configure(self,simple_anno_size=simple_anno_size,annotation_height=annotation_height,
105
+ annotation_width=annotation_width,gap=gap,annotation_label=annotation_label,
106
+ annotation_name_side=annotation_name_side,show_annotation_name=show_annotation_name,
107
+ height=height,width=width,gp=gp,annotation_name_align=annotation_name_align)
108
+
109
+ def __add__(self,other):
110
+ if isinstance(other,(ClusterMapPlotter,HeatmapAnnotation,HeatmapList)):return HeatmapList(self,other)
111
+ return super().__add__(other)
112
+ def __or__(self,other):return HeatmapList(self,other,direction='vertical')
113
+ def _as_plot(self,names=None,dpi=300,length_mm=180):
114
+ frames=[h.df for h in self if h.df is not None]
115
+ if not self:raise ValueError('annotation collection is empty')
116
+ if names is None:
117
+ if not frames:raise ValueError('standalone annotations need indexed or positional data')
118
+ names=frames[0].index.map(str)
119
+ names=pd.Index(names).map(str)
120
+ tracks=[]
121
+ row=self.which=='row'
122
+ for source in self:
123
+ obj=copy.copy(source)
124
+ if obj.df is not None:
125
+ obj.df=obj.df.copy()
126
+ if getattr(obj,'_positional',False):
127
+ if len(obj.df)!=len(names):raise ValueError('annotation length does not match shared axis')
128
+ obj._bind_item_ids(names);obj._positional=False
129
+ else:
130
+ obj.df.index=obj.df.index.map(str)
131
+ if set(obj.df.index)!=set(names):raise ValueError('annotation identifiers must match shared axis')
132
+ tracks.append(obj)
133
+ frame=pd.DataFrame(np.zeros((len(names),1) if row else (1,len(names))),index=names if row else ['_'],columns=['_'] if row else names)
134
+ p=Heatmap(frame,annotations=tracks,dpi=dpi,z_score=False,row_cluster=False,col_cluster=False,show_rownames=False,show_colnames=False,show_heatmap_legend=False)
135
+ p._annotation_only=True
136
+ extent=p._appearance.mm(length_mm)
137
+ p._shared_body=(1.,extent) if row else (extent,1.)
138
+ return p
139
+ def save(self,path,fmt=None,dpi=300,length_mm=180):
140
+ return self._as_plot(dpi=dpi,length_mm=length_mm).save(path,fmt)
141
+ def _repr_svg_(self):return self._as_plot()._render_svg()[0]
142
+
143
+
144
+ def rowAnnotation(df=None,col=None,**kwargs):
145
+ return HeatmapAnnotation(df,col,which='row',**kwargs)
146
+
147
+
148
+ def columnAnnotation(df=None,col=None,**kwargs):
149
+ return HeatmapAnnotation(df,col,which='column',**kwargs)
150
+
151
+
152
+ def _order(order,names):
153
+ if order is None:return np.arange(len(names))
154
+ values=np.asarray(order)
155
+ if values.dtype.kind in 'iu':ids=values.astype(int)
156
+ else:
157
+ lookup={str(n):i for i,n in enumerate(names)}
158
+ try:ids=np.array([lookup[str(v)] for v in values])
159
+ except KeyError as e:raise ValueError(f'unknown order identifier: {e.args[0]}') from e
160
+ if len(ids)!=len(names) or set(ids)!=set(range(len(names))):raise ValueError('order must be a permutation of every axis identifier/index')
161
+ return ids
162
+
163
+
164
+ class Heatmap(ClusterMapPlotter):
165
+ """R-named convenience interface for annotated matrices.
166
+
167
+ ``row_order``/``column_order`` accept zero-based permutations or identifiers.
168
+ ``ordering='auto'`` uses angles in a shared two-component SVD projection
169
+ for unsplit numeric matrices and diagonal ordering when either axis has
170
+ a split. Explicit axis orders, tree and block-order controls, and
171
+ algorithm bindings take precedence over automatic ordering.
172
+ Use ``ordering='diagonal'`` to infer groups for an unsplit numeric matrix
173
+ or ``ordering=None`` to use standard ordering.
174
+
175
+ With ``ordering=None`` and neither splits nor an explicit order, both axes
176
+ follow the input. To retain supplied splits and keep the input order
177
+ within each group, also set ``cluster_rows=False`` and
178
+ ``cluster_columns=False``.
179
+
180
+ To order split blocks by descending mean, use ``ordering=None`` and
181
+ ``cluster_order='avg_desc'`` with the default ``cluster_dendrogram=True``.
182
+ A full hierarchy can be requested with ``row_split=1`` or
183
+ ``column_split=1`` on a clustered axis. Select its method with
184
+ ``clustering_method_rows`` or ``clustering_method_columns``, such as
185
+ ``'complete'`` or ``'average'``. To use a separately calculated order,
186
+ pass the complete permutations as ``row_order`` and ``column_order``.
187
+
188
+ Native split heatmaps default to ``split_dendrogram='groups'``: one leaf
189
+ per displayed block, centered on that block, without per-item branches.
190
+ The display-only tree uses Euclidean distances of prepared block means
191
+ and complete linkage constrained to adjacent blocks, preserving the
192
+ selected heatmap order. Categorical cell matrices use category frequencies
193
+ instead of numeric-code means. Equal profiles use topological spacing;
194
+ terminal stems reserve at most one canvas pixel (at most 10% of tree depth)
195
+ for visibility. These are display-only adjustments, not distance-axis
196
+ measurements. Scientific item trees and values are unchanged.
197
+ ``split_dendrogram='full'`` requests item branches at the selected order.
198
+ A compatible source tree is rotated without changing its topology; otherwise
199
+ preserve mode builds a separate, order-constrained display hierarchy.
200
+ ``show_parent_dend_line=True`` also selects the original full-tree display.
201
+ ``row_dend_width`` and ``column_dend_height`` are millimeters (default 6);
202
+ zero or ``show_row_dend=False`` / ``show_column_dend=False`` hides that tree.
203
+ ``cluster_dendrogram=False`` hides the split tree in groups mode.
204
+
205
+ ``within_block_order`` selects ``auto``, ``svd``, ``hierarchical`` or
206
+ ``input`` within each displayed split; ``row_within_block_order`` and
207
+ ``column_within_block_order`` override one axis. Public automatic numeric
208
+ split ordering defaults to local SVD; ``input`` keeps source order inside
209
+ blocks. Each row slice uses all columns and each column slice uses all rows,
210
+ before compression and raster BlockMean. Explicit source orders and supplied
211
+ scientific trees take priority. Legacy ``ordering=None`` is unchanged unless
212
+ a within-block mode is explicitly selected.
213
+
214
+ On an unsplit axis ``auto_dendrogram_max_items=100`` shows an item tree for
215
+ 2 through 100 cleaned source items, independently for rows and columns,
216
+ before numeric compression; above the limit no automatic item tree is built.
217
+ Splits keep group trees at all sizes. Set the limit to 0 to disable automatic
218
+ item trees. ``row_dendrogram`` / ``column_dendrogram`` accept ``auto``,
219
+ ``none``, ``groups`` or ``items`` and override the default on one axis.
220
+ The explicit items override remains subject to identity and memory limits.
221
+ ``item_dendrogram_order='auto'`` preserves the selected order for automatic
222
+ drawing-only trees and uses scientific tree order for an explicit hierarchy.
223
+ ``tree`` and ``preserve`` select that contract explicitly; per-axis aliases
224
+ are ``row_item_dendrogram_order`` / ``column_item_dendrogram_order``.
225
+
226
+ For native numeric heatmaps, ``col=None`` uses the ``garnet`` palette by
227
+ default. Pass a built-in name such as ``col='kingfisher'`` or append
228
+ ``_r`` to reverse its color scale. ``heatmap_palettes()`` lists the built-in
229
+ names and their five colors. Preset anchors are equally spaced between
230
+ ``vmin`` and ``vmax`` and interpolate in CIELAB by default. ``col`` also
231
+ accepts a Matplotlib colormap name, color list, explicit ColorMapping or
232
+ categorical color dictionary.
233
+ Pass ``mask`` to distinguish hidden cells and original missing values in the native display.
234
+ For native numeric cells, an explicit ``na_col`` can colour missing inputs
235
+ with no separate mask when matrix compression and raster aggregation are off.
236
+ Set ``scale`` for explicit numeric axis scaling and ``cell_labels`` for native cell text.
237
+ ``use_raster=None`` selects a raster body when the longer axis exceeds 2000 and
238
+ the shorter exceeds 10. Explicit booleans override this choice.
239
+ ``raster_resize_mat=None`` selects block means for eligible raster displays
240
+ with at least 1,000,000 cells when shrinking. False selects centre sampling.
241
+ Use ``render_backend='cpu_tiled'`` to reduce preparation copies for eligible
242
+ native raster displays, including the canvas returned by ``to_matplotlib``.
243
+ Existing ClusterMapPlotter remains a supported independent entry point.
244
+ """
245
+ def __init__(self, matrix=None, col=None, name=None, top_annotation=None, bottom_annotation=None,
246
+ left_annotation=None, right_annotation=None, row_order=None, column_order=None,
247
+ slice_fun=None, *, ordering='auto', mask=None, mask_col='#F3D8A1', scale=None, cell_labels=None,
248
+ number_format='%.2f', number_color='#555555', fontsize_number=8,
249
+ max_number_labels=10000, raster_resize_mat=None, **kwargs):
250
+ if ordering is not None and (not isinstance(ordering, str) or ordering not in ('auto', 'diagonal')):
251
+ raise ValueError("ordering must be 'auto', 'diagonal', or None")
252
+ default_ordering = ordering == 'auto'
253
+ self._explicit_axis_orders={'row':row_order is not None,'col':column_order is not None}
254
+ if ordering is not None and (row_order is not None or column_order is not None):
255
+ if not default_ordering:
256
+ raise ValueError("diagonal ordering conflicts with row_order or column_order")
257
+ if slice_fun is not None and not callable(slice_fun):raise TypeError('slice_fun must be callable(context) or None')
258
+ if slice_fun is not None and kwargs.get('style',getattr(kwargs.get('config'),'style','complexheatmap'))!='complexheatmap':
259
+ raise ValueError('slice_fun requires the native complexheatmap style')
260
+ for alias, value, native in (('matrix', matrix, 'df'), ('col', col, 'cmap'),
261
+ ('name', name, 'heatmap_name')):
262
+ if value is not None and native in kwargs:
263
+ raise TypeError(f'{alias} and {native} both supplied')
264
+ if matrix is None:matrix=kwargs.pop('df',None)
265
+ if matrix is None:raise ValueError('matrix is required')
266
+ # Resolve the palette before deciding whether values represent numeric
267
+ # observations or categorical states. All public entry points share
268
+ # the same explicit > config > context priority as the renderer.
269
+ from .options import resolve_options
270
+ palette_options = {}
271
+ if kwargs.get('config') is not None:
272
+ palette_options['cmap'] = getattr(kwargs['config'], 'cmap', None)
273
+ if 'cmap' in kwargs:
274
+ palette_options['cmap'] = kwargs['cmap']
275
+ if col is not None:
276
+ palette_options['cmap'] = col
277
+ col = resolve_options(palette_options).get('cmap')
278
+ self.scale = scale
279
+ if scale is not None:
280
+ from .matrix_scaling import SCALES
281
+ if not isinstance(scale, str) or scale not in SCALES:
282
+ raise ValueError(f'scale must be None or one of {", ".join(SCALES)}')
283
+ if 'z_score' in kwargs:
284
+ raise TypeError('scale and z_score both supplied; choose one normalization control')
285
+ kwargs['z_score'] = False
286
+ self._explicit_color_space=kwargs.pop('color_space',None)
287
+ if self._explicit_color_space is not None:
288
+ self._explicit_color_space=str(self._explicit_color_space).upper()
289
+ if self._explicit_color_space not in ('LAB','RGB','SRGB'):raise ValueError('color_space must be LAB, RGB or sRGB')
290
+ if isinstance(col,(ColorMapping,dict)):raise ValueError('color_space requires a continuous palette; ColorMapping controls its own interpolation')
291
+ self._post_fun=kwargs.pop('post_fun',None)
292
+ if self._post_fun is not None and not callable(self._post_fun):raise TypeError('post_fun must be callable(heatmap, sink, layout)')
293
+ if self._post_fun is not None and kwargs.get('style',getattr(kwargs.get('config'),'style','complexheatmap'))!='complexheatmap':raise ValueError('post_fun requires the native complexheatmap style')
294
+ frame=matrix.copy() if isinstance(matrix,pd.DataFrame) else pd.DataFrame(matrix)
295
+ if any(len(set(axis.map(str)))!=len(axis) for axis in (frame.index,frame.columns)):
296
+ raise ValueError('heatmap axis identifiers must be unique after string conversion')
297
+ if cell_labels is not None and (not isinstance(cell_labels, (bool, np.bool_)) or cell_labels):
298
+ from .cell_labels import CellLabels
299
+ labels = True if isinstance(cell_labels, (bool, np.bool_)) else cell_labels
300
+ if isinstance(kwargs.get('layer_fun'), CellLabels):
301
+ raise TypeError('cell_labels and an existing cell label layer were both supplied')
302
+ self._cell_labels = CellLabels(
303
+ frame, labels, number_format, number_color, fontsize_number,
304
+ previous=kwargs.get('layer_fun'), maximum=max_number_labels, format_custom=True,
305
+ )
306
+ kwargs['layer_fun'] = self._cell_labels
307
+ if mask is not None:
308
+ if getattr(self, '_dot_heatmap', False):
309
+ raise ValueError('mask requires matrix-cell rendering; DotHeatmap uses size zero for absent marks')
310
+ from .cell_mask import CellMask
311
+ self._cell_mask = CellMask.from_input(frame, mask, mask_col)
312
+ from .r_cluster_controls import extract
313
+ self._r_controls=extract(kwargs,frame)
314
+ original_index=frame.index.copy();original_columns=frame.columns.copy()
315
+ self._name_gp_input_ids={'row':original_index.map(str),'column':original_columns.map(str)}
316
+ self._explicit_splits=set()
317
+ for key,names in [('row_labels',original_index),('column_labels',original_columns)]:
318
+ labels=kwargs.get(key)
319
+ if labels is not None and not isinstance(labels,dict):
320
+ if len(labels)!=len(names):raise ValueError(f'{key} length must match the input axis')
321
+ kwargs[key]=dict(zip(names.map(str),labels))
322
+ for key,axis in [('cluster_rows','row'),('cluster_columns','col')]:
323
+ value=kwargs.get(key)
324
+ if value is not None and not isinstance(value,(bool,np.bool_)):
325
+ linkage_key = axis + '_linkage_input'
326
+ if linkage_key in kwargs:
327
+ raise TypeError(f'{key} and {linkage_key} both supplied')
328
+ kwargs[linkage_key] = value
329
+ kwargs[key]=True
330
+ if axis=='row' or 'column_split' not in kwargs:
331
+ kwargs.setdefault(axis+'_split',1)
332
+ aliases={'cluster_rows':'row_cluster','cluster_columns':'col_cluster','show_row_names':'show_rownames','show_column_names':'show_colnames','show_row_dend':'row_dendro','show_column_dend':'col_dendro','column_split':'col_split','use_raster':'rasterized','row_dend_width':'row_dend_width_mm','column_dend_height':'column_dend_height_mm','clustering_distance_rows':'row_distance','clustering_distance_columns':'col_distance','clustering_method_rows':'row_cluster_method','clustering_method_columns':'col_cluster_method'}
333
+ for old,new in aliases.items():
334
+ if old in kwargs:
335
+ if new in kwargs:raise TypeError(f'{old} and {new} both supplied')
336
+ kwargs[new]=kwargs.pop(old)
337
+ for old,new in [('row_names_max_width','row_names_max_width_mm'),('column_names_max_height','column_names_max_height_mm'),
338
+ ('width','width_mm'),('height','height_mm'),('row_gap','row_gap_mm'),('gap','row_gap_mm'),('column_gap','column_gap_mm'),('border','body_border'),('border_gp','body_border_gp')]:
339
+ if old in kwargs:
340
+ if new in kwargs:raise TypeError(f'{old} and {new} both supplied')
341
+ kwargs[new]=kwargs.pop(old)
342
+ from .r_layout_controls import extract as extract_total_dimensions
343
+ from .r_raster import extract as extract_raster_controls
344
+ extract_total_dimensions(self,kwargs)
345
+ extract_raster_controls(self, kwargs, raster_resize_mat)
346
+ self._show_parent_dend_line=kwargs.pop('show_parent_dend_line',None)
347
+ if self._show_parent_dend_line is not None:
348
+ if not isinstance(self._show_parent_dend_line,(bool,np.bool_)):
349
+ raise TypeError('show_parent_dend_line must be boolean')
350
+ self._show_parent_dend_line=bool(self._show_parent_dend_line)
351
+ if kwargs.get('style',getattr(kwargs.get('config'),'style','complexheatmap'))!='complexheatmap':
352
+ raise ValueError('show_parent_dend_line requires native complexheatmap style')
353
+ allowed={f.name for f in fields(HeatmapConfig)}|{'config','df_filter','annotations','row_cluster_map','col_cluster_map','cell_fun','layer_fun'}
354
+ unknown=set(kwargs)-allowed
355
+ if unknown:raise TypeError('unsupported Heatmap options: '+', '.join(sorted(unknown)))
356
+ self._input_row_order=_order(row_order,frame.index)
357
+ self._input_col_order=_order(column_order,frame.columns)
358
+ self._hard_order_ids={
359
+ 'row':tuple(original_index[self._input_row_order].map(str)) if row_order is not None else None,
360
+ 'col':tuple(original_columns[self._input_col_order].map(str)) if column_order is not None else None}
361
+ if row_order is not None and kwargs.get('row_linkage_input') is None:kwargs['row_cluster']=False
362
+ if column_order is not None and kwargs.get('col_linkage_input') is None:kwargs['col_cluster']=False
363
+ self._input_applied_to_frame=False
364
+ category_colors=None
365
+ numeric_categories=all(pd.api.types.is_numeric_dtype(frame[c]) for c in frame.columns)
366
+ categorical = (not numeric_categories or isinstance(col, dict)
367
+ or isinstance(col, ColorMapping) and col.is_categorical)
368
+ real_numeric = not categorical and not any(pd.api.types.is_complex_dtype(t) for t in frame.dtypes)
369
+ if ordering is not None and not real_numeric:
370
+ if not default_ordering:
371
+ raise ValueError("diagonal ordering requires a real numeric matrix and continuous colour scale")
372
+ ordering = None
373
+ if scale not in (None, 'none') and not real_numeric:
374
+ raise ValueError('axis scaling requires a real numeric matrix and a continuous colour scale')
375
+ if categorical:
376
+ if self._r_raster_reducer is not False:raise ValueError('raster_resize_mat cannot aggregate categorical codes')
377
+ def category_key(value):
378
+ if numeric_categories and isinstance(value,(int,float,np.integer,np.floating)) and np.isfinite(value) and float(value).is_integer():
379
+ return str(int(value))
380
+ return str(value)
381
+ values=list(dict.fromkeys(category_key(v) for v in frame.to_numpy().ravel() if pd.notna(v)))
382
+ if isinstance(col,dict):mapping={category_key(k):v for k,v in col.items()}
383
+ elif isinstance(col,ColorMapping):
384
+ if not col.is_categorical:raise ValueError('categorical matrices require a categorical ColorMapping')
385
+ mapping={category_key(k):tuple(c) for k,c in zip(col.levels,col.colors)}
386
+ else:
387
+ auto=_generate_distinct_colors(len(values),palette=col)
388
+ mapping={v:tuple(x/255 for x in auto[i]) for i,v in enumerate(values)}
389
+ missing=set(values)-set(mapping)
390
+ if missing:raise ValueError(f'missing categorical colors: {sorted(missing)}')
391
+ codes={v:i+1 for i,v in enumerate(values)}
392
+ frame=frame.map(lambda v:0 if pd.isna(v) else codes[category_key(v)]).astype(float)
393
+ # R's named grey is #BEBEBE; Python/Matplotlib grey is #808080.
394
+ # Let the shared renderer resolve config/global/explicit priority.
395
+ category_colors={0:'#BEBEBE',**{codes[v]:mapping[v] for v in values}}
396
+ self._category_labels={codes[v]:v for v in values}
397
+ self._category_legend_levels=[v for v in mapping if v in codes]
398
+ kwargs.setdefault('z_score',False);kwargs.setdefault('row_cluster',False);kwargs.setdefault('col_cluster',False)
399
+ kwargs.setdefault('vmin',0);kwargs.setdefault('vmax',max(1,len(values)))
400
+ if kwargs.get('z_score') is not False:raise ValueError('categorical matrices cannot use z_score=True')
401
+ elif col is not None:kwargs['cmap']=col
402
+ if name is not None:kwargs['heatmap_name']=name
403
+ annotations=list(kwargs.pop('annotations',[]) or [])
404
+ for side,value in [('top',top_annotation),('bottom',bottom_annotation),('left',left_annotation),('right',right_annotation)]:
405
+ if value is None:continue
406
+ for obj in value if isinstance(value,(list,tuple)) else [value]:
407
+ obj=copy.copy(obj);obj.side=side;annotations.append(obj)
408
+ # Positional tracks belong to the caller's input axis, before any
409
+ # explicit permutation. Bind identities once, then reindex by names.
410
+ for i,obj in enumerate(annotations):
411
+ if getattr(obj,'_positional',False) and getattr(obj,'df',None) is not None:
412
+ obj=copy.copy(obj);obj.df=obj.df.copy()
413
+ axis=original_index if obj.side in ('left','right') else original_columns
414
+ if len(obj.df)!=len(axis):raise ValueError('positional annotation length does not match original heatmap axis')
415
+ obj._bind_item_ids(axis);obj._positional=False;annotations[i]=obj
416
+ for axis in ('row','col'):
417
+ split=kwargs.get(axis+'_split')
418
+ if split is not None and not np.isscalar(split):
419
+ mapping_key = axis + '_cluster_map'
420
+ if kwargs.get(mapping_key) is not None:
421
+ raise TypeError(f'{axis}_split and {mapping_key} both supplied')
422
+ names=original_index if axis=='row' else original_columns
423
+ groups=split.copy() if isinstance(split,(pd.Series,pd.DataFrame)) else pd.Series(split,index=names)
424
+ if isinstance(groups,pd.DataFrame):groups=groups.astype(str).agg(' / '.join,axis=1)
425
+ groups.index=groups.index.map(str)
426
+ self._explicit_splits.add(axis)
427
+ kwargs[mapping_key]=groups
428
+ kwargs[axis+'_split']=groups.nunique()
429
+ super().__init__(df=frame,annotations=annotations,**kwargs)
430
+ if ordering is not None:
431
+ orders=(self.cluster_order,self.row_cluster_order,self.col_cluster_order)
432
+ tree_controls=any(
433
+ self._visual_options.get(axis+'_linkage_input') is not None or
434
+ self._r_controls.get(axis+'_reorder',False) is not False
435
+ for axis in ('row','col')
436
+ )
437
+ competing_order = (any(value not in (None, 'dendrogram') for value in orders)
438
+ or self.reverse_columns
439
+ or (tree_controls and not default_ordering))
440
+ if default_ordering:
441
+ full_tree = (
442
+ (self.row_cluster and self.row_split == 1 and self.row_cluster_map is None)
443
+ or (self.col_cluster and self.col_split == 1 and self.col_cluster_map is None)
444
+ )
445
+ preserve_input = not (self.row_cluster or self.col_cluster or self._explicit_splits)
446
+ if (competing_order or preserve_input or getattr(self, '_dot_heatmap', False)
447
+ or self.dendrogram_mode != 'hierarchical' or any(value is not None for value in orders)):
448
+ ordering = None
449
+ elif competing_order:
450
+ raise ValueError("diagonal ordering conflicts with a separate block order, mirror or dendrogram control")
451
+ self.ordering = 'diagonal' if ordering is not None else None
452
+ self._uses_default_ordering = default_ordering
453
+ from .ordering_policy import resolve_axis_order
454
+ for axis in ('row','col'):
455
+ resolve_axis_order(self,axis)
456
+ if slice_fun is not None and self.style!='complexheatmap':
457
+ raise ValueError('slice_fun requires the resolved native complexheatmap style')
458
+ if slice_fun is not None and (self.row_compression!=1 or self.col_compression!=1):
459
+ raise ValueError('slice_fun requires row_compression=col_compression=1 to retain cell source identities')
460
+ if category_colors is not None and (self.row_compression!=1 or self.col_compression!=1):
461
+ raise ValueError('categorical heatmaps require compression=1; averaging category codes is undefined')
462
+ if slice_fun is not None:self._visual_options['slice_fun']=slice_fun
463
+ from .r_layout_controls import validate_resolved as validate_total_dimensions
464
+ from .r_raster import validate_resolved as validate_raster_controls
465
+ validate_total_dimensions(self)
466
+ validate_raster_controls(self)
467
+ label_layer = getattr(self, '_cell_labels', None)
468
+ if label_layer is not None:
469
+ if self.style != 'complexheatmap':
470
+ raise ValueError('cell_labels requires native complexheatmap style')
471
+ if label_layer.data is not None and (self.row_compression != 1 or self.col_compression != 1):
472
+ raise ValueError('custom cell_labels require one-to-one cells; disable mean compression')
473
+ if mask is not None:
474
+ if self.style != 'complexheatmap':
475
+ raise ValueError('mask requires native complexheatmap style')
476
+ if self.row_compression != 1 or self.col_compression != 1 or self._r_raster_reducer is not False:
477
+ raise ValueError('mask requires one-to-one cells; disable matrix compression and raster_resize_mat')
478
+ elif (real_numeric and self.style == 'complexheatmap' and not getattr(self, '_dot_heatmap', False)
479
+ and self.row_compression == self.col_compression == 1 and self._r_raster_reducer is False
480
+ and (self.df_filter is None or self.label not in frame.columns)
481
+ and (kwargs.get('na_col') is not None
482
+ or self._visual_options.get('na_col') not in (None, HeatmapConfig.na_col))):
483
+ missing = frame.isna()
484
+ if missing.to_numpy().any():
485
+ from .cell_mask import CellMask
486
+ self._cell_mask = CellMask.from_missing(missing, label='Missing')
487
+ if self._show_parent_dend_line is not None and self.style!='complexheatmap':
488
+ raise ValueError('show_parent_dend_line requires native complexheatmap style')
489
+ self._category_colors=category_colors
490
+
491
+ def _generate_lut(self):
492
+ space=getattr(self,'_explicit_color_space',None)
493
+ if space is None:return super()._generate_lut()
494
+ from .palettes import _continuous_palette_colors
495
+ palette=self.cmap
496
+ if isinstance(palette,ColorMapping):raise ValueError('color_space conflicts with a ColorMapping; set its space directly')
497
+ colors = _continuous_palette_colors(palette, native=self.style == 'complexheatmap')
498
+ if colors is not None:
499
+ palette = colors
500
+ elif palette is None or isinstance(palette,str) and palette in ('complexheatmap','auto'):
501
+ palette=['blue','#EEEEEE','red']
502
+ elif isinstance(palette,str):
503
+ import matplotlib
504
+ palette=matplotlib.colormaps.get_cmap(palette)(np.linspace(0,1,256))[:,:3]
505
+ return ColorMapping(np.linspace(0,1,len(palette)),palette,space=space).lut()
506
+
507
+ def __add__(self,other):return HeatmapList(self,other)
508
+ def __or__(self,other):return HeatmapList(self,other,direction='vertical')
509
+ def _repr_svg_(self):return self._render_svg()[0]
510
+ def __getitem__(self,key):
511
+ from .object_ops import subset_heatmap
512
+ if not isinstance(key,tuple):key=(key,slice(None))
513
+ if len(key)!=2:raise IndexError('heatmap selection needs rows and columns')
514
+ return subset_heatmap(self,*key)
515
+
516
+
517
+ class HeatmapList:
518
+ """Compose heatmaps with shared row (horizontal) or column (vertical) IDs."""
519
+ def __init__(self,*heatmaps,direction='horizontal',gap_mm=4,layout='aligned',main_heatmap=None,
520
+ row_title=None,column_title=None,row_title_gp=None,column_title_gp=None,padding_mm=0):
521
+ if direction not in ('horizontal','vertical'):raise ValueError('direction must be horizontal or vertical')
522
+ if layout not in ('aligned','independent'):raise ValueError('layout must be aligned or independent')
523
+ self.heatmaps=[]
524
+ for h in heatmaps:
525
+ if isinstance(h,HeatmapList) and h.direction!=direction:raise ValueError('nested composition direction must match; draw opposite directions separately')
526
+ self.heatmaps.extend(h.heatmaps if isinstance(h,HeatmapList) else [h])
527
+ if not self.heatmaps or not all(isinstance(h,(ClusterMapPlotter,HeatmapAnnotation)) for h in self.heatmaps):raise TypeError('HeatmapList requires heatmaps')
528
+ from .composition_controls import lengths,initialize
529
+ self.direction=direction;self.gap_mm=lengths(gap_mm,len(self.heatmaps)-1,'gap_mm');self.layout=layout
530
+ initialize(self,main_heatmap,row_title,column_title,row_title_gp,column_title_gp,padding_mm)
531
+
532
+ def __len__(self):return len(self.heatmaps)
533
+ def __getitem__(self,key):
534
+ from .object_ops import get_heatmap,subset_heatmap_list
535
+ if isinstance(key,str):return get_heatmap(self,key)
536
+ if not isinstance(key,tuple):return subset_heatmap_list(self,heatmaps=key)
537
+ if len(key)!=2:raise IndexError('list selection needs shared axis and components')
538
+ return subset_heatmap_list(self,rows=key[0],heatmaps=key[1]) if self.direction=='horizontal' else subset_heatmap_list(self,heatmaps=key[0],columns=key[1])
539
+
540
+ def _append(self,other,direction):
541
+ from .composition_controls import appended_settings
542
+ count=len(self.heatmaps)+(len(other) if isinstance(other,HeatmapList) else 1)
543
+ return HeatmapList(*self.heatmaps,other,**appended_settings(self,count,direction))
544
+ def __add__(self,other):return self._append(other,self.direction)
545
+ def __or__(self,other):return self._append(other,'vertical')
546
+ def _repr_svg_(self):return draw(self)
547
+
548
+ def _scene(self,render=True,*,writer=None):
549
+ from .appearance import compute_layout,draw_body,prepare
550
+ from .pdf_renderer import PdfSink
551
+ horizontal=self.direction=='horizontal'
552
+ from .composition_controls import reference,frame_scene
553
+ ref=reference(self)
554
+ if ref is None:ref=self.heatmaps[0]._as_plot()
555
+ compute_layout(ref)
556
+ ids=list(ref.row_names if horizontal else ref.col_names)
557
+ if len(set(ids))!=len(ids):raise ValueError('shared axis identifiers must be unique')
558
+ self.aligned_names=ids
559
+ views=[];layouts=[]
560
+ heatmap_indices=[i for i,h in enumerate(self.heatmaps) if isinstance(h,ClusterMapPlotter)]
561
+ for index,source in enumerate(self.heatmaps):
562
+ if isinstance(source,HeatmapAnnotation):
563
+ if (source.which=='row')!=horizontal:raise ValueError('annotation orientation conflicts with composition direction')
564
+ input_names=np.asarray(ref.df.index if horizontal else ref.df.columns,dtype=object)
565
+ input_order=getattr(ref,'_input_row_order' if horizontal else '_input_col_order',None)
566
+ if input_order is not None and getattr(ref,'_input_applied_to_frame',True):
567
+ original_names=input_names.copy();original_names[input_order]=input_names;input_names=original_names
568
+ source=source._as_plot(input_names,dpi=ref.dpi)
569
+ if self.layout=='aligned' and source is not ref:
570
+ # The reference supplies the shared tree. Size a private view
571
+ # without calculating a tree that will immediately be discarded.
572
+ prepare(source)
573
+ sizing=copy.copy(source);sizing._visual_options=dict(source._visual_options)
574
+ sizing.all_annotations=[copy.copy(h) for h in source.all_annotations]
575
+ for side in ('top','bottom','left','right'):
576
+ setattr(sizing,side+'_annotations',[h for h in sizing.all_annotations if h.side==side])
577
+ setattr(sizing,'row_dendro' if horizontal else 'col_dendro',False)
578
+ source_layout=compute_layout(sizing)
579
+ else:
580
+ source_layout=compute_layout(source)
581
+ names=list(source.row_names if horizontal else source.col_names)
582
+ if set(names)!=set(ids) or len(names)!=len(ids):raise ValueError('heatmaps must have identical shared-axis identifiers')
583
+ p=copy.copy(source);p._visual_options=dict(source._visual_options)
584
+ p.all_annotations=[copy.copy(h) for h in source.all_annotations]
585
+ for side in ('top','bottom','left','right'):setattr(p,side+'_annotations',[h for h in p.all_annotations if h.side==side])
586
+ order=[names.index(n) for n in ids]
587
+ if horizontal:
588
+ p._matrix_sorted=source._matrix_sorted[order,:];p.row_names=np.asarray(ids);p.row_linkage=ref.row_linkage;p.row_breaks=list(ref.row_breaks)
589
+ p._matrix_raw_sorted=source._matrix_raw_sorted[order,:] if source._matrix_raw_sorted.shape==source._matrix_sorted.shape else source._matrix_raw_sorted
590
+ else:
591
+ p._matrix_sorted=source._matrix_sorted[:,order];p.col_names=np.asarray(ids);p.col_linkage=ref.col_linkage;p.col_breaks=list(ref.col_breaks)
592
+ p._matrix_raw_sorted=source._matrix_raw_sorted[:,order] if source._matrix_raw_sorted.shape==source._matrix_sorted.shape else source._matrix_raw_sorted
593
+ # Reindex views from original sources using the new shared names.
594
+ p._appearance=Appearance(ref.dpi,source._appearance.body_width_mm,source._appearance.font_family);p.dpi=ref.dpi
595
+ # Normalize geometry before sharing an axis, including slice gaps.
596
+ scale=ref.dpi/source.dpi
597
+ p._visual_options['dpi']=ref.dpi
598
+ if horizontal:
599
+ p._shared_body=(source_layout['heatmap_w']*scale,ref._last_layout['heatmap_h'])
600
+ p._visual_options['row_split_gap']=ref.row_gap_pixels/10
601
+ p._visual_options['row_gap_mm']=ref._visual_options.get('row_gap_mm')
602
+ else:
603
+ p._shared_body=(ref._last_layout['heatmap_w'],source_layout['heatmap_h']*scale)
604
+ p._visual_options['col_split_gap']=ref.col_gap_pixels/10
605
+ p._visual_options['column_gap_mm']=ref._visual_options.get('column_gap_mm')
606
+ if self.layout=='aligned':
607
+ from .composition_layout import shared_view
608
+ shared_view(p,ref,index,heatmap_indices,horizontal,len(self.heatmaps))
609
+ p._r_shared_axis='height' if horizontal else 'width'
610
+ layout=compute_layout(p);views.append(p);layouts.append(layout)
611
+ self._reference=ref
612
+ self._composed_views=views
613
+ self._component_boxes={}
614
+ gaps=[self.gap_mm]*(len(self.heatmaps)-1) if np.isscalar(self.gap_mm) else self.gap_mm
615
+ anchor=max(l['heatmap_y' if horizontal else 'heatmap_x'] for l in layouts)
616
+ offset=0;sink=PdfSink()
617
+ width=height=0;placements=[]
618
+ for index,(p,l) in enumerate(zip(views,layouts)):
619
+ shift=anchor-l['heatmap_y' if horizontal else 'heatmap_x']
620
+ tx,ty=(offset,shift) if horizontal else (shift,offset)
621
+ from .decorations import components
622
+ from .object_ops import heatmap_names
623
+ # Numeric prefixes are always unambiguous; unique names are aliases.
624
+ names=heatmap_names(self)
625
+ for component,(cx,cy,cw,ch) in components(p).items():
626
+ box=(cx+tx,cy+ty,cw,ch)
627
+ self._component_boxes[f'{index}/{component}']=box
628
+ if names.count(names[index])==1:self._component_boxes[f'{names[index]}/{component}']=box
629
+ placements.append((p,l,tx,ty))
630
+ width=max(width,tx+l['full_w']);height=max(height,ty+l['full_h'])
631
+ # Aligned groups share the adjacent outer padding; gap_mm is the
632
+ # clearance between measured content rather than two padded pages.
633
+ gap=ref._appearance.mm(gaps[index]) if index<len(gaps) else 0
634
+ offset+=(l['full_w'] if horizontal else l['full_h'])+gap-(ref._appearance.mm(4) if self.layout=='aligned' else 0)
635
+ shared_scenes=[]
636
+ if self.layout=='aligned':
637
+ from .composition_layout import external_legends
638
+ placements,width,height,shared_scenes=external_legends(self,placements,width,height,ref)
639
+ placements,width,height,title_nodes=frame_scene(self,placements,width,height,shared_scenes,ref)
640
+ if width*height>ref.max_canvas_pixels or max(width,height)>ref.max_canvas_dimension:raise ValueError('combined canvas exceeds pixel budget; lower each heatmap dpi/width')
641
+ self._shared_legend_scenes=shared_scenes
642
+ width,height=int(np.ceil(width)),int(np.ceil(height))
643
+ self._last_layout={'full_w':width,'full_h':height}
644
+ if render:
645
+ def draw_scene(target):
646
+ for p,l,tx,ty in placements:
647
+ target.write(f'<g transform="translate({tx},{ty})">')
648
+ draw_body(p,target,l)
649
+ target.write('</g>')
650
+ for scene in shared_scenes:
651
+ sx,sy,_,_=scene['box'];scene['packed']._draw(target,sx,sy,ref._appearance,scene['layout'])
652
+ from .titles import draw_title
653
+ for node in title_nodes:draw_title(ref,target,node)
654
+ from .decorations import render_decorations
655
+ render_decorations(self,target)
656
+
657
+ if writer is None:
658
+ draw_scene(sink)
659
+ else:
660
+ writer(width,height,ref.dpi,ref._appearance.font_family,draw_scene)
661
+ return sink,width,height,ref
662
+
663
+ def save(self,output_path,fmt=None,**options):
664
+ if options:
665
+ from .composition_controls import configured
666
+ return configured(self,options).save(output_path,fmt=fmt)
667
+ fmt=(fmt or Path(output_path).suffix.lstrip('.') or 'svg').lower()
668
+ if fmt in ('pdf','svg') and any(getattr(h,'rasterized',None) is False or getattr(h,'_dot_heatmap',False)
669
+ for h in self.heatmaps):
670
+ self._scene(writer=_vector_file_writer(fmt,output_path))
671
+ return
672
+ sink,w,h,ref=self._scene()
673
+ _save_ops(sink,w,h,ref.dpi,ref._appearance.font_family,output_path,fmt)
674
+
675
+
676
+ def _vector_file_writer(fmt,path):
677
+ from functools import partial
678
+ if fmt=='svg':
679
+ from .streaming_svg import save_vector_svg
680
+ return partial(save_vector_svg,path)
681
+ from .streaming_pdf import save_vector_pdf
682
+ return partial(save_vector_pdf,path)
683
+
684
+
685
+ def _ops_svg(sink,w,h,dpi,family):
686
+ """Serialize supported primitives through SVG for editable composed output."""
687
+ from .pdf_renderer import _IndexedImage
688
+ import base64,cv2
689
+ out=io.StringIO()
690
+ out.write(f'<svg xmlns="http://www.w3.org/2000/svg" width="{w/dpi*25.4}mm" height="{h/dpi*25.4}mm" viewBox="0 0 {w} {h}" font-family="{family}">')
691
+ def color(c):return 'none' if c is None else '#%02x%02x%02x'%tuple(np.clip(np.round(np.asarray(c)*255),0,255).astype(int))
692
+ for op in sink._ops:
693
+ k=op[0]
694
+ if k=='polygon':
695
+ _,points,fill,stroke,sw,alpha=op
696
+ pts=' '.join(f'{x},{y}' for x,y in points)
697
+ out.write(f'<polygon points="{pts}" fill="{color(fill)}" stroke="{color(stroke)}" stroke-width="{sw or 0}" fill-opacity="{alpha if alpha is not None else 1}"/>')
698
+ elif k=='rect':
699
+ _,x,y,ww,hh,fill,stroke,sw,alpha=op
700
+ out.write(f'<rect x="{x}" y="{y}" width="{ww}" height="{hh}" fill="{color(fill)}" stroke="{color(stroke)}" stroke-width="{sw or 0}" fill-opacity="{alpha if alpha is not None else 1}"/>')
701
+ elif k in ('line','lines'):
702
+ if k=='line':_,x1,y1,x2,y2,stroke,sw=op;segments=[(x1,y1,x2,y2)]
703
+ else:_,segments,stroke,sw=op
704
+ for x1,y1,x2,y2 in segments:out.write(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{color(stroke)}" stroke-width="{sw}"/>')
705
+ elif k=='circle':
706
+ _,x,y,r,fill,stroke,sw=op
707
+ out.write(f'<circle cx="{x}" cy="{y}" r="{r}" fill="{color(fill)}" stroke="{color(stroke)}" stroke-width="{sw}"/>')
708
+ elif k=='text':
709
+ _,x,y,text,font,size,rgb,anchor,baseline,rot=op
710
+ transform=f' transform="rotate({rot[0]},{rot[1]},{rot[2]})"' if rot else ''
711
+ font_family=getattr(font,'family',None)
712
+ family_attribute=(' font-family="'+escape(font_family,{'"':'&quot;'})+'"') if font_family else ''
713
+ out.write(f'<text x="{x}" y="{y}" font-size="{size}" text-anchor="{anchor or "start"}" dominant-baseline="{baseline or "auto"}" fill="{color(rgb)}" font-weight="{"bold" if "Bold" in font else "normal"}" font-style="{"italic" if "Oblique" in font or "Italic" in font else "normal"}"{family_attribute}{transform}>{escape(text)}</text>')
714
+ elif k=='image':
715
+ _,x,y,ww,hh,payload=op
716
+ if isinstance(payload,_IndexedImage):
717
+ indices=np.frombuffer(payload.indices,np.uint8).reshape(payload.height,payload.width)
718
+ pal=np.frombuffer(bytes.fromhex(payload.palette_hex.decode()),np.uint8).reshape(-1,3)
719
+ _,encoded=cv2.imencode('.png',pal[indices][:,:,::-1]);payload=encoded.tobytes()
720
+ b64=base64.b64encode(payload).decode()
721
+ out.write(f'<image x="{x}" y="{y}" width="{ww}" height="{hh}" preserveAspectRatio="none" href="data:image/png;base64,{b64}"/>')
722
+ out.write('</svg>');return out.getvalue()
723
+
724
+
725
+ def _save_ops(sink,w,h,dpi,family,path,fmt=None):
726
+ path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
727
+ fmt=(fmt or path.suffix.lstrip('.') or 'svg').lower()
728
+ if fmt=='svg':path.write_text(_ops_svg(sink,w,h,dpi,family),encoding='utf-8')
729
+ elif fmt=='pdf':
730
+ from .unicode_pdf import UnicodePdfSink
731
+ pdf=UnicodePdfSink(w,h,dpi,family);pdf._ops=sink._ops;pdf.finalize(str(path),w,h)
732
+ elif fmt in ('png','jpg','jpeg','tif','tiff'):
733
+ from .png_renderer import OrderedPngSink
734
+ raster=OrderedPngSink(w,h);raster._ops=sink._ops;raster.font_family=family;raster.dpi=dpi
735
+ raster.finalize(str(path),w,h,fmt)
736
+ else:raise ValueError(f'Unsupported format: {fmt}')
737
+
738
+
739
+ from .legends import Legend, PackedLegends, packLegend
740
+
741
+ def draw(obj,output_path=None,**kwargs):
742
+ if output_path is not None:obj.save(output_path,**kwargs)
743
+ elif isinstance(obj,HeatmapList):
744
+ if kwargs:
745
+ from .composition_controls import configured
746
+ obj=configured(obj,kwargs)
747
+ sink,w,h,p=obj._scene();return _ops_svg(sink,w,h,p.dpi,p._appearance.font_family)
748
+ elif kwargs:raise TypeError('draw without output_path accepts composition settings only for HeatmapList')
749
+ elif isinstance(obj,ClusterMapPlotter):return obj._render_svg()[0]
750
+ elif isinstance(obj,HeatmapAnnotation):return obj._repr_svg_()
751
+ elif isinstance(obj,(Legend,PackedLegends)):return obj._repr_svg_()
752
+ return obj
753
+
754
+ def _axis_order(obj, axis):
755
+ obj._compute_clustering()
756
+ order = np.asarray(getattr(obj, f'_{axis}_order'))
757
+ if getattr(obj, f'{axis}_compression') > 1:
758
+ return order.copy()
759
+ # The bounded source path already keeps positions in final display order.
760
+ source = getattr(obj, '_source_rows' if axis == 'row' else '_source_columns', None)
761
+ if source is not None:
762
+ return source.copy()
763
+ positions = getattr(obj, '_cleaned_source_positions', {}).get(axis)
764
+ return positions[order] if positions is not None else order.copy()
765
+
766
+
767
+ def row_order(obj,*,name=None):
768
+ if isinstance(obj,HeatmapList):
769
+ from .composition_controls import query
770
+ return query(obj,'row','order',name)
771
+ if name is not None:raise TypeError('name selects a HeatmapList component')
772
+ return _axis_order(obj, 'row')
773
+ def column_order(obj,*,name=None):
774
+ if isinstance(obj,HeatmapList):
775
+ from .composition_controls import query
776
+ return query(obj,'column','order',name)
777
+ if name is not None:raise TypeError('name selects a HeatmapList component')
778
+ return _axis_order(obj, 'col')
779
+ def row_dend(obj,*,name=None):
780
+ if isinstance(obj,HeatmapList):
781
+ from .composition_controls import query
782
+ return query(obj,'row','dend',name)
783
+ if name is not None:raise TypeError('name selects a HeatmapList component')
784
+ obj._compute_clustering();return None if obj.row_linkage is None else obj.row_linkage.copy()
785
+ def column_dend(obj,*,name=None):
786
+ if isinstance(obj,HeatmapList):
787
+ from .composition_controls import query
788
+ return query(obj,'column','dend',name)
789
+ if name is not None:raise TypeError('name selects a HeatmapList component')
790
+ obj._compute_clustering();return None if obj.col_linkage is None else obj.col_linkage.copy()
791
+ def add_heatmap(left,right):return HeatmapList(left,right)
792
+ def anno_simple(x,col=None,*,which='column',gp=None,pch=None,pt_size=2,pt_gp=None,na_col='#BEBEBE',**kwargs):
793
+ # New aliases are physical mm, unlike retained canvas-unit height.
794
+ size=kwargs.pop('simple_anno_size',None)
795
+ width=kwargs.pop('width',None)
796
+ if width is not None and which!='row':raise ValueError('width is only for row annotations')
797
+ if size is not None and width is not None:raise ValueError('simple_anno_size conflicts with width')
798
+ size=width if width is not None else size
799
+ if size is not None:
800
+ if 'height' in kwargs:raise ValueError('physical size conflicts with canvas-unit height')
801
+ if isinstance(size,(bool,np.bool_)) or not isinstance(size,(int,float,np.integer,np.floating)) or not np.isfinite(size) or size<=0:
802
+ raise ValueError('simple annotation size must be positive finite mm')
803
+ from .graphics import validate_gp,draw_marker
804
+ allowed={'side','height','fontsize','label','border','element_border','element_border_color','element_border_width','cmap'}
805
+ if set(kwargs)-allowed:raise TypeError('unsupported anno_simple options: '+', '.join(sorted(set(kwargs)-allowed)))
806
+ if which not in ('row','column'):raise ValueError('which must be row or column')
807
+ kwargs.setdefault('side','left' if which=='row' else 'top')
808
+ if (kwargs['side'] in ('left','right'))!=(which=='row'):raise ValueError('side conflicts with which')
809
+ style=validate_gp(gp,{'col','lwd'});point_style=validate_gp(pt_gp,{'col','fill','lwd'})
810
+ if not np.isscalar(pt_size) or not np.isfinite(pt_size) or pt_size<=0:raise ValueError('pt_size must be positive finite mm')
811
+ markers=None if pch is None else list(pch) if isinstance(pch,(list,tuple,np.ndarray)) else [pch]
812
+ if markers is not None:
813
+ if not markers:raise ValueError('pch must not be empty')
814
+ for marker in markers:
815
+ if marker is not None and not pd.isna(marker):draw_marker(io.StringIO(),0,0,1,marker)
816
+ frame=x.to_frame() if isinstance(x,pd.Series) else pd.DataFrame(x)
817
+ if all(pd.api.types.is_numeric_dtype(frame[c]) for c in frame) and not isinstance(col,dict):
818
+ h=ColorAnnotation(df=frame,color_mappings={c:col for c in frame},**kwargs)
819
+ else:
820
+ if col is not None:kwargs['colors']=col
821
+ h=SimpleAnnotation(df=frame,**kwargs)
822
+ if hasattr(h,'color_mappings'):
823
+ # A per-annotation NA override must not mutate the caller's mapping.
824
+ h.color_mappings={key:ColorMapping(col_fun=mapping,na_col=na_col) for key,mapping in h.color_mappings.items()}
825
+ if size is not None:h._fixed_height_mm=float(size);h._simple_physical_size=True
826
+ h._simple_gp=style;h._point_gp=point_style;h._simple_pch=markers;h._simple_pt_size=float(pt_size);h.na_col=na_col
827
+ h._graphical_ids=pd.Series(np.arange(len(frame)),index=frame.index.map(str))
828
+ h._positional=not isinstance(x,(pd.Series,pd.DataFrame));return h
829
+ def anno_barplot(x=None,**kwargs):
830
+ if x is not None:
831
+ from .barplot import StackedBarAnnotation
832
+ kwargs.setdefault('colors','#cccccc')
833
+ return StackedBarAnnotation(x,**kwargs)
834
+ # Preserve legacy implicit matrix-derived bars, but never swallow explicit
835
+ # controls that only the data-driven bar implementation can honor.
836
+ implicit={'side','height','fontsize','label','plot_color','background_color','ylim',
837
+ 'force_zero','show_border','border_color','border_width','element_border','agg','show_values'}
838
+ unknown=set(kwargs)-implicit
839
+ if unknown:raise TypeError('barplot controls require explicit x or are unsupported for implicit data: '+', '.join(sorted(unknown)))
840
+ kwargs.setdefault('force_zero',True);kwargs.setdefault('show_values',False)
841
+ h=ExpressionAnnotation(df=x,**kwargs);h._positional=x is not None and not isinstance(x,(pd.Series,pd.DataFrame));return h
842
+ def anno_boxplot(x=None,**kwargs):
843
+ from .annotations_extra import DistributionBoxplotAnnotation
844
+ row=kwargs.get('which')=='row' or kwargs.get('side') in ('left','right')
845
+ # Matrix columns are distributions in a column annotation. Lists contain
846
+ # one distribution per item; a DataFrame retains its explicit axis IDs.
847
+ if isinstance(x,pd.DataFrame):x=x if row else x.T
848
+ elif isinstance(x,np.ndarray) and x.ndim==2 and not row:x=x.T
849
+ return DistributionBoxplotAnnotation(x,**kwargs)
850
+
851
+
852
+ def row_anno_barplot(x=None,**kwargs):
853
+ kwargs.setdefault('side','left')
854
+ return anno_barplot(x,**kwargs)
855
+
856
+ def row_anno_boxplot(x=None,**kwargs):
857
+ kwargs.setdefault('side','left')
858
+ return anno_boxplot(x,**kwargs)
859
+
860
+
861
+ __all__=['Heatmap','HeatmapList','HeatmapAnnotation','Legend','PackedLegends','packLegend','draw','rowAnnotation','columnAnnotation','row_order','column_order','row_dend','column_dend','add_heatmap','anno_simple','anno_barplot','anno_boxplot','row_anno_barplot','row_anno_boxplot']