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,231 @@
1
+ """Fixed-grid statistics over bounded reads from an ordered numeric matrix."""
2
+
3
+ from dataclasses import dataclass
4
+ from numbers import Integral, Real
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from .matrix_source import MatrixSource, as_matrix_source
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class BlockSummary:
14
+ """Prepared block matrices with matching IDs and source coordinates.
15
+
16
+ Bounds are zero-based, half-open positions after applying any requested
17
+ axis orders. Mean and share are missing when a block has no finite entries.
18
+ Hits and share are available when a threshold was supplied to
19
+ prepare_block_summary.
20
+ """
21
+
22
+ means: pd.DataFrame
23
+ measured: pd.DataFrame
24
+ hits: pd.DataFrame | None
25
+ threshold: float | None
26
+ row_bounds: tuple[tuple[int, int], ...]
27
+ column_bounds: tuple[tuple[int, int], ...]
28
+ row_groups: pd.Series | None
29
+ column_groups: pd.Series | None
30
+
31
+ @property
32
+ def share(self):
33
+ """Fraction of measured entries strictly above the threshold, or None."""
34
+ if self.hits is None:
35
+ return None
36
+ return self.hits.div(self.measured.where(self.measured > 0))
37
+
38
+
39
+ def _positive_integer(value, option):
40
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value < 1:
41
+ raise ValueError(f"{option} must be a positive integer")
42
+ return int(value)
43
+
44
+
45
+ def _axis_permutation(order, axis, option):
46
+ if order is None:
47
+ return None
48
+ message = f"{option} must be a complete permutation of source positions or IDs"
49
+ try:
50
+ values = np.asarray(order, dtype=object)
51
+ except (TypeError, ValueError) as error:
52
+ raise ValueError(message) from error
53
+ if values.ndim != 1 or len(values) != len(axis):
54
+ raise ValueError(message)
55
+
56
+ if all(isinstance(value, Integral) and not isinstance(value, (bool, np.bool_))
57
+ for value in values):
58
+ if any(value < 0 or value >= len(axis) for value in values):
59
+ raise ValueError(message)
60
+ positions = values.astype(np.intp)
61
+ else:
62
+ positions = axis.get_indexer([str(value) for value in values])
63
+ if np.any(positions < 0) or len(np.unique(positions)) != len(axis):
64
+ raise ValueError(message)
65
+ return positions
66
+
67
+
68
+ def _group_runs(groups, axis, option, positions):
69
+ if groups is None:
70
+ return np.array([0, len(axis)]), None
71
+ if isinstance(groups, pd.Series):
72
+ groups = groups.copy()
73
+ groups.index = groups.index.map(str)
74
+ if not groups.index.is_unique or len(groups) != len(axis) or not axis.isin(groups.index).all():
75
+ raise ValueError(f"{option} IDs must match the source axis")
76
+ labels = groups.reindex(axis)
77
+ else:
78
+ labels = pd.Series(groups)
79
+ if len(labels) != len(axis):
80
+ raise ValueError(f"{option} must provide one label per source item")
81
+ if positions is not None:
82
+ labels = labels.iloc[positions]
83
+ if labels.isna().any():
84
+ raise ValueError(f"{option} labels must be nonmissing")
85
+
86
+ codes, unique = pd.factorize(labels)
87
+ names = np.asarray(unique.map(str))
88
+ if len(set(names)) != len(unique):
89
+ raise ValueError(f"{option} labels must be distinct after string conversion")
90
+ starts = np.r_[0, np.flatnonzero(codes[1:] != codes[:-1]) + 1]
91
+ runs = codes[starts]
92
+ if len(np.unique(runs)) != len(runs):
93
+ raise ValueError(f"{option} labels must form contiguous runs in the summary order")
94
+ return np.r_[starts, len(axis)], names[runs]
95
+
96
+
97
+ def _boundaries(run_edges, step):
98
+ starts = np.concatenate([np.arange(first, stop, step) for first, stop in
99
+ zip(run_edges[:-1], run_edges[1:])])
100
+ return np.r_[starts, run_edges[-1]]
101
+
102
+
103
+ def _tile_axis(boundaries, offset, size):
104
+ first = np.searchsorted(boundaries, offset, side="right") - 1
105
+ stop = np.searchsorted(boundaries, offset + size, side="left")
106
+ starts = boundaries[first:stop] - offset
107
+ starts[0] = 0
108
+ return slice(first, stop), starts
109
+
110
+
111
+ def _reduce_tile(values, rows, columns, dtype):
112
+ partial = np.add.reduceat(values, columns, axis=1, dtype=dtype)
113
+ return np.add.reduceat(partial, rows, axis=0, dtype=dtype)
114
+
115
+
116
+ def _statistics(source, row_edges, column_edges, threshold):
117
+ shape = (len(row_edges) - 1, len(column_edges) - 1)
118
+ sums = np.zeros(shape, dtype=np.float64)
119
+ measured = np.zeros(shape, dtype=np.int64)
120
+ hits = np.zeros(shape, dtype=np.int64) if threshold is not None else None
121
+ for r, c, values in source.blocks():
122
+ row_slice, rows = _tile_axis(row_edges, r, values.shape[0])
123
+ column_slice, columns = _tile_axis(column_edges, c, values.shape[1])
124
+ target = row_slice, column_slice
125
+
126
+ valid = np.isfinite(values)
127
+ if valid.all():
128
+ heights = np.diff(rows, append=values.shape[0])
129
+ widths = np.diff(columns, append=values.shape[1])
130
+ measured[target] += np.multiply.outer(heights, widths)
131
+ else:
132
+ measured[target] += _reduce_tile(valid, rows, columns, np.int64)
133
+ values = np.where(valid, values, 0.)
134
+
135
+ sums[target] += _reduce_tile(values, rows, columns, np.float64)
136
+ if hits is not None:
137
+ above = np.greater(values, np.float64(threshold))
138
+ above &= valid
139
+ hits[target] += _reduce_tile(above, rows, columns, np.int64)
140
+
141
+ with np.errstate(invalid="ignore"):
142
+ np.divide(sums, measured, out=sums, where=measured > 0)
143
+ sums[measured == 0] = np.nan
144
+ return sums, measured, hits
145
+
146
+
147
+ def _block_labels(edges, runs, names, index, option):
148
+ if names is None:
149
+ return None
150
+ indices = np.searchsorted(runs, edges[:-1], side="right") - 1
151
+ return pd.Series(names[indices], index=index, name=option)
152
+
153
+
154
+ def prepare_block_summary(matrix, *, block_shape, threshold=None, row_groups=None,
155
+ column_groups=None, max_blocks=1_000_000,
156
+ row_order=None, column_order=None):
157
+ """Reduce a numeric matrix to fixed contiguous blocks in the supplied order.
158
+
159
+ matrix: Numeric ndarray, DataFrame, scipy sparse matrix, or MatrixSource.
160
+ block_shape: Maximum numbers of source rows and columns per block.
161
+ threshold: Finite scalar for strict exceedance counts, or None for means.
162
+ row_groups: Optional contiguous group labels by position or Series by row ID.
163
+ column_groups: Optional contiguous group labels by position or Series by column ID.
164
+ max_blocks: Maximum number of output blocks, checked before source reads.
165
+ row_order: Complete permutation of zero-based row positions or source row IDs.
166
+ column_order: Complete permutation of zero-based column positions or source column IDs.
167
+
168
+ Omitted orders retain the source order for their respective axes. Use string
169
+ IDs for integer-valued axis labels. Positional group labels follow the axis
170
+ permutations and Series align by ID. Contiguous groups split bins at their
171
+ boundaries in the resulting order. Shorter trailing bins are retained.
172
+ Means and counts use finite entries, including sparse implicit zeros.
173
+ Source reads preserve float32 arrays or use float64 for other numeric inputs.
174
+ All sums accumulate in float64.
175
+ Reuse the returned BlockSummary to draw multiple views from one source pass.
176
+ """
177
+ try:
178
+ row_step, column_step = block_shape
179
+ except (TypeError, ValueError) as error:
180
+ raise ValueError("block_shape must contain two positive integers") from error
181
+ row_step = _positive_integer(row_step, "block_shape row size")
182
+ column_step = _positive_integer(column_step, "block_shape column size")
183
+ max_blocks = _positive_integer(max_blocks, "max_blocks")
184
+ if threshold is not None:
185
+ if isinstance(threshold, (bool, np.bool_)) or not isinstance(threshold, Real):
186
+ raise ValueError("threshold must be a finite real number or None")
187
+ try:
188
+ threshold = float(threshold)
189
+ except OverflowError as error:
190
+ raise ValueError("threshold must be representable as a finite float64 value") from error
191
+ if not np.isfinite(threshold):
192
+ raise ValueError("threshold must be a finite real number or None")
193
+ if isinstance(matrix, pd.DataFrame):
194
+ from pandas.api.types import is_complex_dtype, is_numeric_dtype
195
+ if any(not is_numeric_dtype(dtype) or is_complex_dtype(dtype) for dtype in matrix.dtypes):
196
+ raise ValueError("matrix must contain real numeric values")
197
+
198
+ if isinstance(matrix, MatrixSource):
199
+ source = matrix
200
+ else:
201
+ dtype = np.float32 if getattr(matrix, "dtype", None) == np.dtype("float32") else np.float64
202
+ source = as_matrix_source(matrix, dtype=dtype)
203
+ row_positions = _axis_permutation(row_order, source.index, "row_order")
204
+ column_positions = _axis_permutation(column_order, source.columns, "column_order")
205
+ if row_positions is not None or column_positions is not None:
206
+ source = source.subset(row_positions, column_positions)
207
+ row_runs, row_names = _group_runs(row_groups, source.index, "row_groups", row_positions)
208
+ column_runs, column_names = _group_runs(
209
+ column_groups, source.columns, "column_groups", column_positions,
210
+ )
211
+ n_rows = int(((np.diff(row_runs) - 1) // row_step + 1).sum())
212
+ n_columns = int(((np.diff(column_runs) - 1) // column_step + 1).sum())
213
+ if n_rows * n_columns > max_blocks:
214
+ raise MemoryError(f"block grid would exceed max_blocks={max_blocks:,}")
215
+
216
+ row_edges = _boundaries(row_runs, row_step)
217
+ column_edges = _boundaries(column_runs, column_step)
218
+ means, measured, hits = _statistics(source, row_edges, column_edges, threshold)
219
+ rows = pd.Index([f"R{i + 1}" for i in range(n_rows)])
220
+ columns = pd.Index([f"C{i + 1}" for i in range(n_columns)])
221
+
222
+ return BlockSummary(
223
+ means=pd.DataFrame(means, index=rows, columns=columns),
224
+ measured=pd.DataFrame(measured, index=rows, columns=columns),
225
+ hits=None if hits is None else pd.DataFrame(hits, index=rows, columns=columns),
226
+ threshold=threshold,
227
+ row_bounds=tuple(zip(row_edges[:-1].tolist(), row_edges[1:].tolist())),
228
+ column_bounds=tuple(zip(column_edges[:-1].tolist(), column_edges[1:].tolist())),
229
+ row_groups=_block_labels(row_edges, row_runs, row_names, rows, "row_groups"),
230
+ column_groups=_block_labels(column_edges, column_runs, column_names, columns, "column_groups"),
231
+ )
tilesig/bundle_io.py ADDED
@@ -0,0 +1,92 @@
1
+ """Bounded passive JSON/ZIP integrity and atomic publication helpers."""
2
+ import hashlib
3
+ import json
4
+ import math
5
+ import os
6
+ from pathlib import PurePosixPath, Path
7
+ import stat
8
+ import zipfile
9
+
10
+
11
+ def positive(value,name):
12
+ if isinstance(value,bool) or not isinstance(value,int) or value<1:raise ValueError(name+' must be a positive integer')
13
+ return value
14
+
15
+
16
+ def write_json(path,value,budget):
17
+ path.parent.mkdir(parents=True,exist_ok=True)
18
+ remaining=budget[0]
19
+ with path.open('wb') as out:
20
+ for part in json.JSONEncoder(ensure_ascii=False,allow_nan=False,indent=2).iterencode(value):
21
+ encoded=part.encode('utf-8');remaining-=len(encoded)
22
+ if remaining<0:raise MemoryError('metadata exceeds max_metadata_bytes')
23
+ out.write(encoded)
24
+ budget[0]=remaining
25
+
26
+
27
+ def digest(path):
28
+ result=hashlib.sha256()
29
+ with path.open('rb') as stream:
30
+ for block in iter(lambda:stream.read(1024**2),b''):result.update(block)
31
+ return result.hexdigest()
32
+
33
+
34
+ def publish(stage,destination,overwrite):
35
+ archive=stage/'bundle.zip'
36
+ members=sorted(p for p in stage.rglob('*') if p.is_file() and p!=archive)
37
+ with zipfile.ZipFile(archive,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=6) as z:
38
+ for p in members:z.write(p,p.relative_to(stage).as_posix())
39
+ if overwrite:os.replace(archive,destination)
40
+ else:os.link(archive,destination) # atomic no-clobber, sibling filesystem
41
+
42
+
43
+ def verify_bundle(path,*,max_bytes=1024**3,max_members=10000):
44
+ """Validate inventory and streamed SHA256 without extraction or code loading."""
45
+ positive(max_bytes,'max_bytes');positive(max_members,'max_members')
46
+ def invalid_constant(value):raise ValueError('nonfinite JSON constant '+value)
47
+ def finite_float(value):
48
+ result=float(value)
49
+ if not math.isfinite(result):raise ValueError('nonfinite JSON number '+value)
50
+ return result
51
+ def unique_keys(pairs):
52
+ result={}
53
+ for key,value in pairs:
54
+ if key in result:raise ValueError('duplicate JSON key '+key)
55
+ result[key]=value
56
+ return result
57
+ with zipfile.ZipFile(path) as z:
58
+ infos=z.infolist();names=[i.filename for i in infos]
59
+ if len(infos)>max_members:raise MemoryError('bundle exceeds max_members')
60
+ if sum(i.file_size for i in infos)>max_bytes:raise MemoryError('bundle exceeds max_bytes')
61
+ if len(set(names))!=len(names):raise ValueError('duplicate archive member')
62
+ for info in infos:
63
+ name=info.filename;parts=PurePosixPath(name).parts
64
+ if not name or '\\' in name or ':' in name or name.startswith('/') or any(p in ('..','.','') for p in name.split('/')) or info.is_dir() or stat.S_ISLNK(info.external_attr>>16):
65
+ raise ValueError('unsafe archive member '+name)
66
+ if 'manifest.json' not in names:raise ValueError('missing manifest.json')
67
+ manifest=json.loads(z.read('manifest.json'),parse_constant=invalid_constant,parse_float=finite_float,object_pairs_hook=unique_keys)
68
+ if not isinstance(manifest,dict) or type(manifest.get('schema_version')) is not int or manifest.get('schema_version')!=1:raise ValueError('unsupported bundle schema_version')
69
+ inventory=manifest.get('files')
70
+ if not isinstance(inventory,dict) or set(inventory)!=set(names)-{'manifest.json'}:raise ValueError('manifest inventory differs from archive')
71
+ required={'README.md','versions.json','resources.json'}
72
+ panels=manifest.get('panels');reproduction=manifest.get('reproduction')
73
+ if type(manifest.get('data_included')) is not bool or not isinstance(panels,list) or not panels or not isinstance(reproduction,dict) or reproduction.get('automatic_reconstruction') is not False or not isinstance(reproduction.get('requirements'),list):
74
+ raise ValueError('invalid required bundle schema fields')
75
+ if not any('images/heatmap.'+f in names for f in ('png','pdf','svg')):raise ValueError('bundle requires native image artifacts')
76
+ for i,panel in enumerate(panels):
77
+ prefix=f'panels/{i:04d}'
78
+ if not isinstance(panel,dict) or type(panel.get('index')) is not int or panel['index']!=i or panel.get('path')!=prefix:
79
+ raise ValueError('invalid panel schema')
80
+ required.update(prefix+'/'+f+'.json' for f in ('config','order','palette','transforms','source','algorithms'))
81
+ if manifest['data_included']:required.update(prefix+'/data/'+f+'.npy' for f in ('retained_numeric','display_values'))
82
+ if not required.issubset(inventory):raise ValueError('missing required bundle members')
83
+ for info in infos:
84
+ if info.filename=='manifest.json':continue
85
+ entry=inventory[info.filename]
86
+ if not isinstance(entry,dict) or entry.get('bytes')!=info.file_size:raise ValueError('member size mismatch '+info.filename)
87
+ h=hashlib.sha256()
88
+ with z.open(info) as stream:
89
+ for block in iter(lambda:stream.read(1024**2),b''):h.update(block)
90
+ if h.hexdigest()!=entry.get('sha256'):raise ValueError('member checksum mismatch '+info.filename)
91
+ manifest['integrity_verified']=True
92
+ return manifest
tilesig/cell_labels.py ADDED
@@ -0,0 +1,68 @@
1
+ """Bounded, identity-aware cell labels on the existing native layer protocol."""
2
+ from numbers import Real
3
+
4
+ import numpy as np
5
+ from .slice_geometry import slice_gaps
6
+ import pandas as pd
7
+ from matplotlib.colors import to_hex
8
+
9
+
10
+ class CellLabels:
11
+ def __init__(self,frame,labels,number_format='%.2f',color='#555555',fontsize=8,previous=None,maximum=10000,*,format_custom=False):
12
+ if not isinstance(maximum,(int,np.integer)) or maximum<1:raise ValueError('maximum number-label budget must be positive')
13
+ if frame.size>maximum:raise ValueError('cell label budget exceeded; increase max_number_labels explicitly')
14
+ if not np.isscalar(fontsize) or not np.isfinite(fontsize) or fontsize<=0:raise ValueError('number fontsize must be positive finite points')
15
+ if not isinstance(number_format,str):raise TypeError('number_format must be a percent-format string')
16
+ try:number_format%1.25
17
+ except (ValueError,TypeError) as e:raise ValueError('invalid number_format') from e
18
+ self.data=None
19
+ if labels is not True:
20
+ parameter = 'cell_labels' if format_custom else 'display_numbers'
21
+ if isinstance(labels,pd.DataFrame):
22
+ data=labels.copy();data.index=data.index.map(str);data.columns=data.columns.map(str)
23
+ rows=frame.index.map(str);cols=frame.columns.map(str)
24
+ if not data.index.is_unique or not data.columns.is_unique or set(data.index)!=set(rows) or set(data.columns)!=set(cols):raise ValueError(f'{parameter} matrix IDs/shape must match input')
25
+ data=data.reindex(index=rows,columns=cols)
26
+ else:
27
+ array=np.asarray(labels,dtype=object)
28
+ if array.shape!=frame.shape:raise ValueError(f'{parameter} matrix shape must match input')
29
+ data=pd.DataFrame(array,index=frame.index.map(str),columns=frame.columns.map(str))
30
+ self.data=data
31
+ self.number_format=number_format;self.color=to_hex(color);self.fontsize=float(fontsize)
32
+ self.format_custom = format_custom
33
+ if previous is not None and not callable(previous):raise TypeError('layer_fun must be callable')
34
+ self.previous=previous;self.maximum=int(maximum)
35
+
36
+ def __call__(self,jj,ii,sink,layout):
37
+ from .appearance import _text,_coord
38
+ p=sink.plotter
39
+ if len(ii)>self.maximum:raise ValueError('cell label budget exceeded')
40
+ if self.previous is not None:self.previous(jj,ii,sink,layout)
41
+ if self.data is not None:
42
+ if set(map(str,p.row_names))-set(self.data.index) or set(map(str,p.col_names))-set(self.data.columns):raise ValueError('cell-label IDs do not match current heatmap')
43
+ for j,i in zip(jj,ii):
44
+ if self.data is None:
45
+ value=p._matrix_sorted[i,j];text=self.number_format%value if np.isfinite(value) else 'NA'
46
+ else:
47
+ value = self.data.at[str(p.row_names[i]), str(p.col_names[j])]
48
+ if self.format_custom:
49
+ if not pd.api.types.is_scalar(value):
50
+ raise TypeError('cell_labels entries must be scalar values or text')
51
+ if pd.isna(value):
52
+ continue
53
+ if isinstance(value, Real) and not isinstance(value, (bool, np.bool_)):
54
+ if not np.isfinite(value):
55
+ continue
56
+ text = self.number_format % value
57
+ else:
58
+ text = str(value)
59
+ else:
60
+ text = str(value)
61
+ x=layout['heatmap_x']+_coord(j,layout['cell_w'],p.col_breaks,slice_gaps(p,'column'))+layout['cell_w']/2
62
+ y=layout['heatmap_y']+_coord(i,layout['cell_h'],p.row_breaks,slice_gaps(p,'row'))+layout['cell_h']/2
63
+ _text(sink,x,y,text,p._appearance.pt(self.fontsize),'middle',color=self.color)
64
+
65
+ def transform(self,p,row_map=None,column_map=None,subset=False):
66
+ if self.data is None:return
67
+ if subset:self.data=self.data.reindex(index=p.df.index.map(str),columns=p.df.columns.map(str)).copy()
68
+ else:self.data=self.data.rename(index=row_map or {},columns=column_map or {})
tilesig/cell_mask.py ADDED
@@ -0,0 +1,70 @@
1
+ """Cell display states kept separate from the prepared numeric matrix."""
2
+ from dataclasses import dataclass, replace
3
+
4
+ import numpy as np
5
+ import pandas as pd
6
+ from matplotlib.colors import to_hex
7
+
8
+ from .gpu_raster import OrderedMatrix
9
+
10
+
11
+ # Stored states are 0 for observed, 1 for missing, and 2 for masked.
12
+ MASKED = 2
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class CellMask:
17
+ states: pd.DataFrame
18
+ masked_color: str
19
+ only_missing: bool = False
20
+ missing_label: str = 'Missing'
21
+
22
+ @classmethod
23
+ def from_input(cls, frame, mask, mask_col):
24
+ rows, columns = frame.index.map(str), frame.columns.map(str)
25
+ if isinstance(mask, pd.DataFrame):
26
+ if not all(pd.api.types.is_bool_dtype(dtype) for dtype in mask.dtypes):
27
+ raise TypeError('mask must contain boolean values')
28
+ labels = mask.index.map(str), mask.columns.map(str)
29
+ if any(not axis.is_unique or set(axis) != set(ids)
30
+ for axis, ids in zip(labels, (rows, columns))):
31
+ raise ValueError('mask row and column identifiers must match the input matrix')
32
+ labelled = mask.set_axis(labels[0], axis=0).set_axis(labels[1], axis=1)
33
+ labelled = labelled.reindex(index=rows, columns=columns)
34
+ if labelled.isna().to_numpy().any():
35
+ raise ValueError('mask must contain nonmissing boolean values')
36
+ mask = labelled.to_numpy(dtype=bool)
37
+ else:
38
+ mask = np.asarray(mask)
39
+ if mask.shape != frame.shape:
40
+ raise ValueError('mask shape must match the input matrix')
41
+ if mask.dtype.kind != 'b':
42
+ raise TypeError('mask must contain boolean values')
43
+
44
+ states = frame.isna().to_numpy().astype(np.uint8)
45
+ states[mask] = MASKED
46
+ return cls(pd.DataFrame(states, index=rows, columns=columns), to_hex(mask_col))
47
+
48
+ @classmethod
49
+ def from_missing(cls, missing, *, label='No finite values'):
50
+ states = missing.astype(np.uint8)
51
+ states.index = states.index.map(str)
52
+ states.columns = states.columns.map(str)
53
+ return cls(states, '#F3D8A1', only_missing=True, missing_label=label)
54
+
55
+ def displayed(self, plot):
56
+ """Return a bounded-indexing view in the current physical cell order."""
57
+ rows = self.states.index.get_indexer(plot.row_names)
58
+ columns = self.states.columns.get_indexer(plot.col_names)
59
+ if (rows < 0).any() or (columns < 0).any():
60
+ raise ValueError('mask identifiers must match the displayed matrix')
61
+ return OrderedMatrix(self.states.to_numpy(copy=False), rows, columns)
62
+
63
+ def colors(self, plot):
64
+ return to_hex(plot._visual_options.get('na_col', '#BEBEBE')), self.masked_color
65
+
66
+ def subset(self, rows, columns):
67
+ return replace(self, states=self.states.loc[rows.map(str), columns.map(str)].copy())
68
+
69
+ def rename(self, row_map, column_map):
70
+ return replace(self, states=self.states.rename(index=row_map, columns=column_map))
tilesig/clustering.py ADDED
@@ -0,0 +1,39 @@
1
+ """Explicit alternative distances and precomputed hierarchical trees."""
2
+ import inspect
3
+ import numpy as np
4
+ from scipy.cluster.hierarchy import linkage,is_valid_linkage
5
+ from scipy.spatial.distance import pdist,squareform
6
+ from scipy.stats import rankdata,kendalltau
7
+
8
+
9
+ def explicit_linkage(data,method='complete',metric='euclidean',supplied=None,max_bytes=1_073_741_824):
10
+ if supplied is None and max_bytes is not None:
11
+ if not np.isfinite(max_bytes) or max_bytes<=0:raise ValueError('max_clustering_bytes must be positive or None')
12
+ n=len(data) if not hasattr(data,'shape') else data.shape[0]
13
+ # Condensed float64 distances plus conservative linkage/copy workspace.
14
+ required=3*8*n*(n-1)//2
15
+ if required>max_bytes:
16
+ raise ValueError(f'pairwise distance workspace estimate {required:,} bytes exceeds budget {max_bytes:,}; use automatic/PCA/KMeans clustering, a supplied tree, or raise max_clustering_bytes')
17
+ data=data.toarray() if hasattr(data,'toarray') else np.asarray(data)
18
+ if supplied is not None:
19
+ z=np.asarray(supplied(data) if callable(supplied) else supplied,dtype=float)
20
+ else:
21
+ if method not in ('ward','complete','average','single','weighted','centroid','median'):
22
+ raise ValueError('explicit distances require a hierarchical linkage method')
23
+ if method in ('ward','centroid','median') and metric!='euclidean':
24
+ raise ValueError(f'{method} requires euclidean distances')
25
+ if callable(metric):
26
+ try:nargs=len(inspect.signature(metric).parameters)
27
+ except (TypeError,ValueError):nargs=2
28
+ distance=np.asarray(metric(data),dtype=float) if nargs==1 else pdist(data,metric=metric)
29
+ if distance.ndim==2:distance=squareform(distance,checks=True)
30
+ else:
31
+ aliases={'manhattan':'cityblock','maximum':'chebyshev','binary':'jaccard','pearson':'correlation'}
32
+ if metric=='spearman':distance=pdist(rankdata(data,axis=1),metric='correlation')
33
+ elif metric=='kendall':distance=pdist(data,metric=lambda x,y:1-kendalltau(x,y).statistic)
34
+ else:distance=pdist(data,metric=aliases.get(metric,metric))
35
+ if not np.isfinite(distance).all() or np.any(distance<0):raise ValueError('distances must be finite and nonnegative; constant correlation profiles need a custom distance rule')
36
+ z=linkage(distance,method=method)
37
+ if z.shape!=(len(data)-1,4) or not np.isfinite(z).all():raise ValueError('precomputed linkage shape must match the clustered axis')
38
+ is_valid_linkage(z,throw=True)
39
+ return z
tilesig/comparison.py ADDED
@@ -0,0 +1,158 @@
1
+ """Native diagnostic panels against independent raster reference captures.
2
+
3
+ These utilities never start R or replace the heatmap engine. Capture a reference
4
+ in the original system separately; supply its image and (optionally) displayed
5
+ IDs/values. A diagnostic with only an image makes no numerical parity claim.
6
+ """
7
+ import json
8
+ from pathlib import Path
9
+ from xml.sax.saxutils import escape
10
+ import cv2
11
+ import numpy as np
12
+ from .api import Heatmap, _save_ops, _ops_svg, _vector_file_writer
13
+ from .compatibility import pheatmap
14
+
15
+
16
+ class HeatmapComparison:
17
+ """Independent reference + native plot, with inspectable comparison results.
18
+
19
+ ``reference_data`` keys: source (provenance string), rows, columns and values
20
+ in the reference's *display order*. ID comparison is exact; values compare
21
+ positionally with rtol/atol. Missing evidence is None, never inferred True.
22
+ Both panels retain their own size; no resampling/image error threshold is
23
+ used to declare equivalence. PNG/SVG/PDF use the existing native sinks.
24
+ """
25
+ def __init__(self,heatmap,reference,*,kind,reference_data=None,rtol=1e-5,atol=1e-7):
26
+ if reference is None:raise ValueError('reference image is required; capture it independently in the original system')
27
+ path=Path(reference)
28
+ try:self._reference_bytes=path.read_bytes()
29
+ except OSError as exc:raise ValueError(f'cannot decode reference image: {path}') from exc
30
+ self._reference=cv2.imdecode(np.frombuffer(self._reference_bytes,np.uint8),cv2.IMREAD_COLOR)
31
+ if self._reference is None:raise ValueError(f'cannot decode reference image: {path}')
32
+ # Normalize an independently decoded image to PNG for SVG/PDF embedding.
33
+ ok,encoded=cv2.imencode('.png',self._reference)
34
+ if not ok:raise ValueError('cannot encode reference image')
35
+ self._reference_bytes=encoded.tobytes()
36
+ if not np.isfinite([rtol,atol]).all() or min(rtol,atol)<0:raise ValueError('rtol/atol must be finite nonnegative')
37
+ self.heatmap=heatmap;self.kind=kind
38
+ heatmap._compute_clustering()
39
+ reference_data=dict(reference_data or {})
40
+ unknown=set(reference_data)-{'source','rows','columns','values'}
41
+ if unknown:raise ValueError('unknown reference metadata: '+', '.join(sorted(unknown)))
42
+ rows=list(map(str,heatmap.row_names));columns=list(map(str,heatmap.col_names))
43
+ actual=np.asarray(heatmap._matrix_sorted)
44
+ report={'kind':kind,'reference_path':str(path),'reference_source':str(reference_data.get('source','user-supplied image; provenance not verified')),
45
+ 'reference_image_shape':list(self._reference.shape[:2]),'native_rows':rows,'native_columns':columns,
46
+ 'native_shape':list(actual.shape),'rows_equal':None,'columns_equal':None,'values_equal':None,
47
+ 'max_value_abs_error':None,'rtol':float(rtol),'atol':float(atol),'full_R_parity':False,
48
+ 'note':'Independent image comparison; supplied provenance is not authenticated. No pixel-perfect or full R semantics claim.'}
49
+ for key,native in [('rows',rows),('columns',columns)]:
50
+ if key in reference_data:report[key+'_equal']=list(map(str,reference_data[key]))==native
51
+ if 'values' in reference_data:
52
+ expected=np.asarray(reference_data['values'],dtype=float)
53
+ report['values_equal']=bool(expected.shape==actual.shape and np.allclose(expected,actual,rtol=rtol,atol=atol,equal_nan=True))
54
+ if expected.shape==actual.shape:
55
+ finite=np.isfinite(actual)&np.isfinite(expected)
56
+ report['max_value_abs_error']=float(np.max(np.abs(actual[finite]-expected[finite]))) if finite.any() else None
57
+ self.report=report
58
+
59
+ def _scene(self,*,writer=None):
60
+ from .appearance import compute_layout,draw_body
61
+ from .pdf_renderer import PdfSink
62
+ if self.heatmap.style!='complexheatmap':raise ValueError('comparison panels require the native complexheatmap style')
63
+ layout=compute_layout(self.heatmap)
64
+ if layout is None:raise ValueError('comparison needs nonempty native input')
65
+ h,w=self._reference.shape[:2];gap=20;header=32
66
+ width=int(np.ceil(w+gap+layout['full_w']));height=int(np.ceil(header+max(h,layout['full_h'])))
67
+ if width*height>self.heatmap.max_canvas_pixels or max(width,height)>self.heatmap.max_canvas_dimension:raise ValueError('comparison canvas exceeds pixel budget; reduce reference size or heatmap DPI')
68
+ def draw_scene(sink):
69
+ sink.write(f'<rect x="0" y="0" width="{width}" height="{height}" fill="white"/>')
70
+ sink.write('<text x="4" y="22" font-size="16">Independent reference</text>')
71
+ sink.write(f'<text x="{w+gap+4}" y="22" font-size="16">Native {escape(self.kind)}</text>')
72
+ sink.write_image(0,header,w,h,self._reference_bytes)
73
+ sink.write(f'<g transform="translate({w+gap},{header})">')
74
+ draw_body(self.heatmap,sink,layout)
75
+ sink.write('</g>')
76
+
77
+ sink=PdfSink()
78
+ if writer is None:
79
+ draw_scene(sink)
80
+ else:
81
+ p=self.heatmap
82
+ writer(width,height,p.dpi,p._appearance.font_family,draw_scene)
83
+ return sink,width,height
84
+
85
+ def save(self,path,fmt=None):
86
+ """Export the labeled side-by-side panel through native PNG/SVG/PDF sinks."""
87
+ p=self.heatmap
88
+ fmt=(fmt or Path(path).suffix.lstrip('.') or 'svg').lower()
89
+ if fmt in ('pdf','svg') and (p.rasterized is False or getattr(p,'_dot_heatmap',False)):
90
+ self._scene(writer=_vector_file_writer(fmt,path))
91
+ return
92
+ sink,w,h=self._scene()
93
+ _save_ops(sink,w,h,p.dpi,p._appearance.font_family,path,fmt)
94
+
95
+ def save_report(self,path):
96
+ """Save numerical/order comparisons separately from the visual panel."""
97
+ path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
98
+ path.write_text(json.dumps(self.report,ensure_ascii=False,indent=2,allow_nan=False)+'\n',encoding='utf-8')
99
+
100
+ def _repr_svg_(self):
101
+ sink,w,h=self._scene();p=self.heatmap
102
+ return _ops_svg(sink,w,h,p.dpi,p._appearance.font_family)
103
+
104
+
105
+ def _legacy_heatmap(matrix,kwargs):
106
+ """Map common stats/gplots controls; all other options are native Heatmap controls."""
107
+ kwargs=dict(kwargs)
108
+ scale=kwargs.pop('scale',None)
109
+ # The explicit scale contract is shared with the native pheatmap wrapper.
110
+ if scale not in (None,'none','row','column'):raise ValueError('scale must be none, row or column')
111
+ aliases={'Rowv':'cluster_rows','Colv':'cluster_cols','labRow':'labels_row','labCol':'labels_col',
112
+ 'col':'color','main':'main'}
113
+ translated={}
114
+ for old,new in aliases.items():
115
+ if old in kwargs:
116
+ if new in kwargs and old!=new:raise TypeError(f'{old} and {new} both supplied')
117
+ translated[new]=kwargs.pop(old)
118
+ for old,new in [('cexRow','fontsize_row'),('cexCol','fontsize_col')]:
119
+ if old in kwargs:translated[new]=12*float(kwargs.pop(old))
120
+ return pheatmap(matrix,scale=scale,**translated,**kwargs)
121
+
122
+
123
+ def compare_heatmap(matrix,*,reference=None,reference_data=None,output_path=None,rtol=1e-5,atol=1e-7,**kwargs):
124
+ """Compare a native stats-style translation to an independent reference image.
125
+
126
+ Common explicit Rowv/Colv, scale, col, labRow/labCol, cexRow/cexCol, main
127
+ controls are translated. Remaining kwargs are validated native Heatmap
128
+ options. R closures/expressions/device settings are not interpreted.
129
+ """
130
+ if reference is None:raise ValueError('reference image is required')
131
+ result=HeatmapComparison(_legacy_heatmap(matrix,kwargs),reference,kind='heatmap',reference_data=reference_data,rtol=rtol,atol=atol)
132
+ if output_path is not None:result.save(output_path)
133
+ return result
134
+
135
+
136
+ def compare_heatmap2(matrix,*,reference=None,reference_data=None,output_path=None,rtol=1e-5,atol=1e-7,**kwargs):
137
+ """gplots-style comparison; same explicit common controls as compare_heatmap.
138
+
139
+ R trace/density/add.expr/layout/device semantics are outside this Python
140
+ diagnostic. Supply an original heatmap.2 image; the native side keeps the
141
+ project's own renderer and numerical defaults. Explicitly select scale and
142
+ clustering when comparing to a system with different defaults.
143
+ """
144
+ if reference is None:raise ValueError('reference image is required')
145
+ result=HeatmapComparison(_legacy_heatmap(matrix,kwargs),reference,kind='heatmap.2',reference_data=reference_data,rtol=rtol,atol=atol)
146
+ if output_path is not None:result.save(output_path)
147
+ return result
148
+
149
+
150
+ def compare_pheatmap(matrix,*,reference=None,reference_data=None,output_path=None,rtol=1e-5,atol=1e-7,**kwargs):
151
+ """Compare the real native pheatmap wrapper to an independent raster capture."""
152
+ if reference is None:raise ValueError('reference image is required')
153
+ result=HeatmapComparison(pheatmap(matrix,**kwargs),reference,kind='pheatmap',reference_data=reference_data,rtol=rtol,atol=atol)
154
+ if output_path is not None:result.save(output_path)
155
+ return result
156
+
157
+
158
+ __all__=['HeatmapComparison','compare_heatmap','compare_heatmap2','compare_pheatmap']