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/single_cell.py ADDED
@@ -0,0 +1,251 @@
1
+ """Explicit cell graph clustering and blockwise group summaries.
2
+
3
+ These operations never normalise expression, infer a graph/embedding choice,
4
+ modify AnnData, or replace the heatmap's existing clustering defaults.
5
+ """
6
+ from dataclasses import dataclass
7
+ from importlib.metadata import version
8
+ import numpy as np
9
+ import pandas as pd
10
+ from scipy import sparse
11
+ from .matrix_source import MatrixSource
12
+
13
+ DEFAULT_MAX_BYTES = 256 * 1024**2
14
+
15
+
16
+ def _budget(max_bytes, required):
17
+ if isinstance(max_bytes, (bool, np.bool_)) or not isinstance(max_bytes, (int,np.integer)) or max_bytes < 1:
18
+ raise ValueError('max_bytes must be a positive integer')
19
+ if required > max_bytes:
20
+ raise MemoryError(f'estimated operation workspace {required:,} exceeds max_bytes={max_bytes:,}; subset the input or explicitly raise the budget')
21
+
22
+
23
+ def _ids(cell_ids, n):
24
+ ids=pd.Index(range(n) if cell_ids is None else cell_ids)
25
+ if ids.hasnans:raise ValueError('cell IDs must not be missing')
26
+ ids=ids.map(str)
27
+ if len(ids)!=n or not ids.is_unique:
28
+ raise ValueError('cell IDs must be unique and match the input length')
29
+ return ids
30
+
31
+
32
+ @dataclass
33
+ class GroupSummary:
34
+ mean_expression: pd.DataFrame
35
+ fraction_detected: pd.DataFrame
36
+ group_sizes: pd.Series
37
+ report: dict
38
+
39
+ def dot_heatmap(self, **kwargs):
40
+ from .dot_heatmap import DotHeatmap
41
+ kwargs.setdefault('name','Mean expression')
42
+ kwargs.setdefault('size_legend_title','Fraction detected')
43
+ result=DotHeatmap(self.mean_expression,self.fraction_detected,**kwargs)
44
+ result.group_summary=self
45
+ return result
46
+
47
+
48
+ def aggregate_groups(source, groups, *, detection_threshold=0., group_order=None,
49
+ max_bytes=DEFAULT_MAX_BYTES):
50
+ """Arithmetic mean and fraction(value > threshold), including sparse zeros.
51
+
52
+ Every selected cell is in the denominator. Nonfinite expression and missing
53
+ labels fail explicitly; nothing is log transformed or imputed here. The
54
+ budget is a conservative numeric payload/workspace estimate, not an RSS cap.
55
+ """
56
+ if not isinstance(source,MatrixSource):
57
+ from .matrix_source import as_matrix_source
58
+ source=as_matrix_source(source,dtype=np.float64)
59
+ source._ensure_open()
60
+ if not np.isscalar(detection_threshold) or not np.isfinite(detection_threshold):
61
+ raise ValueError('detection_threshold must be finite')
62
+ nr,nc=source.shape
63
+ _budget(max_bytes,128*(nr+nc))
64
+ if isinstance(groups,pd.Series):
65
+ labels=groups.copy();labels.index=labels.index.map(str)
66
+ if not labels.index.is_unique:raise ValueError('group cell IDs must be unique')
67
+ labels=labels.reindex(source.columns)
68
+ else:
69
+ if len(groups)!=nc:raise ValueError('group labels must match source cells')
70
+ labels=pd.Series(groups,index=source.columns)
71
+ if labels.isna().any():raise ValueError('group labels must cover all selected cells without missing values')
72
+ observed=list(pd.unique(labels))
73
+ levels=([v for v in labels.cat.categories if v in observed]
74
+ if isinstance(labels.dtype,pd.CategoricalDtype) else observed)
75
+ names=list(map(str,levels))
76
+ if len(set(names))!=len(names):raise ValueError('group labels must be unique after string conversion')
77
+ if group_order is not None:
78
+ order=list(map(str,group_order))
79
+ if len(order)!=len(names) or set(order)!=set(names):raise ValueError('group_order must contain every observed group exactly once')
80
+ names=order
81
+ lookup={name:i for i,name in enumerate(names)}
82
+ codes=np.array([lookup[str(v)] for v in labels],dtype=np.int64)
83
+ counts=np.bincount(codes,minlength=len(names))
84
+ required=48*nr*len(names)+128*(nr+nc+len(names))+source._cell_workspace_bytes*min(source.max_block_cells,nr*nc)
85
+ _budget(max_bytes,required)
86
+ totals=np.zeros((nr,len(names)),dtype=np.float64)
87
+ detected=np.zeros_like(totals,dtype=np.int64)
88
+ start_calls=source.read_calls
89
+ for r,c,block in source.blocks():
90
+ if not np.isfinite(block).all():raise ValueError('group aggregation requires finite expression values')
91
+ local=codes[c:c+block.shape[1]]
92
+ for code in np.unique(local):
93
+ values=block[:,local==code]
94
+ totals[r:r+len(block),code]+=values.sum(axis=1,dtype=np.float64)
95
+ detected[r:r+len(block),code]+=np.count_nonzero(values>np.float64(detection_threshold),axis=1)
96
+ means=pd.DataFrame(totals/counts,index=source.index.copy(),columns=names)
97
+ fractions=pd.DataFrame(detected/counts,index=source.index.copy(),columns=names)
98
+ report={'aggregation':'arithmetic mean of all selected cells',
99
+ 'detection_rule':'value > detection_threshold','detection_threshold':float(detection_threshold),
100
+ 'denominator':'all selected cells in group','input_shape':source.shape,
101
+ 'source':dict(getattr(source,'provenance',{})),'input_kind':source.kind,
102
+ 'estimated_workspace_bytes':required,'max_bytes':int(max_bytes),
103
+ 'max_read_cells':source.max_read_cells,'read_calls':source.read_calls-start_calls,
104
+ 'missing_values':'rejected','normalisation':'none'}
105
+ report.update(block_dtype=str(source.dtype),accumulation_dtype='float64')
106
+ return GroupSummary(means,fractions,pd.Series(counts,index=names,name='n_cells'),report)
107
+
108
+
109
+ @dataclass
110
+ class CellClusteringResult:
111
+ labels: pd.Series
112
+ report: dict
113
+ linkage: object = None
114
+
115
+ def as_algorithm_result(self):
116
+ """Copy this identity-bound partition into the common extension contract."""
117
+ from .algorithm_types import AlgorithmResult
118
+ return AlgorithmResult.from_labels(self.labels, linkage=self.linkage,
119
+ method=self.report.get('method', 'external'),
120
+ random_state=self.report.get('random_state'), report=self.report)
121
+
122
+
123
+ def _graph_estimate(graph, backend=False):
124
+ if getattr(graph,'ndim',None)!=2 or graph.shape[0]!=graph.shape[1] or graph.shape[0]<1:
125
+ raise ValueError('cell graph must be a nonempty square matrix')
126
+ n=graph.shape[0]
127
+ entries=graph.nnz if sparse.issparse(graph) else n*n
128
+ return int((512 if backend else 48)*entries+(1024 if backend else 128)*(n+1))
129
+
130
+
131
+ def cell_graph(adata, key, *, max_bytes=DEFAULT_MAX_BYTES):
132
+ """Copy an observation-aligned graph, preserving sparse storage and weights."""
133
+ if key not in adata.obsp:raise KeyError(f'graph {key!r} not in AnnData.obsp')
134
+ graph=adata.obsp[key]
135
+ required=_graph_estimate(graph)
136
+ _budget(max_bytes,required)
137
+ if graph.shape!=(adata.n_obs,adata.n_obs):raise ValueError('graph must match observation IDs')
138
+ return sparse.csr_matrix(graph,copy=True)
139
+
140
+
141
+ def _normalise_graph(graph, symmetrize, max_bytes):
142
+ required=_graph_estimate(graph,backend=True)
143
+ _budget(max_bytes,required)
144
+ if symmetrize not in (None,'max'):raise ValueError("symmetrize must be None or 'max'")
145
+ dtypes=graph.dtypes if isinstance(graph,pd.DataFrame) else [graph.dtype]
146
+ if any(not pd.api.types.is_numeric_dtype(t) or pd.api.types.is_complex_dtype(t) for t in dtypes):
147
+ raise ValueError('graph weights must be real numeric values')
148
+ graph=sparse.csr_matrix(graph,dtype=np.float64,copy=True)
149
+ if not np.isfinite(graph.data).all() or np.any(graph.data<0):
150
+ raise ValueError('graph weights must be finite and nonnegative')
151
+ graph.sum_duplicates();graph.setdiag(0);graph.eliminate_zeros();graph.sort_indices()
152
+ if symmetrize=='max':graph=graph.maximum(graph.T)
153
+ elif (graph!=graph.T).nnz:raise ValueError("graph must be symmetric; explicitly choose symmetrize='max' if intended")
154
+ return graph,required
155
+
156
+
157
+ def _knn_graph(embedding,n_neighbors,max_bytes):
158
+ from scipy.spatial import cKDTree
159
+ if sparse.issparse(embedding) or getattr(embedding,'ndim',None)!=2 or min(embedding.shape)<1:
160
+ raise ValueError('embedding must be a nonempty dense cells x dimensions matrix; use graph for sparse adjacency')
161
+ n,d=embedding.shape
162
+ if isinstance(n_neighbors,(bool,np.bool_)) or not isinstance(n_neighbors,(int,np.integer)) or not 1<=n_neighbors<n:
163
+ raise ValueError('n_neighbors must be an integer between 1 and number of cells minus 1')
164
+ # Include an upper bound for the union graph AND its community backend
165
+ # before constructing tree/query/graph buffers, not after allocation.
166
+ required=int(24*n*d+512*n+256*n*(int(n_neighbors)+1)
167
+ +1024*n*int(n_neighbors)+1024*(n+1))
168
+ _budget(max_bytes,required)
169
+ values=np.asarray(embedding,dtype=np.float64)
170
+ if not np.isfinite(values).all():raise ValueError('embedding values must be finite')
171
+ _,neighbors=cKDTree(values).query(values,k=int(n_neighbors)+1,workers=1)
172
+ rows=[];cols=[]
173
+ for i,near in enumerate(neighbors):
174
+ chosen=near[near!=i][:int(n_neighbors)]
175
+ rows.extend([i]*len(chosen));cols.extend(chosen)
176
+ graph=sparse.csr_matrix((np.ones(len(rows)),(rows,cols)),shape=(n,n))
177
+ return graph.maximum(graph.T),required
178
+
179
+
180
+ def cluster_cells(graph=None, *, embedding=None, cell_ids=None, method='leiden',
181
+ resolution=1., random_state=0, n_neighbors=15, symmetrize=None,
182
+ max_bytes=DEFAULT_MAX_BYTES):
183
+ """Explicit CPU community detection with no implicit expression/reduction step.
184
+
185
+ Leiden: weighted RBConfiguration partition via leidenalg/igraph, two
186
+ iterations. Louvain: NetworkX weighted modularity. Labels are communities,
187
+ not a hierarchy; no dendrogram is manufactured. Cross-version bitwise
188
+ reproducibility and a total-RSS memory guarantee are not implied.
189
+ """
190
+ if (graph is None)==(embedding is None):raise ValueError('supply exactly one of graph or embedding')
191
+ if method not in ('leiden','louvain'):raise ValueError("method must be 'leiden' or 'louvain'")
192
+ if not np.isscalar(resolution) or not np.isfinite(resolution) or resolution<=0:
193
+ raise ValueError('resolution must be positive and finite')
194
+ if random_state is not None and (isinstance(random_state,(bool,np.bool_)) or not isinstance(random_state,(int,np.integer)) or not 0<=random_state<2**31):
195
+ raise ValueError('random_state must be None or an integer in [0, 2**31)')
196
+ if embedding is not None:
197
+ if cell_ids is None and isinstance(embedding,pd.DataFrame):cell_ids=embedding.index
198
+ graph,embedding_required=_knn_graph(embedding,n_neighbors,max_bytes)
199
+ else:embedding_required=0
200
+ if isinstance(graph,pd.DataFrame):
201
+ if not graph.index.map(str).equals(graph.columns.map(str)):
202
+ raise ValueError('graph row and column IDs must match in the same order')
203
+ if cell_ids is None:cell_ids=graph.index
204
+ elif not pd.Index(cell_ids).map(str).equals(graph.index.map(str)):
205
+ raise ValueError('cell IDs must match the labelled graph')
206
+ graph,required=_normalise_graph(graph,symmetrize,max_bytes)
207
+ required=max(required,embedding_required)
208
+ ids=_ids(cell_ids,graph.shape[0])
209
+ upper=sparse.triu(graph,k=1,format='coo')
210
+ seed=None if random_state is None else int(random_state)
211
+ versions={}
212
+ try:
213
+ if method=='leiden':
214
+ import igraph as ig
215
+ import leidenalg as la
216
+ versions={name:version(name) for name in ('igraph','leidenalg')}
217
+ if graph.nnz:
218
+ g=ig.Graph(n=len(ids),edges=list(zip(upper.row.tolist(),upper.col.tolist())),directed=False)
219
+ partition=la.find_partition(g,la.RBConfigurationVertexPartition,
220
+ weights=upper.data.tolist(),resolution_parameter=float(resolution),seed=seed,n_iterations=2)
221
+ memberships=np.asarray(partition.membership)
222
+ else:memberships=np.arange(len(ids))
223
+ backend='leidenalg/igraph'
224
+ else:
225
+ import networkx as nx
226
+ versions={'networkx':version('networkx')}
227
+ if graph.nnz:
228
+ g=nx.from_scipy_sparse_array(graph,create_using=nx.Graph)
229
+ communities=nx.community.louvain_communities(g,weight='weight',resolution=float(resolution),seed=seed,backend='networkx')
230
+ memberships=np.empty(len(ids),dtype=np.int64)
231
+ for code,community in enumerate(communities):memberships[list(community)]=code
232
+ else:memberships=np.arange(len(ids))
233
+ backend='networkx'
234
+ except ImportError as e:
235
+ raise ImportError("cell graph clustering needs optional dependencies; install tilesig[single-cell]") from e
236
+ # Canonicalise arbitrary backend labels by first cell occurrence.
237
+ labels=pd.Series(pd.factorize(memberships,sort=False)[0].astype(str),index=ids,name=method)
238
+ report={'method':method,'backend':backend,'versions':versions,'device':'cpu',
239
+ 'resolution':float(resolution),'random_state':seed,
240
+ 'input':'embedding' if embedding is not None else 'graph',
241
+ 'graph_policy':'binary union kNN' if embedding is not None else 'remove diagonal; '+('maximum symmetrisation' if symmetrize else 'require symmetry'),
242
+ 'n_neighbors':int(n_neighbors) if embedding is not None else None,
243
+ 'n_cells':len(ids),'n_edges':len(upper.data),'n_clusters':int(labels.nunique()),
244
+ 'estimated_workspace_bytes':required,'max_bytes':int(max_bytes),
245
+ 'objective':'RBConfiguration' if method=='leiden' else 'weighted modularity',
246
+ 'n_iterations':2 if method=='leiden' else None,
247
+ 'threshold':1e-7 if method=='louvain' else None,'fallback':None}
248
+ return CellClusteringResult(labels,report)
249
+
250
+
251
+ __all__=['GroupSummary','CellClusteringResult','aggregate_groups','cluster_cells']
@@ -0,0 +1,100 @@
1
+ """Opt-in slice drawing with stable labels and no full-grid coordinates."""
2
+ from dataclasses import dataclass, field
3
+ from html import escape
4
+ import numbers
5
+
6
+ import numpy as np
7
+ from .slice_geometry import slice_gaps
8
+ from .graphics import color as svg_color
9
+
10
+
11
+ def _finite(value, name, *, positive=False):
12
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, numbers.Real) or not np.isfinite(value):
13
+ raise ValueError(f'{name} must be finite numeric')
14
+ if positive and value <= 0:
15
+ raise ValueError(f'{name} must be positive')
16
+ return float(value)
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class HeatmapSliceContext:
21
+ """One displayed row-slice/column-slice intersection.
22
+
23
+ Slice numbers and cell indices are zero-based. Geometry is in canvas pixels.
24
+ Values are obtained lazily; they are displayed values after transformations,
25
+ with categorical codes decoded to labels, in a read-only array. Keep this
26
+ object only for the duration of its callback. Drawing helper sizes are pt.
27
+ """
28
+ row_slice: int
29
+ column_slice: int
30
+ row_ids: tuple
31
+ column_ids: tuple
32
+ x: float
33
+ y: float
34
+ width: float
35
+ height: float
36
+ _plotter: object = field(repr=False, compare=False)
37
+ _sink: object = field(repr=False, compare=False)
38
+ _bounds: tuple = field(repr=False)
39
+
40
+ @property
41
+ def values(self):
42
+ r0, r1, c0, c1 = self._bounds
43
+ values = np.asarray(self._plotter._matrix_sorted[r0:r1, c0:c1])
44
+ labels = getattr(self._plotter, '_category_labels', None)
45
+ if labels is not None:
46
+ values = np.array([[labels.get(int(v), None) if np.isfinite(v) else None
47
+ for v in row] for row in values], dtype=object)
48
+ else:
49
+ values = values.view()
50
+ values.flags.writeable = False
51
+ return values
52
+
53
+ def cell_center(self, row, column):
54
+ """Canvas-pixel centre of one local cell; bounds checked."""
55
+ for index, size in [(row, len(self.row_ids)), (column, len(self.column_ids))]:
56
+ if isinstance(index, (bool, np.bool_)) or not isinstance(index, numbers.Integral) or not 0 <= index < size:
57
+ raise IndexError('slice cell index must be a zero-based integer within the slice')
58
+ return (self.x + (column + .5) * self.width / len(self.column_ids),
59
+ self.y + (row + .5) * self.height / len(self.row_ids))
60
+
61
+ def rect(self, *, fill=None, stroke='black', line_width=1):
62
+ """Draw the slice rectangle; line width in points."""
63
+ width = _finite(line_width, 'line_width')
64
+ if width < 0:raise ValueError('line_width must be nonnegative')
65
+ self._sink.write(f'<rect x="{self.x}" y="{self.y}" width="{self.width}" height="{self.height}" '
66
+ f'fill="{svg_color(fill)}" stroke="{svg_color(stroke)}" '
67
+ f'stroke-width="{self._plotter._appearance.pt(width)}"/>')
68
+
69
+ def text(self, text, *, x=.5, y=.5, font_size=10, color='black'):
70
+ """Draw centred text; x/y are fractions of slice width/height."""
71
+ x = _finite(x, 'x');y = _finite(y, 'y')
72
+ size = self._plotter._appearance.pt(_finite(font_size, 'font_size', positive=True))
73
+ family = escape(self._plotter._appearance.font_family, quote=True)
74
+ self._sink.write(f'<text x="{self.x+x*self.width}" y="{self.y+y*self.height}" '
75
+ f'font-size="{size}" font-family="{family}" fill="{svg_color(color)}" '
76
+ f'text-anchor="middle" dominant-baseline="middle">{escape(str(text))}</text>')
77
+
78
+ def line(self, x1, y1, x2, y2, *, color='black', line_width=1):
79
+ """Draw a line between fractional slice coordinates; width in points."""
80
+ x1,y1,x2,y2 = [_finite(v,n) for v,n in zip((x1,y1,x2,y2), ('x1','y1','x2','y2'))]
81
+ width = _finite(line_width, 'line_width')
82
+ if width < 0:raise ValueError('line_width must be nonnegative')
83
+ self._sink.write(f'<line x1="{self.x+x1*self.width}" y1="{self.y+y1*self.height}" '
84
+ f'x2="{self.x+x2*self.width}" y2="{self.y+y2*self.height}" '
85
+ f'stroke="{svg_color(color)}" stroke-width="{self._plotter._appearance.pt(width)}"/>')
86
+
87
+
88
+ def draw_slices(plotter, sink, x, y, cell_width, cell_height):
89
+ callback = plotter._visual_options.get('slice_fun')
90
+ if callback is None:return
91
+ from .appearance import _coord
92
+ nr,nc = plotter._matrix_sorted.shape
93
+ for ri,(r0,r1) in enumerate(plotter._get_bounds(nr, plotter.row_breaks)):
94
+ for ci,(c0,c1) in enumerate(plotter._get_bounds(nc, plotter.col_breaks)):
95
+ ctx = HeatmapSliceContext(ri,ci,tuple(map(str,plotter.row_names[r0:r1])),
96
+ tuple(map(str,plotter.col_names[c0:c1])),
97
+ x+_coord(c0,cell_width,plotter.col_breaks,slice_gaps(plotter,'column')),
98
+ y+_coord(r0,cell_height,plotter.row_breaks,slice_gaps(plotter,'row')),
99
+ (c1-c0)*cell_width,(r1-r0)*cell_height,plotter,sink,(r0,r1,c0,c1))
100
+ callback(ctx)
@@ -0,0 +1,48 @@
1
+ """One geometry contract for scalar or explicitly unequal slice boundaries."""
2
+ import numpy as np
3
+
4
+
5
+ class _GapVector(np.ndarray):
6
+ def __new__(cls,values):
7
+ obj=np.asarray(values,float).view(cls)
8
+ obj.prefix=np.r_[0.,np.cumsum(values)]
9
+ return obj
10
+
11
+ def __array_finalize__(self,source):
12
+ self.prefix=getattr(source,'prefix',None)
13
+
14
+
15
+ def slice_gaps(p,axis):
16
+ return getattr(p,'_'+axis+'_slice_gaps',p.row_gap_pixels if axis=='row' else p.col_gap_pixels)
17
+
18
+
19
+ def gap_total(gap,count):
20
+ return float(np.sum(gap)) if np.ndim(gap) else count*gap
21
+
22
+
23
+ def gap_at(gap,index):
24
+ if np.ndim(gap):return float(gap[index]) if index<len(gap) else 0.
25
+ return gap
26
+
27
+
28
+ def gap_offset(gap,count):
29
+ return float(gap.prefix[count]) if isinstance(gap,_GapVector) else float(np.sum(gap[:count])) if np.ndim(gap) else count*gap
30
+
31
+
32
+ def configure(p,axis,raw,breaks):
33
+ key='row_gap_pixels' if axis=='row' else 'col_gap_pixels'
34
+ if raw is None:
35
+ value=getattr(p,key)
36
+ if not np.isfinite(value) or value<0:raise ValueError('slice gaps must be finite and nonnegative')
37
+ setattr(p,'_'+axis+'_slice_gaps',value)
38
+ return value
39
+ values=np.asarray(raw,dtype=float)
40
+ if values.ndim==0:
41
+ if not np.isfinite(values) or values<0:raise ValueError('slice gaps must be finite and nonnegative')
42
+ value=p._appearance.mm(float(values));setattr(p,key,value)
43
+ else:
44
+ if values.ndim!=1 or len(values)!=len(breaks):raise ValueError(axis+' gap vector must have one value per slice boundary')
45
+ if not np.isfinite(values).all() or np.any(values<0):raise ValueError('slice gaps must be finite and nonnegative')
46
+ value=_GapVector(values*p.dpi/25.4)
47
+ setattr(p,'_'+axis+'_slice_gaps',value)
48
+ return value
@@ -0,0 +1,80 @@
1
+ """Slice-level summary annotation for a one-column or one-row heatmap."""
2
+ import numpy as np
3
+ from .slice_geometry import gap_total
4
+ import pandas as pd
5
+
6
+ from .annotation import AnnotationBase
7
+
8
+
9
+ class SliceSummaryAnnotation(AnnotationBase):
10
+ """Category proportions or numeric Tukey boxes across orthogonal slices.
11
+
12
+ This complements the retained per-item SummaryAnnotation. It reads the
13
+ finalized owning heatmap and requires a single column (column annotation)
14
+ or single row (row annotation). Values and cluster assignments are unchanged.
15
+ """
16
+ n_tracks=1
17
+ _draws_own_border=True
18
+ _default_height_mm=20
19
+ def __init__(self,*,which='column',side=None,bar_width=.8,box_width=.6,
20
+ axis=True,axis_param=None,border=True,ylim=None,outline=True,
21
+ height=None,fontsize=None,label=None,gp=None,box_color='#cccccc'):
22
+ if which not in ('column','row'):raise ValueError('which must be column or row')
23
+ side=side or ('left' if which=='row' else 'top')
24
+ if side not in ('top','bottom','left','right'):raise ValueError('invalid summary side')
25
+ if (side in ('left','right'))!=(which=='row'):raise ValueError('side conflicts with which')
26
+ if not 0<bar_width<=1 or not 0<box_width<=1:raise ValueError('bar/box width must lie in (0,1]')
27
+ from .axes import axis_parameters
28
+ axis_parameters(axis_param,which)
29
+ super().__init__(df=None,side=side,height=height,fontsize=fontsize,label=label)
30
+ self.bar_width=bar_width;self.box_width=box_width;self.axis=bool(axis)
31
+ self.axis_param=dict(axis_param or {});self.border=bool(border);self.ylim=ylim
32
+ self.outline=bool(outline);self.gp=gp;self.box_color=box_color
33
+ self._show_legend=False
34
+
35
+ def summary_data(self,p):
36
+ p._compute_clustering()
37
+ row=self.side in ('left','right')
38
+ values=np.asarray(p._matrix_sorted).T if row else np.asarray(p._matrix_sorted)
39
+ if values.shape[1]!=1:raise ValueError('slice summary requires a single row or single column heatmap')
40
+ breaks=p.col_breaks if row else p.row_breaks
41
+ bounds=p._get_bounds(len(values),breaks)
42
+ groups=[values[start:end,0] for start,end in bounds]
43
+ labels=[f'Slice {i+1}' for i in range(len(groups))]
44
+ if getattr(p,'_category_colors',None) is not None:
45
+ if self.ylim is not None:raise ValueError('categorical slice summary has fixed proportions in [0,1]; ylim is unsupported')
46
+ codes=list(p._category_labels)
47
+ counts=np.asarray([[np.sum(group==code) for code in codes] for group in groups],dtype=float)
48
+ totals=counts.sum(axis=1,keepdims=True)
49
+ proportions=np.divide(counts,totals,out=np.zeros_like(counts),where=totals>0)
50
+ return pd.DataFrame(proportions,index=labels,columns=[p._category_labels[code] for code in codes])
51
+ return pd.Series([group[np.isfinite(group)] for group in groups],index=labels,dtype=object)
52
+
53
+ def _resolved(self,p):
54
+ data=self.summary_data(p)
55
+ options=dict(side=self.side,height=self.height,fontsize=self.fontsize,label=self.label,
56
+ axis=self.axis,axis_param=self.axis_param,border=self.border)
57
+ if isinstance(data,pd.DataFrame):
58
+ from .barplot import StackedBarAnnotation
59
+ colors={p._category_labels[code]:p._category_colors[code] for code in p._category_labels}
60
+ if self.gp:raise ValueError('categorical slice summary uses the heatmap colors; gp is for numeric summaries')
61
+ obj=StackedBarAnnotation(data,colors=colors,bar_width=self.bar_width,ylim=(0,1),**options)
62
+ else:
63
+ from .annotations_extra import DistributionBoxplotAnnotation
64
+ obj=DistributionBoxplotAnnotation(data,width_frac=self.box_width,show_outliers=self.outline,
65
+ ylim=self.ylim,gp=self.gp,box_color=self.box_color,**options)
66
+ obj._default_height_mm=self._default_height_mm
67
+ if hasattr(self,'_fixed_height_mm'):obj._fixed_height_mm=self._fixed_height_mm
68
+ for key in ('_show_annotation_name','_annotation_name_gp','_annotation_name_rot','_annotation_name_offset'):
69
+ if hasattr(self,key):setattr(obj,key,getattr(self,key))
70
+ return obj,len(data)
71
+
72
+ def axis_padding(self,p):
73
+ if not self.axis:return {}
74
+ obj,_=self._resolved(p)
75
+ return obj.axis_padding(p)
76
+
77
+ def draw(self,f,start_x,start_y,pixel_size,bounds,gap_pixels,direction,renderer):
78
+ obj,count=self._resolved(renderer)
79
+ span=sum((end-start)*pixel_size for start,end in bounds)+gap_total(gap_pixels,max(0,len(bounds)-1))
80
+ obj.draw(f,start_x,start_y,span/count,[(0,count)],0,direction,renderer)