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
@@ -0,0 +1,453 @@
1
+ """Aligned region-by-position signal panels on the native heatmap engine.
2
+
3
+ No file readers or genomic annotation dependencies are involved. Preparation is
4
+ explicit and reusable; profile means always describe the original signal units.
5
+ """
6
+ from collections.abc import Mapping
7
+ from copy import deepcopy
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from .api import Heatmap, HeatmapList, HeatmapAnnotation, rowAnnotation
13
+ from .annotations_extra import LinesAnnotation
14
+
15
+
16
+ class SignalHeatmapData:
17
+ """Owned preparation result returned by :func:`prepare_signal_heatmap`.
18
+
19
+ Public data properties return copies. Matrices and summary_values retain
20
+ first-panel input row order; row_order describes the display permutation.
21
+ Profiles have bins in rows and group_order in columns. This is an in-memory
22
+ dense snapshot, not a disk cache or a sparse/backed matrix adapter.
23
+ """
24
+
25
+ def __init__(self, matrices, positions, groups, order, group_order, profiles,
26
+ summary_values, report):
27
+ self._matrices = {k: v.copy(deep=True) for k, v in matrices.items()}
28
+ self._positions = np.array(positions, dtype=float, copy=True)
29
+ self._groups = groups.copy(deep=True)
30
+ self._order = tuple(order)
31
+ self._group_order = tuple(group_order)
32
+ self._profiles = {k: v.copy(deep=True) for k, v in profiles.items()}
33
+ self._summary_values = summary_values.copy(deep=True)
34
+ self._report = deepcopy(report)
35
+
36
+ @property
37
+ def matrices(self):
38
+ return {k: v.copy(deep=True) for k, v in self._matrices.items()}
39
+
40
+ @property
41
+ def positions(self):
42
+ return self._positions.copy()
43
+
44
+ @property
45
+ def row_groups(self):
46
+ return self._groups.copy(deep=True)
47
+
48
+ @property
49
+ def row_order(self):
50
+ return list(self._order)
51
+
52
+ @property
53
+ def group_order(self):
54
+ return list(self._group_order)
55
+
56
+ @property
57
+ def profiles(self):
58
+ return {k: v.copy(deep=True) for k, v in self._profiles.items()}
59
+
60
+ @property
61
+ def summary_values(self):
62
+ return self._summary_values.copy(deep=True)
63
+
64
+ @property
65
+ def report(self):
66
+ return deepcopy(self._report)
67
+
68
+
69
+ def _string_ids(values, name):
70
+ index = pd.Index(values)
71
+ if index.hasnans:
72
+ raise ValueError(name + ' identifiers must not be missing')
73
+ index = index.map(str)
74
+ if not index.is_unique:
75
+ raise ValueError(name + ' identifiers must be unique after string conversion')
76
+ return index
77
+
78
+
79
+ def _signal_matrices(signals):
80
+ if not isinstance(signals, Mapping) or not signals:
81
+ raise ValueError('signals must be a nonempty name-to-matrix mapping')
82
+ names = _string_ids(list(signals), 'panel')
83
+ if any(not name.strip() for name in names):
84
+ raise ValueError('panel names must be nonempty')
85
+ named = [isinstance(value, pd.DataFrame) for value in signals.values()]
86
+ if any(named) and not all(named):
87
+ raise ValueError('cannot mix named DataFrame and positional array panels')
88
+ matrices = {}
89
+ rows = columns = None
90
+ for name, value in zip(names, signals.values()):
91
+ shape = getattr(value, 'shape', None)
92
+ if shape is None:
93
+ shape = np.shape(value)
94
+ if len(shape) != 2 or min(shape) < 1:
95
+ raise ValueError('each signal panel must be a nonempty 2D matrix')
96
+ frame = value.copy(deep=True) if isinstance(value, pd.DataFrame) else pd.DataFrame(value)
97
+ if any(not pd.api.types.is_numeric_dtype(t) or pd.api.types.is_complex_dtype(t)
98
+ or pd.api.types.is_bool_dtype(t) for t in frame.dtypes):
99
+ raise ValueError('signal panels require real numeric values')
100
+ try:
101
+ array = frame.to_numpy(dtype=float, na_value=np.nan)
102
+ except (TypeError, ValueError) as exc:
103
+ raise ValueError('signal panels require finite real numeric values') from exc
104
+ if not np.isfinite(array).all():
105
+ raise ValueError('signal values must be finite; handle missing values explicitly')
106
+ frame = pd.DataFrame(array, index=_string_ids(frame.index, 'region'),
107
+ columns=_string_ids(frame.columns, 'bin'))
108
+ if rows is None:
109
+ rows, columns = frame.index, frame.columns
110
+ elif set(frame.index) != set(rows):
111
+ raise ValueError('panels must have exactly the same region identifiers')
112
+ elif not frame.columns.equals(columns):
113
+ raise ValueError('panels must have identical bin identifiers in the same order')
114
+ matrices[name] = frame.reindex(rows).copy(deep=True)
115
+ return matrices
116
+
117
+
118
+ def _groups(row_groups, rows):
119
+ if row_groups is None:
120
+ return pd.Series('All', index=rows, name='group')
121
+ if isinstance(row_groups, (pd.Series, Mapping)):
122
+ group = pd.Series(row_groups).copy()
123
+ group.index = _string_ids(group.index, 'row_groups')
124
+ if set(group.index) != set(rows):
125
+ raise ValueError('row_groups must cover exactly the region IDs')
126
+ group = group.reindex(rows)
127
+ else:
128
+ if isinstance(row_groups, str) or np.ndim(row_groups) != 1 or len(row_groups) != len(rows):
129
+ raise ValueError('row_groups must have one label per region')
130
+ group = pd.Series(row_groups, index=rows)
131
+ if group.isna().any():
132
+ raise ValueError('row_groups must not contain missing labels')
133
+ labels = pd.unique(group)
134
+ _string_ids(labels, 'row_groups label')
135
+ return group.map(str).rename('group')
136
+
137
+
138
+ def _permutation(order, rows):
139
+ if isinstance(order, str):
140
+ raise ValueError('row_order must be a complete permutation')
141
+ values = list(order)
142
+ if values and all(isinstance(v, (int, np.integer)) and not isinstance(v, (bool, np.bool_))
143
+ for v in values):
144
+ if sorted(values) != list(range(len(rows))):
145
+ raise ValueError('row_order must be a complete zero-based permutation')
146
+ return rows[np.asarray(values, dtype=int)].tolist()
147
+ values = list(map(str, values))
148
+ if len(values) != len(rows) or len(set(values)) != len(values) or set(values) != set(rows):
149
+ raise ValueError('row_order must contain each region ID exactly once')
150
+ return values
151
+
152
+
153
+ def prepare_signal_heatmap(signals, *, positions=None, row_groups=None,
154
+ group_order=None, row_order=None, order_by=None,
155
+ decreasing=True, cluster=None, n_clusters=3,
156
+ standardize=False, random_state=0):
157
+ """Prepare matching region-by-bin matrices and their group mean profiles.
158
+
159
+ ``signals`` maps panel names to dense finite numeric DataFrames or 2D arrays.
160
+ Named rows align by ID, with no bin-column reordering. ``positions`` gives
161
+ strictly increasing, equally spaced bin centres; omitted values are 0..n-1.
162
+ ``row_groups`` is an ID-indexed Series/mapping or labels in first-panel order.
163
+ Within each group the input order is retained, unless ``order_by`` selects
164
+ panel names whose region bin-means define a stable intensity order.
165
+
166
+ ``cluster='kmeans'`` groups those same region-by-panel mean signals, using
167
+ n_init=10 and random_state=0 by default. It does not cluster bin shapes.
168
+ ``standardize`` applies population z-scores to summary columns only (constant
169
+ columns become zero); it never normalizes the displayed signal or profiles.
170
+ Existing groups and clustering are mutually exclusive. Explicit ``row_order``
171
+ cannot be combined with sorting/clustering and must keep groups contiguous.
172
+ Group order defaults to first appearance, or cluster mean intensity descending.
173
+ """
174
+ for value, name in [(decreasing, 'decreasing'), (standardize, 'standardize')]:
175
+ if not isinstance(value, (bool, np.bool_)):
176
+ raise TypeError(name + ' must be boolean')
177
+ matrices = _signal_matrices(signals)
178
+ first = next(iter(matrices.values()))
179
+ rows, columns = first.index, first.columns
180
+ if positions is None:
181
+ positions = np.arange(len(columns), dtype=float)
182
+ try:
183
+ positions = np.asarray(positions, dtype=float)
184
+ except (TypeError, ValueError) as exc:
185
+ raise ValueError('positions must be finite numeric bin centres') from exc
186
+ if positions.shape != (len(columns),) or not np.isfinite(positions).all():
187
+ raise ValueError('positions must be finite and match the number of bins')
188
+ if len(positions) > 1 and (np.diff(positions) <= 0).any():
189
+ raise ValueError('positions must be strictly increasing')
190
+ if len(positions) > 2 and not np.allclose(np.diff(positions), np.diff(positions)[0], rtol=1e-7, atol=1e-10):
191
+ raise ValueError('positions must be equally spaced for equal-width heatmap bins')
192
+ summary = pd.DataFrame({name: frame.mean(axis=1) for name, frame in matrices.items()}, index=rows)
193
+ representation = summary.copy()
194
+ if standardize:
195
+ scale = representation.std(axis=0, ddof=0).replace(0, 1)
196
+ representation = (representation - representation.mean(axis=0)) / scale
197
+ if order_by is None:
198
+ selected = list(matrices)
199
+ else:
200
+ selected = [order_by] if isinstance(order_by, str) else list(order_by)
201
+ if not selected or len(set(selected)) != len(selected) or set(selected) - set(matrices):
202
+ raise ValueError('order_by must select unique existing panel names')
203
+ scores = representation[selected].mean(axis=1)
204
+ if cluster not in (None, 'kmeans'):
205
+ raise ValueError("cluster must be None or 'kmeans'; pass external clusters as row_groups")
206
+ if row_order is not None and (order_by is not None or cluster is not None):
207
+ raise ValueError('row_order cannot be combined with order_by or cluster')
208
+ groups = _groups(row_groups, rows)
209
+ if cluster is not None:
210
+ if row_groups is not None:
211
+ raise ValueError('cluster and row_groups are mutually exclusive')
212
+ if (isinstance(n_clusters, (bool, np.bool_)) or not isinstance(n_clusters, (int, np.integer))
213
+ or not 1 <= n_clusters <= len(rows)):
214
+ raise ValueError('n_clusters must be an integer between 1 and the region count')
215
+ if isinstance(random_state, (bool, np.bool_)) or not isinstance(random_state, (int, np.integer)) or not 0 <= random_state < 2**32:
216
+ raise ValueError('random_state must be an integer in [0, 2**32)')
217
+ values = representation[selected].to_numpy()
218
+ if len(np.unique(values, axis=0)) < n_clusters:
219
+ raise ValueError('n_clusters exceeds the number of distinct region summaries')
220
+ from sklearn.cluster import KMeans
221
+ labels = KMeans(n_clusters=int(n_clusters), n_init=10,
222
+ random_state=int(random_state)).fit_predict(values)
223
+ means = {k: float(scores.iloc[np.flatnonzero(labels == k)].mean()) for k in np.unique(labels)}
224
+ ranked = sorted(means, key=lambda k: (-means[k], k))
225
+ names = {label: 'Cluster ' + str(i + 1) for i, label in enumerate(ranked)}
226
+ groups = pd.Series([names[k] for k in labels], index=rows, name='group')
227
+ default_order = list(names.values())
228
+ else:
229
+ default_order = list(pd.unique(groups))
230
+ if group_order is not None:
231
+ if isinstance(group_order, str):
232
+ raise ValueError('group_order must list every group exactly once')
233
+ wanted = list(_string_ids(group_order, 'group_order'))
234
+ if set(wanted) != set(default_order):
235
+ raise ValueError('group_order must list every group exactly once')
236
+ else:
237
+ wanted = default_order
238
+ if row_order is not None:
239
+ order = _permutation(row_order, rows)
240
+ sequence = groups.loc[order].tolist()
241
+ blocks = [v for i, v in enumerate(sequence) if i == 0 or sequence[i - 1] != v]
242
+ if len(blocks) != len(set(blocks)):
243
+ raise ValueError('row_order must keep each group contiguous')
244
+ if group_order is not None and blocks != wanted:
245
+ raise ValueError('row_order conflicts with group_order')
246
+ wanted = blocks
247
+ else:
248
+ order = []
249
+ for group in wanted:
250
+ members = scores[groups == group]
251
+ if order_by is not None or cluster is not None:
252
+ members = members.sort_values(ascending=not decreasing, kind='stable')
253
+ order.extend(members.index)
254
+ profiles = {name: pd.DataFrame({group: frame.loc[groups == group].mean(axis=0)
255
+ for group in wanted}, index=columns)
256
+ for name, frame in matrices.items()}
257
+ return SignalHeatmapData(matrices, positions, groups, order, wanted, profiles, summary,
258
+ {'cluster': cluster, 'random_state': int(random_state) if cluster else None,
259
+ 'standardize': bool(standardize), 'order_by': selected if order_by is not None else None,
260
+ 'representation': 'region-by-panel arithmetic bin means',
261
+ 'profile_statistic': 'arithmetic mean across group regions per bin',
262
+ 'display_transform': 'none', 'missing_values': 'rejected',
263
+ 'n_regions': len(rows), 'n_bins': len(columns)})
264
+
265
+
266
+ def _panel_options(value, names, name):
267
+ if isinstance(value, Mapping):
268
+ if set(value) != set(names):
269
+ raise ValueError(name + ' mapping must contain exactly the panel names')
270
+ return dict(value)
271
+ return {key: value for key in names}
272
+
273
+
274
+ def _limits(value, arrays, shared, name, zero=False):
275
+ options = _panel_options(value, arrays, name)
276
+ limits = {}
277
+ for key, array in arrays.items():
278
+ pair = options[key]
279
+ if pair is None:
280
+ low, high = float(np.min(array)), float(np.max(array))
281
+ if zero:
282
+ low, high = min(0., low), max(0., high)
283
+ if low == high:
284
+ padding = max(abs(low) * .05, .5)
285
+ low, high = low - padding, high + padding
286
+ else:
287
+ try:
288
+ pair = np.asarray(pair, dtype=float)
289
+ except (TypeError, ValueError) as exc:
290
+ raise ValueError(name + ' must be a finite (min, max) pair') from exc
291
+ if pair.shape != (2,) or not np.isfinite(pair).all() or pair[0] >= pair[1]:
292
+ raise ValueError(name + ' must have finite min < max')
293
+ low, high = map(float, pair)
294
+ limits[key] = (low, high)
295
+ if shared:
296
+ pair = (min(v[0] for v in limits.values()), max(v[1] for v in limits.values()))
297
+ limits = {key: pair for key in arrays}
298
+ return limits
299
+
300
+
301
+ _PREPARATION_OPTIONS = {
302
+ 'positions', 'row_groups', 'group_order', 'row_order', 'order_by',
303
+ 'decreasing', 'cluster', 'n_clusters', 'standardize', 'random_state',
304
+ }
305
+
306
+
307
+ def _visual_options(kwargs):
308
+ """Prevent Heatmap options from contradicting the prepared scientific state."""
309
+ fixed = {'z_score': False, 'symmetric': False, 'row_cluster': False,
310
+ 'col_cluster': False, 'cluster_rows': False, 'cluster_columns': False,
311
+ 'row_compression': 1, 'col_compression': 1, 'reverse_columns': False,
312
+ 'cluster_order': None, 'row_cluster_order': None,
313
+ 'col_cluster_order': None, 'style': 'complexheatmap'}
314
+ reserved = {'config', 'df_filter', 'row_split', 'col_split', 'column_split',
315
+ 'column_order', 'row_cluster_map', 'col_cluster_map', 'row_km',
316
+ 'column_km', 'km', 'split', 'jitter', 'row_distance', 'col_distance',
317
+ 'row_linkage_input', 'col_linkage_input', 'cluster_row_slices',
318
+ 'cluster_column_slices', 'column_labels', 'cmap', 'col', 'vmin',
319
+ 'vmax', 'top_annotation', 'name', 'heatmap_name', 'matrix', 'df',
320
+ 'width', 'width_mm', 'height', 'row_dend_reorder', 'column_dend_reorder',
321
+ 'row_km_repeats', 'column_km_repeats'}
322
+ for key in reserved & set(kwargs):
323
+ raise ValueError(key + ' conflicts with SignalHeatmap preparation; use its dedicated controls')
324
+ for key, expected in fixed.items():
325
+ if key in kwargs:
326
+ value = kwargs.pop(key)
327
+ if not np.isscalar(value) and value is not None or value != expected:
328
+ raise ValueError(key + ' conflicts with the prepared signal heatmap')
329
+ # Explicit canonical controls also take precedence over ht_opt defaults.
330
+ kwargs.update({key: value for key, value in fixed.items()
331
+ if key not in ('cluster_rows', 'cluster_columns')})
332
+ return kwargs
333
+
334
+
335
+ class SignalHeatmap(HeatmapList):
336
+ """Native aligned signal heatmaps with group mean profiles above each panel.
337
+
338
+ Accept a :class:`SignalHeatmapData` or raw signals; raw input also accepts
339
+ prepare_signal_heatmap's keyword options. Preparation options are rejected
340
+ for an existing prepared result. ``prepared`` exposes the reusable snapshot.
341
+
342
+ ``palettes`` is a Heatmap palette or an exact panel-name mapping of palettes.
343
+ ``color_limits`` and ``profile_limits`` accept None (automatic), a finite
344
+ (low, high) pair, or an exact panel-name mapping. Automatic heatmap limits
345
+ use original matrix extrema; automatic profile limits include zero. Constant
346
+ domains receive symmetric padding. Each shared_*_scale independently uses
347
+ the union of the corresponding panel limits, including explicit limits.
348
+ Changing limits clips only the display, never the signal/profile data.
349
+
350
+ ``group_colors`` maps every group to a color; omitted colors are generated
351
+ deterministically. A group stripe/legend on the first panel matches curves.
352
+ Sizes are mm. Position labels show first/middle/last bin centres and an
353
+ optional unit suffix; omitted positions denote zero-based bin numbers.
354
+ Remaining kwargs are native Heatmap appearance options, such as dpi,
355
+ render_backend, font_family, legend controls and side annotations. Controls
356
+ that regroup, normalize, filter or reorder prepared values are rejected.
357
+ SVG/PNG/PDF, save() and draw() use the existing native HeatmapList path.
358
+ """
359
+
360
+ def __init__(self, signals, *, palettes='Reds', color_limits=None,
361
+ shared_color_scale=False, profile_limits=None,
362
+ shared_profile_scale=False, group_colors=None, show_profiles=True,
363
+ profile_height_mm=20, panel_width_mm=35, height_mm=140,
364
+ gap_mm=4, position_unit='', **kwargs):
365
+ preparation = {key: kwargs.pop(key) for key in _PREPARATION_OPTIONS if key in kwargs}
366
+ if isinstance(signals, SignalHeatmapData):
367
+ if preparation:
368
+ raise ValueError('prepared signal data cannot accept preparation options; prepare a new result')
369
+ self.prepared = signals
370
+ else:
371
+ self.prepared = prepare_signal_heatmap(signals, **preparation)
372
+ for value, name in [(shared_color_scale, 'shared_color_scale'),
373
+ (shared_profile_scale, 'shared_profile_scale'),
374
+ (show_profiles, 'show_profiles')]:
375
+ if not isinstance(value, (bool, np.bool_)):
376
+ raise TypeError(name + ' must be boolean')
377
+ for value, name in [(profile_height_mm, 'profile_height_mm'),
378
+ (panel_width_mm, 'panel_width_mm'), (height_mm, 'height_mm')]:
379
+ if (isinstance(value, (bool, np.bool_)) or not np.isscalar(value)
380
+ or not np.isfinite(value) or value <= 0):
381
+ raise ValueError(name + ' must be positive finite mm')
382
+ if not isinstance(position_unit, str):
383
+ raise TypeError('position_unit must be a string')
384
+ kwargs = _visual_options(dict(kwargs))
385
+ data = self.prepared
386
+ matrices, profiles = data._matrices, data._profiles
387
+ self.color_limits = _limits(color_limits, {k: v.to_numpy() for k, v in matrices.items()},
388
+ shared_color_scale, 'color_limits')
389
+ self.profile_limits = _limits(profile_limits, {k: v.to_numpy() for k, v in profiles.items()},
390
+ shared_profile_scale, 'profile_limits', zero=True)
391
+ palette_options = _panel_options(palettes, matrices, 'palettes')
392
+ if group_colors is None:
393
+ from .palettes import discrete_colors
394
+ from matplotlib.colors import to_hex
395
+ colors = discrete_colors(len(data._group_order))
396
+ group_colors = {group: to_hex(np.asarray(colors[i]) / 255)
397
+ for i, group in enumerate(data._group_order)}
398
+ elif not isinstance(group_colors, Mapping) or set(group_colors) != set(data._group_order):
399
+ raise ValueError('group_colors must map exactly the prepared group names to colors')
400
+ from .graphics import color
401
+ self.group_colors = {group: color(group_colors[group]) for group in data._group_order}
402
+ bins = next(iter(matrices.values())).columns
403
+ labels = {key: '' for key in bins}
404
+ for i in sorted({0, len(bins) // 2, len(bins) - 1}):
405
+ labels[bins[i]] = f'{data._positions[i]:g}' + (' ' + position_unit if position_unit else '')
406
+ panels = []
407
+ for i, (name, frame) in enumerate(matrices.items()):
408
+ options = dict(kwargs)
409
+ options.setdefault('ordering', None)
410
+ if 'show_row_names' not in options:
411
+ options.setdefault('show_rownames', False)
412
+ if 'show_column_names' not in options:
413
+ options.setdefault('show_colnames', True)
414
+ options.setdefault('column_names_rot', 0)
415
+ options.setdefault('column_title', name)
416
+ if 'show_row_dend' not in options:
417
+ options.setdefault('row_dendro', False)
418
+ if 'show_column_dend' not in options:
419
+ options.setdefault('col_dendro', False)
420
+ # There are at most three labelled position ticks. Preserve all of
421
+ # them instead of applying the dense matrix-name sampling policy.
422
+ options.setdefault('label_policy', 'all')
423
+ left = options.pop('left_annotation', None)
424
+ if i == 0:
425
+ stripe = rowAnnotation(df=data._groups.to_frame('Group'),
426
+ col={'Group': self.group_colors},
427
+ show_annotation_name=False,
428
+ show_legend=len(data._group_order) > 1)
429
+ left = list(stripe) + ([] if left is None else list(left) if isinstance(left, (list, tuple)) else [left])
430
+ annotation = None
431
+ if show_profiles:
432
+ lines = LinesAnnotation(profiles[name], ylim=self.profile_limits[name], extend=0,
433
+ gp={'col': [self.group_colors[g] for g in data._group_order]},
434
+ add_points=len(bins) == 1, border=False)
435
+ annotation = HeatmapAnnotation(Profile=lines, annotation_height=profile_height_mm,
436
+ show_annotation_name=False, show_legend=False)
437
+ lo, hi = self.color_limits[name]
438
+ panel = Heatmap(frame, name=name, col=palette_options[name],
439
+ row_order=data._order, row_split=data._groups,
440
+ column_order=bins, column_labels=labels, top_annotation=annotation,
441
+ left_annotation=left, width_mm=panel_width_mm, height_mm=height_mm,
442
+ vmin=lo, vmax=hi, **options)
443
+ if 'row_title_gp' not in kwargs:
444
+ panel._slice_title_colors = {'row': dict(self.group_colors)}
445
+ panels.append(panel)
446
+ super().__init__(*panels, direction='horizontal', gap_mm=gap_mm, layout='aligned')
447
+
448
+ def _repr_svg_(self):
449
+ from .api import draw
450
+ return draw(self)
451
+
452
+
453
+ __all__ = ['SignalHeatmapData', 'prepare_signal_heatmap', 'SignalHeatmap']