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.
- tilesig/__init__.py +124 -0
- tilesig/_bundle_data.py +76 -0
- tilesig/_bundle_metadata.py +199 -0
- tilesig/_gpu_linkage_worker.py +147 -0
- tilesig/_version.py +2 -0
- tilesig/algorithm_adapters.py +130 -0
- tilesig/algorithm_binding.py +157 -0
- tilesig/algorithm_types.py +251 -0
- tilesig/algorithms.py +55 -0
- tilesig/annotation.py +1152 -0
- tilesig/annotation_layout.py +104 -0
- tilesig/annotation_names.py +174 -0
- tilesig/annotation_ops.py +199 -0
- tilesig/annotations_extra.py +1573 -0
- tilesig/api.py +861 -0
- tilesig/appearance.py +707 -0
- tilesig/axes.py +146 -0
- tilesig/barplot.py +337 -0
- tilesig/block_heatmap.py +158 -0
- tilesig/block_summary.py +231 -0
- tilesig/bundle_io.py +92 -0
- tilesig/cell_labels.py +68 -0
- tilesig/cell_mask.py +70 -0
- tilesig/clustering.py +39 -0
- tilesig/comparison.py +158 -0
- tilesig/compatibility.py +199 -0
- tilesig/compatibility_extra.py +111 -0
- tilesig/composition_controls.py +132 -0
- tilesig/composition_layout.py +121 -0
- tilesig/config.py +343 -0
- tilesig/decoration_context.py +53 -0
- tilesig/decoration_selection.py +56 -0
- tilesig/decorations.py +166 -0
- tilesig/dendrograms.py +299 -0
- tilesig/diagonal.py +213 -0
- tilesig/distribution_heatmaps.py +164 -0
- tilesig/dot_heatmap.py +274 -0
- tilesig/genomic.py +87 -0
- tilesig/gpu_bridge.py +214 -0
- tilesig/gpu_raster.py +128 -0
- tilesig/graphics.py +92 -0
- tilesig/grouped_textboxes.py +133 -0
- tilesig/h5ad.py +742 -0
- tilesig/h5ad_subset.py +245 -0
- tilesig/helpers.py +246 -0
- tilesig/interval_sets.py +120 -0
- tilesig/item_display_tree.py +81 -0
- tilesig/legend_ticks.py +60 -0
- tilesig/legends.py +607 -0
- tilesig/matplotlib_integration.py +50 -0
- tilesig/matrix_scaling.py +40 -0
- tilesig/matrix_source.py +180 -0
- tilesig/name_layout.py +93 -0
- tilesig/object_ops.py +505 -0
- tilesig/options.py +44 -0
- tilesig/ordering_policy.py +91 -0
- tilesig/palettes.py +101 -0
- tilesig/parent_dendrogram.py +199 -0
- tilesig/pdf_renderer.py +717 -0
- tilesig/png_renderer.py +559 -0
- tilesig/preparation_cache.py +94 -0
- tilesig/prepared.py +179 -0
- tilesig/r_cluster_controls.py +138 -0
- tilesig/r_layout_controls.py +92 -0
- tilesig/r_raster.py +235 -0
- tilesig/renderer.py +3611 -0
- tilesig/renderer_old.py +2060 -0
- tilesig/reproducibility.py +88 -0
- tilesig/sets.py +407 -0
- tilesig/signal_heatmap.py +453 -0
- tilesig/single_cell.py +251 -0
- tilesig/slice_drawing.py +100 -0
- tilesig/slice_geometry.py +48 -0
- tilesig/slice_summary.py +80 -0
- tilesig/source_render.py +252 -0
- tilesig/specialized.py +520 -0
- tilesig/specialized_support.py +172 -0
- tilesig/streaming_pdf.py +118 -0
- tilesig/streaming_svg.py +72 -0
- tilesig/style.py +148 -0
- tilesig/text_boxes.py +158 -0
- tilesig/text_layout.py +45 -0
- tilesig/text_styles.py +83 -0
- tilesig/titles.py +191 -0
- tilesig/tree_styles.py +45 -0
- tilesig/unicode_pdf.py +119 -0
- tilesig/upset_annotations.py +58 -0
- tilesig/vector_grid.py +13 -0
- tilesig/within_block_order.py +167 -0
- tilesig-0.1.0.dev0.dist-info/METADATA +107 -0
- tilesig-0.1.0.dev0.dist-info/RECORD +94 -0
- tilesig-0.1.0.dev0.dist-info/WHEEL +5 -0
- tilesig-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
- tilesig-0.1.0.dev0.dist-info/top_level.txt +1 -0
tilesig/__init__.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from .renderer import ClusterMapPlotter
|
|
2
|
+
from .annotation import SimpleAnnotation, ColorAnnotation, ExpressionAnnotation, BoxplotAnnotation
|
|
3
|
+
from .h5ad import H5Data, read_h5ad
|
|
4
|
+
from .config import HeatmapConfig
|
|
5
|
+
from .style import Appearance, ColorMapping, colorRamp2
|
|
6
|
+
from .palettes import heatmap_palettes
|
|
7
|
+
from .api import *
|
|
8
|
+
from .api import __all__ as _api_exports
|
|
9
|
+
from .annotations_extra import *
|
|
10
|
+
from .annotations_extra import __all__ as _annotation_exports
|
|
11
|
+
from .sets import *
|
|
12
|
+
from .sets import __all__ as _set_exports
|
|
13
|
+
from .helpers import *
|
|
14
|
+
from .helpers import __all__ as _helper_exports
|
|
15
|
+
from .specialized import *
|
|
16
|
+
from .specialized import __all__ as _specialized_exports
|
|
17
|
+
from .barplot import StackedBarAnnotation
|
|
18
|
+
from .options import ht_opt, ht_global_opt
|
|
19
|
+
from .decorations import *
|
|
20
|
+
from .decorations import __all__ as _decoration_exports
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
'ClusterMapPlotter',
|
|
24
|
+
'SimpleAnnotation', 'ColorAnnotation',
|
|
25
|
+
'ExpressionAnnotation',
|
|
26
|
+
'BoxplotAnnotation',
|
|
27
|
+
'HeatmapConfig',
|
|
28
|
+
'H5Data',
|
|
29
|
+
'read_h5ad',
|
|
30
|
+
'Appearance', 'ColorMapping', 'colorRamp2', 'heatmap_palettes',
|
|
31
|
+
'StackedBarAnnotation',
|
|
32
|
+
'ht_opt', 'ht_global_opt',
|
|
33
|
+
]
|
|
34
|
+
__all__ = list(dict.fromkeys(__all__ + _api_exports + _annotation_exports + _set_exports + _helper_exports + _specialized_exports + _decoration_exports))
|
|
35
|
+
|
|
36
|
+
from .axes import *
|
|
37
|
+
from .axes import __all__ as _axis_exports
|
|
38
|
+
__all__ = list(dict.fromkeys(__all__ + _axis_exports))
|
|
39
|
+
|
|
40
|
+
from .graphics import subset_gp
|
|
41
|
+
__all__.append("subset_gp")
|
|
42
|
+
|
|
43
|
+
from .text_layout import smartAlign2
|
|
44
|
+
__all__.append("smartAlign2")
|
|
45
|
+
|
|
46
|
+
from .text_boxes import *
|
|
47
|
+
from .text_boxes import __all__ as _text_exports
|
|
48
|
+
__all__=list(dict.fromkeys(__all__+_text_exports))
|
|
49
|
+
|
|
50
|
+
from .grouped_textboxes import GroupedTextboxAnnotation
|
|
51
|
+
__all__.append('GroupedTextboxAnnotation')
|
|
52
|
+
|
|
53
|
+
from .interval_sets import make_interval_comb_mat
|
|
54
|
+
__all__.append('make_interval_comb_mat')
|
|
55
|
+
|
|
56
|
+
from .upset_annotations import *
|
|
57
|
+
from .upset_annotations import __all__ as _upset_annotation_exports
|
|
58
|
+
__all__=list(dict.fromkeys(__all__+_upset_annotation_exports))
|
|
59
|
+
|
|
60
|
+
from .legends import *
|
|
61
|
+
from .legends import __all__ as _legend_exports
|
|
62
|
+
__all__=list(dict.fromkeys(__all__+_legend_exports))
|
|
63
|
+
|
|
64
|
+
from .annotation_ops import *
|
|
65
|
+
from .annotation_ops import __all__ as _annotation_op_exports
|
|
66
|
+
__all__=list(dict.fromkeys(__all__+_annotation_op_exports))
|
|
67
|
+
|
|
68
|
+
from .dendrograms import *
|
|
69
|
+
from .dendrograms import __all__ as _dendrogram_exports
|
|
70
|
+
__all__=list(dict.fromkeys(__all__+_dendrogram_exports))
|
|
71
|
+
|
|
72
|
+
from .object_ops import *
|
|
73
|
+
from .object_ops import __all__ as _object_op_exports
|
|
74
|
+
__all__=list(dict.fromkeys(__all__+_object_op_exports))
|
|
75
|
+
|
|
76
|
+
from .genomic import convert_intervals
|
|
77
|
+
__all__.append("convert_intervals")
|
|
78
|
+
|
|
79
|
+
from .matrix_source import MatrixSource, as_matrix_source
|
|
80
|
+
__all__ += ["MatrixSource", "as_matrix_source"]
|
|
81
|
+
|
|
82
|
+
from .source_render import SourceHeatmap
|
|
83
|
+
__all__.append("SourceHeatmap")
|
|
84
|
+
|
|
85
|
+
from .compatibility import pheatmap
|
|
86
|
+
__all__.append('pheatmap')
|
|
87
|
+
|
|
88
|
+
from .single_cell import GroupSummary, CellClusteringResult, aggregate_groups, cluster_cells
|
|
89
|
+
__all__ += ['GroupSummary', 'CellClusteringResult', 'aggregate_groups', 'cluster_cells']
|
|
90
|
+
|
|
91
|
+
from .dot_heatmap import DotHeatmap
|
|
92
|
+
__all__.append('DotHeatmap')
|
|
93
|
+
|
|
94
|
+
from ._version import __version__
|
|
95
|
+
__all__.append("__version__")
|
|
96
|
+
|
|
97
|
+
from .slice_drawing import HeatmapSliceContext
|
|
98
|
+
__all__.append('HeatmapSliceContext')
|
|
99
|
+
|
|
100
|
+
from .comparison import HeatmapComparison, compare_heatmap, compare_heatmap2, compare_pheatmap
|
|
101
|
+
# Dotted R spelling is available through getattr; Python code uses heatmap2.
|
|
102
|
+
globals()['compare_heatmap.2']=compare_heatmap2
|
|
103
|
+
__all__ += ['HeatmapComparison','compare_heatmap','compare_heatmap2','compare_pheatmap']
|
|
104
|
+
|
|
105
|
+
from .algorithm_types import AlgorithmInput, AlgorithmResult
|
|
106
|
+
from .algorithms import AlgorithmRegistry, run_algorithm
|
|
107
|
+
__all__ += ['AlgorithmInput', 'AlgorithmResult', 'AlgorithmRegistry', 'run_algorithm']
|
|
108
|
+
|
|
109
|
+
from .algorithm_binding import bind_algorithm, algorithm_result
|
|
110
|
+
__all__ += ['bind_algorithm', 'algorithm_result']
|
|
111
|
+
|
|
112
|
+
from .reproducibility import export_bundle, verify_bundle
|
|
113
|
+
__all__ += ['export_bundle', 'verify_bundle']
|
|
114
|
+
|
|
115
|
+
from .prepared import PreparedHeatmap, prepare_heatmap
|
|
116
|
+
from .preparation_cache import PreparationCache
|
|
117
|
+
__all__ += ['PreparedHeatmap', 'prepare_heatmap', 'PreparationCache']
|
|
118
|
+
|
|
119
|
+
from .signal_heatmap import SignalHeatmapData, prepare_signal_heatmap, SignalHeatmap
|
|
120
|
+
__all__ += ['SignalHeatmapData', 'prepare_signal_heatmap', 'SignalHeatmap']
|
|
121
|
+
|
|
122
|
+
from .block_summary import BlockSummary, prepare_block_summary
|
|
123
|
+
from .block_heatmap import block_heatmap
|
|
124
|
+
__all__ += ['BlockSummary', 'prepare_block_summary', 'block_heatmap']
|
tilesig/_bundle_data.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Explicit retained numeric state written to NPY in bounded Cartesian tiles."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from scipy import sparse
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class _DotChannel:
|
|
7
|
+
def __init__(self, plot, grid, dtype):
|
|
8
|
+
self.plot = plot
|
|
9
|
+
self.grid = grid
|
|
10
|
+
self.dtype = np.dtype(dtype)
|
|
11
|
+
self.shape = plot._matrix_sorted.shape
|
|
12
|
+
|
|
13
|
+
def __getitem__(self,key):
|
|
14
|
+
rr,cc=key
|
|
15
|
+
return self.grid.loc[self.plot.row_names[rr],self.plot.col_names[cc]].to_numpy(dtype=self.dtype)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def payloads(view,source):
|
|
19
|
+
values=[('retained_numeric',source._raw_numeric),('display_values',view._matrix_sorted)]
|
|
20
|
+
mask = getattr(view, '_cell_mask', None)
|
|
21
|
+
if mask is not None:
|
|
22
|
+
values.append(('cell_display_states', mask.displayed(view)))
|
|
23
|
+
if getattr(view,'_dot_heatmap',False):
|
|
24
|
+
values.append(('dot_sizes', _DotChannel(view, view.size_values, 'float64')))
|
|
25
|
+
if view._dot_category_ids is not None:
|
|
26
|
+
values.append(('dot_category_ids', _DotChannel(view, view._dot_category_ids, 'int32')))
|
|
27
|
+
return values
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def preflight_data(views,sources,max_bytes):
|
|
31
|
+
payload=0;count=0
|
|
32
|
+
for view,source in zip(views,sources):
|
|
33
|
+
for _,values in payloads(view,source):
|
|
34
|
+
dtype=np.dtype(values.dtype)
|
|
35
|
+
if dtype.kind not in 'biuf':raise ValueError('bundle data must be real numeric, never object/pickle arrays')
|
|
36
|
+
payload+=int(values.shape[0])*int(values.shape[1])*dtype.itemsize;count+=1
|
|
37
|
+
# Includes output, conservative copy/tile allowance and NPY headers.
|
|
38
|
+
required=2*payload+4096*count
|
|
39
|
+
if required>max_bytes:raise MemoryError(f'retained numeric estimate {required:,} exceeds max_data_bytes={max_bytes:,}')
|
|
40
|
+
return {'payload_bytes':payload,'estimated_workspace_bytes':required,'max_data_bytes':max_bytes}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def early_preflight(sources,max_bytes):
|
|
44
|
+
# Conservative unprepared shape bound, before source reads. Cleaning may
|
|
45
|
+
# later reduce it, so callers can prepare/subset first for a tighter bound.
|
|
46
|
+
required=0
|
|
47
|
+
for source in sources:
|
|
48
|
+
if hasattr(source,'_matrix_sorted') and source._matrix_sorted is not None:
|
|
49
|
+
required+=preflight_data([source],[source],max_bytes)['estimated_workspace_bytes']
|
|
50
|
+
continue
|
|
51
|
+
if not hasattr(source,'df'):continue
|
|
52
|
+
n,d=source.df.shape;dot=getattr(source,'_dot_heatmap',False)
|
|
53
|
+
required+=int(n)*int(d)*(32 if dot else 16)+(12288 if dot else 8192)
|
|
54
|
+
if dot and source._dot_category_ids is not None:
|
|
55
|
+
required += int(n) * int(d) * 8 + 4096
|
|
56
|
+
if getattr(source, '_cell_mask', None) is not None:
|
|
57
|
+
required += int(n) * int(d) * 2 + 4096
|
|
58
|
+
if required>max_bytes:raise MemoryError(f'unprepared numeric shape estimate {required:,} exceeds max_data_bytes={max_bytes:,}; subset or prepare first for a tighter bound')
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def write_data(directory,view,source,max_bytes):
|
|
62
|
+
data_dir=directory/'data';data_dir.mkdir()
|
|
63
|
+
for name,values in payloads(view,source):
|
|
64
|
+
cells=min(65536,max(1,max_bytes//64))
|
|
65
|
+
backing=getattr(values,'source',None)
|
|
66
|
+
if backing is not None:cells=min(cells,backing.max_block_cells)
|
|
67
|
+
nr,nc=values.shape;width=max(1,min(nc,cells,1024));height=max(1,min(nr,256,cells//width))
|
|
68
|
+
out=np.lib.format.open_memmap(data_dir/(name+'.npy'),mode='w+',dtype=values.dtype,shape=values.shape)
|
|
69
|
+
try:
|
|
70
|
+
for r in range(0,nr,height):
|
|
71
|
+
for c in range(0,nc,width):
|
|
72
|
+
block=values[r:min(nr,r+height),c:min(nc,c+width)]
|
|
73
|
+
if sparse.issparse(block):block=block.toarray()
|
|
74
|
+
out[r:r+block.shape[0],c:c+block.shape[1]]=block
|
|
75
|
+
out.flush()
|
|
76
|
+
finally:out._mmap.close()
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Passive reproduction metadata over existing prepared native plot state."""
|
|
2
|
+
from dataclasses import asdict, fields
|
|
3
|
+
from hashlib import sha256
|
|
4
|
+
from importlib import metadata
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import sys
|
|
9
|
+
import numpy as np
|
|
10
|
+
import pandas as pd
|
|
11
|
+
from scipy import sparse
|
|
12
|
+
from .config import HeatmapConfig
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Metadata:
|
|
16
|
+
def __init__(self): self.requirements=[]
|
|
17
|
+
|
|
18
|
+
def safe(self,value,path='metadata',depth=0):
|
|
19
|
+
if depth>20:
|
|
20
|
+
self.requirements.append(path+': nested runtime object required')
|
|
21
|
+
return {'portable':False,'type':'nested object'}
|
|
22
|
+
if value is None or isinstance(value,(str,bool,int)):return value
|
|
23
|
+
if isinstance(value,(float,np.floating)):
|
|
24
|
+
return float(value) if np.isfinite(value) else {'type':'nonfinite','value':str(value)}
|
|
25
|
+
if isinstance(value,np.integer):return int(value)
|
|
26
|
+
if isinstance(value,np.bool_):return bool(value)
|
|
27
|
+
if isinstance(value,Path):return str(value)
|
|
28
|
+
if isinstance(value,np.ndarray):
|
|
29
|
+
if value.size<=4096:return self.safe(value.tolist(),path,depth+1)
|
|
30
|
+
self.requirements.append(path+': large parameter array required')
|
|
31
|
+
return {'portable':False,'type':'ndarray','shape':list(value.shape),'dtype':str(value.dtype)}
|
|
32
|
+
if isinstance(value,pd.Series):
|
|
33
|
+
return {'type':'Series','index':self.safe(value.index.to_numpy(),path+'.index',depth+1),
|
|
34
|
+
'values':self.safe(value.to_numpy(),path+'.values',depth+1)}
|
|
35
|
+
if isinstance(value,pd.DataFrame):
|
|
36
|
+
self.requirements.append(path+': original table required')
|
|
37
|
+
return {'portable':False,'type':'DataFrame','shape':list(value.shape)}
|
|
38
|
+
if isinstance(value,dict):
|
|
39
|
+
if all(isinstance(k,str) for k in value):
|
|
40
|
+
return {k:self.safe(v,path+'.'+k,depth+1) for k,v in value.items()}
|
|
41
|
+
return {'type':'mapping','entries':[[self.safe(k,path,depth+1),self.safe(v,path,depth+1)] for k,v in value.items()]}
|
|
42
|
+
if isinstance(value,(tuple,list)):
|
|
43
|
+
return [self.safe(v,path+f'[{i}]',depth+1) for i,v in enumerate(value)]
|
|
44
|
+
from .style import ColorMapping
|
|
45
|
+
if isinstance(value,ColorMapping):
|
|
46
|
+
return {'type':'ColorMapping','breaks':self.safe(value.breaks,path,depth+1),
|
|
47
|
+
'colors_rgb_unit':self.safe(value.colors,path,depth+1),
|
|
48
|
+
'space':getattr(value,'space',None),'categorical':value.is_categorical,
|
|
49
|
+
'na_rgb':self.safe(value.na_color,path,depth+1)}
|
|
50
|
+
from functools import partial
|
|
51
|
+
if isinstance(value,partial):
|
|
52
|
+
return {'type':'partial','portable':False,'function':self.safe(value.func,path+'.function',depth+1),
|
|
53
|
+
'args':self.safe(value.args,path+'.args',depth+1),'keywords':self.safe(value.keywords,path+'.keywords',depth+1)}
|
|
54
|
+
self.requirements.append(path+': original runtime '+('callable' if callable(value) else 'object')+' required')
|
|
55
|
+
return {'portable':False,'type':type(value).__module__+'.'+type(value).__qualname__,
|
|
56
|
+
'module':getattr(value,'__module__',None),'qualified_name':getattr(value,'__qualname__',None)}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _axis(p,axis):
|
|
60
|
+
row=axis=='row'
|
|
61
|
+
ids=list(map(str,getattr(p,'_dendrogram_source_row_ids' if row else '_dendrogram_source_column_ids')))
|
|
62
|
+
displayed=list(map(str,p.row_names if row else p.col_names))
|
|
63
|
+
lossy=(p.row_compression if row else p.col_compression)!=1 or len(displayed)!=len(ids)
|
|
64
|
+
positions=None
|
|
65
|
+
if not lossy and len(set(ids))==len(ids) and set(displayed)==set(ids):
|
|
66
|
+
lookup={v:i for i,v in enumerate(ids)};positions=[lookup[v] for v in displayed]
|
|
67
|
+
labels=getattr(p,'_row_cluster_labels' if row else '_col_cluster_labels',None)
|
|
68
|
+
# Drawing labels can come from a composition reference. Preserve those
|
|
69
|
+
# separately from each component's scientific labels mapped by source ID.
|
|
70
|
+
original=getattr(p,'_row_labels_original' if row else '_col_labels_original_idx',None)
|
|
71
|
+
source_labels=None
|
|
72
|
+
if original is not None and len(original)==len(ids) and positions is not None:source_labels=np.asarray(original)[positions].tolist()
|
|
73
|
+
return {'source_ids':ids,'display_ids':displayed,'display_source_positions':positions,
|
|
74
|
+
'lossy':bool(lossy),'labels':None if labels is None else np.asarray(labels).tolist(),
|
|
75
|
+
'source_labels_in_display_order':source_labels,
|
|
76
|
+
'breaks':list(map(int,p.row_breaks if row else p.col_breaks))}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def collect_panel(p,source,meta,*,include_data):
|
|
80
|
+
from .algorithm_binding import algorithm_result
|
|
81
|
+
from .r_raster import resolved_reducer
|
|
82
|
+
raster_reducer = resolved_reducer(p)
|
|
83
|
+
runtime={'color_space':getattr(p,'_explicit_color_space',None),'post_fun':getattr(p,'_post_fun',None),'decorations':getattr(p,'_decorations',[]),
|
|
84
|
+
'r_controls':getattr(p,'_r_controls',{}),'raster_quality':getattr(p,'_r_raster_quality',1.),
|
|
85
|
+
'raster_reducer':raster_reducer}
|
|
86
|
+
config={'factory_defaults':asdict(HeatmapConfig()),
|
|
87
|
+
'config_object':None if p.cfg is None else asdict(p.cfg),
|
|
88
|
+
'requested_visual_options':p._visual_options,
|
|
89
|
+
'resolved':{f.name:getattr(p,f.name,p._visual_options.get(f.name,f.default)) for f in fields(HeatmapConfig)},
|
|
90
|
+
'runtime':runtime,'class':type(p).__module__+'.'+type(p).__qualname__,
|
|
91
|
+
'requested_font':p._requested_font_family,'resolved_font':p._appearance.font_family,
|
|
92
|
+
'geometry':getattr(p,'_last_layout',{})}
|
|
93
|
+
annotations=getattr(p,'all_annotations',[])
|
|
94
|
+
if annotations:meta.requirements.append('annotations: original annotation inputs/runtime objects required')
|
|
95
|
+
config['annotations']=[{'class':type(a).__module__+'.'+type(a).__qualname__,'side':a.side,'label':getattr(a,'label',None)} for a in annotations]
|
|
96
|
+
if getattr(p,'_specialized_kind',None):meta.requirements.append('specialized heatmap: original specialized inputs required')
|
|
97
|
+
order={axis:_axis(p,axis) for axis in ('row','col')}
|
|
98
|
+
palette={'lut_rgb':p._generate_lut().reshape(-1,3)[:,::-1].tolist(),
|
|
99
|
+
'vmin':p.vmin,'vmax':p.vmax,'limit':p._limit,
|
|
100
|
+
'display_range':[-p._limit,p._limit] if p.style=='legacy' and p.z_score else [p.vmin,p.vmax],
|
|
101
|
+
'index_rule':'0 missing; finite floor(clip((value-lo)/(hi-lo)*254+1,1,255)); hi=lo+1e-6 if hi<=lo',
|
|
102
|
+
'categorical_colors':getattr(p,'_category_colors',None),
|
|
103
|
+
'categorical_labels':getattr(p,'_category_labels',None),'requested':p.cmap}
|
|
104
|
+
mask = getattr(p, '_cell_mask', None)
|
|
105
|
+
if mask is not None:
|
|
106
|
+
missing, hidden = mask.colors(p)
|
|
107
|
+
palette['cell_display_states'] = {
|
|
108
|
+
'0': {'label': 'Observed'},
|
|
109
|
+
'1': {'label': mask.missing_label, 'color': missing},
|
|
110
|
+
}
|
|
111
|
+
if mask.only_missing:
|
|
112
|
+
meta.requirements.append('missing-value positions needed to rebuild the display')
|
|
113
|
+
else:
|
|
114
|
+
palette['cell_display_states']['2'] = {'label': 'Masked', 'color': hidden}
|
|
115
|
+
meta.requirements.append('cell mask: original mask and missing-value positions needed to rebuild the display')
|
|
116
|
+
if getattr(p,'_dot_heatmap',False):
|
|
117
|
+
palette['dot']={k:getattr(p,k) for k in ('size_max','dot_max_fraction','dot_max_size_mm','dot_edge_color','dot_edge_width','size_legend_title','show_size_legend')}
|
|
118
|
+
palette['dot']['size_rule']='circle area proportional to size/size_max; zero absent'
|
|
119
|
+
if p._dot_category_ids is not None:
|
|
120
|
+
palette['dot'].update(
|
|
121
|
+
size_rule='equal marker area across categories for equal sizes; zero or absent pair is blank',
|
|
122
|
+
marker_legend_title=p._dot_marker_legend_title,
|
|
123
|
+
category_labels=list(p._dot_category_labels),
|
|
124
|
+
category_marker_pch=list(p._dot_marker_codes),
|
|
125
|
+
missing_category_id=-1,
|
|
126
|
+
)
|
|
127
|
+
memory=getattr(p,'memory_report',{})
|
|
128
|
+
is_sparse=memory.get('use_sparse_statistics',sparse.issparse(p._raw_numeric))
|
|
129
|
+
transforms={'cleaning':'drop all-NaN rows/columns; fill remaining NaN with zero in native numeric preparation',
|
|
130
|
+
'filter':p.df_filter,'working_dtype':'float32','sparse_statistics':bool(is_sparse),
|
|
131
|
+
'z_score':{'enabled':bool(p.z_score),'ddof':0 if is_sparse else 1,
|
|
132
|
+
'sparse_variance_floor':1e-10 if is_sparse else None,
|
|
133
|
+
'zero_std_replaced_by':1,'nonfinite_normalized_values':'zero'},
|
|
134
|
+
'clip':{'percentile_parameter':p.z_clip_percentile,'resolved_vmin':p.vmin,'resolved_vmax':p.vmax,'symmetric_limit':p._limit},
|
|
135
|
+
'row_compression':p.row_compression,'col_compression':p.col_compression,
|
|
136
|
+
'compression_rule':'cv2.INTER_AREA or bounded source area integration',
|
|
137
|
+
'reverse_columns':p.reverse_columns,'symmetric':p.symmetric,
|
|
138
|
+
'r_controls':getattr(p,'_r_controls',{}),'raster_reducer':raster_reducer}
|
|
139
|
+
scale = getattr(p, 'scale', None)
|
|
140
|
+
if scale not in (None, 'none'):
|
|
141
|
+
transforms['cleaning'] = 'drop all-nonfinite axes; retained raw missing values use zero'
|
|
142
|
+
transforms['scale'] = {'mode': scale, 'sample_ddof': 1 if scale.endswith('zscore') else None,
|
|
143
|
+
'missing': 'omit for reductions; fill scaled missing cells with zero'}
|
|
144
|
+
transforms['clip']['percentile_parameter'] = None
|
|
145
|
+
transforms['clip']['scope'] = 'colour mapping only'
|
|
146
|
+
algorithms={}
|
|
147
|
+
for axis in ('row','col'):
|
|
148
|
+
try:r=algorithm_result(source,axis)
|
|
149
|
+
except ValueError as exc:
|
|
150
|
+
algorithms[axis]={'available':False,'reason':str(exc)};continue
|
|
151
|
+
algorithms[axis]={'available':True,'scope':'component algorithm before composition alignment',
|
|
152
|
+
'item_ids':r.item_ids,'ordered_ids':r.ordered_ids,'labels':None if r.labels is None else r.labels.to_list(),
|
|
153
|
+
'linkage':None if r.linkage is None else r.linkage.tolist(),'embedding':None if r.embedding is None else {'shape':list(r.embedding.shape),'included':False},
|
|
154
|
+
'method':r.method,'kind':r.kind,'random_state':r.random_state,'parameters':r.parameters,'report':r.report}
|
|
155
|
+
from .algorithm_types import AlgorithmResult
|
|
156
|
+
from .algorithm_adapters import native_cluster,graph_cluster,reduce_matrix
|
|
157
|
+
from functools import partial
|
|
158
|
+
for axis,binding in getattr(source,'_algorithm_bindings',{}).items():
|
|
159
|
+
if isinstance(binding,AlgorithmResult):
|
|
160
|
+
algorithms[axis]['binding']={'type':'external_result','representation_responsibility':'caller supplied'}
|
|
161
|
+
else:
|
|
162
|
+
name,parameters,registry=binding
|
|
163
|
+
runner,kinds,supports_sparse=registry._entries['clustering',name]
|
|
164
|
+
function=runner.func if isinstance(runner,partial) else runner
|
|
165
|
+
builtin=any(function is f for f in (native_cluster,graph_cluster,reduce_matrix))
|
|
166
|
+
algorithms[axis]['binding']={'type':'registered_runner','registered_name':name,
|
|
167
|
+
'input_parameters':parameters,'input_kinds':kinds,'supports_sparse':supports_sparse,
|
|
168
|
+
'runner':{'builtin':True,'qualified_name':function.__module__+'.'+function.__qualname__} if builtin else runner}
|
|
169
|
+
input_source=getattr(source,'_input_source',None)
|
|
170
|
+
source_info={'kind':getattr(input_source,'kind','in-memory native frame'),'matrix_payload_included':include_data,
|
|
171
|
+
'numeric_state':'retained cleaned pre-transform numeric state; not original external dataset',
|
|
172
|
+
'source_shape':list(p._raw_numeric.shape),'display_shape':list(p._matrix_sorted.shape),
|
|
173
|
+
'input_row_ids':list(map(str,source.df.index)),'input_column_ids':list(map(str,source.df.columns)),
|
|
174
|
+
'provenance':getattr(input_source,'provenance',None),
|
|
175
|
+
'matrix_content_hash':'not computed unless included NPY files are hashed',
|
|
176
|
+
'original_input_permutation':{'row':getattr(source,'_input_row_order',None),'col':getattr(source,'_input_col_order',None)}}
|
|
177
|
+
return {name:meta.safe(value,name) for name,value in [('config',config),('order',order),('palette',palette),('transforms',transforms),('algorithms',algorithms),('source',source_info)]}
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def versions():
|
|
181
|
+
names=('tilesig','numpy','pandas','scipy','scikit-learn','fastcluster','opencv-python','matplotlib','bottleneck','numexpr','Pillow','reportlab','resvg-py','anndata','umap-learn','networkx','igraph','leidenalg','cupy-cuda12x')
|
|
182
|
+
packages={}
|
|
183
|
+
for name in names:
|
|
184
|
+
try:packages[name]=metadata.version(name)
|
|
185
|
+
except metadata.PackageNotFoundError:packages[name]=None
|
|
186
|
+
return {'python':sys.version,'platform':{'system':platform.system(),'release':platform.release(),'machine':platform.machine()},
|
|
187
|
+
'packages':packages,'versions_scope':'selected installed distributions, not evidence of execution',
|
|
188
|
+
'module_sha256':{p.name:sha256(p.read_bytes()).hexdigest() for p in sorted(Path(__file__).parent.glob('*.py'))}}
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def rss():
|
|
192
|
+
try:
|
|
193
|
+
import resource
|
|
194
|
+
value=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
|
195
|
+
return int(value if sys.platform=='darwin' else value*1024)
|
|
196
|
+
except (ImportError,AttributeError):return None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def threads():return {k:os.environ.get(k) for k in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMEXPR_NUM_THREADS')}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""WSL-side worker: exact Ward/complete linkage with GPU pairwise distances.
|
|
2
|
+
|
|
3
|
+
Run inside WSL (RAPIDS env) by ``gpu_bridge.wsl_linkage``. The condensed
|
|
4
|
+
Euclidean distance matrix is computed on the GPU in row tiles (so peak VRAM
|
|
5
|
+
stays bounded), copied to host, and the hierarchical merge is done on the CPU
|
|
6
|
+
with ``fastcluster.linkage`` (exact, full dendrogram preserved).
|
|
7
|
+
|
|
8
|
+
Usage::
|
|
9
|
+
|
|
10
|
+
python _gpu_linkage_worker.py --in X.npy --out Z.npy --method ward
|
|
11
|
+
python _gpu_linkage_worker.py --in X.npy --out Z.npy --method ward --pca 50
|
|
12
|
+
"""
|
|
13
|
+
import argparse
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _condensed_euclidean_gpu(X, tile=4096):
|
|
19
|
+
"""Condensed Euclidean distance vector, computed on GPU in row tiles."""
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
n = X.shape[0]
|
|
23
|
+
out = np.empty(n * (n - 1) // 2, dtype=np.float64)
|
|
24
|
+
if n < 2:
|
|
25
|
+
return out
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
import cupy as cp
|
|
29
|
+
Xg = cp.asarray(X, dtype=cp.float32)
|
|
30
|
+
sq = cp.sum(Xg * Xg, axis=1)
|
|
31
|
+
start = 0
|
|
32
|
+
for i0 in range(0, n, tile):
|
|
33
|
+
i1 = min(i0 + tile, n)
|
|
34
|
+
G = Xg[i0:i1] @ Xg.T
|
|
35
|
+
D2 = sq[i0:i1, None] + sq[None, :] - 2.0 * G
|
|
36
|
+
cp.maximum(D2, 0.0, out=D2)
|
|
37
|
+
Db = cp.asnumpy(cp.sqrt(D2))
|
|
38
|
+
del G, D2
|
|
39
|
+
for r in range(i1 - i0):
|
|
40
|
+
i = i0 + r
|
|
41
|
+
cnt = n - i - 1
|
|
42
|
+
if cnt > 0:
|
|
43
|
+
out[start:start + cnt] = Db[r, i + 1:]
|
|
44
|
+
start += cnt
|
|
45
|
+
del Xg, sq
|
|
46
|
+
cp.get_default_memory_pool().free_all_blocks()
|
|
47
|
+
except Exception as e: # no GPU / cupy missing -> CPU fallback
|
|
48
|
+
print(f" [gpu-worker] cupy unavailable ({e}); using scipy pdist", file=sys.stderr)
|
|
49
|
+
from scipy.spatial.distance import pdist
|
|
50
|
+
out = pdist(X, metric='euclidean').astype(np.float64)
|
|
51
|
+
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def compute_linkage(X, method='ward', pca_n=0, tile=4096):
|
|
56
|
+
"""Return the full linkage matrix Z for ``X`` (exact, GPU distances)."""
|
|
57
|
+
import numpy as np
|
|
58
|
+
X = np.ascontiguousarray(X, dtype=np.float32)
|
|
59
|
+
|
|
60
|
+
if pca_n and pca_n > 0:
|
|
61
|
+
n_comp = min(pca_n, X.shape[0] - 1, X.shape[1] - 1)
|
|
62
|
+
if n_comp >= 2:
|
|
63
|
+
t0 = time.time()
|
|
64
|
+
try:
|
|
65
|
+
from cuml.decomposition import PCA
|
|
66
|
+
X = PCA(n_components=n_comp, output_type='numpy').fit_transform(X)
|
|
67
|
+
except Exception:
|
|
68
|
+
from sklearn.decomposition import PCA
|
|
69
|
+
X = PCA(n_components=n_comp).fit_transform(X)
|
|
70
|
+
print(f" [gpu-worker] PCA({n_comp}) {time.time() - t0:.2f}s", file=sys.stderr)
|
|
71
|
+
|
|
72
|
+
t0 = time.time()
|
|
73
|
+
D = _condensed_euclidean_gpu(X, tile=tile)
|
|
74
|
+
print(f" [gpu-worker] condensed distances n={X.shape[0]}: {time.time() - t0:.2f}s", file=sys.stderr)
|
|
75
|
+
|
|
76
|
+
t0 = time.time()
|
|
77
|
+
try:
|
|
78
|
+
import fastcluster
|
|
79
|
+
Z = fastcluster.linkage(D, method=method)
|
|
80
|
+
except ImportError:
|
|
81
|
+
from scipy.cluster.hierarchy import linkage
|
|
82
|
+
Z = linkage(D, method=method)
|
|
83
|
+
print(f" [gpu-worker] {method} linkage: {time.time() - t0:.2f}s", file=sys.stderr)
|
|
84
|
+
return np.asarray(Z, dtype=np.float64)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def serve():
|
|
88
|
+
"""Persistent mode: read ``in\\tout\\tmethod\\tpca\\ttile`` lines on stdin.
|
|
89
|
+
|
|
90
|
+
Keeps the (expensive) cupy/CUDA context alive between calls. Prints
|
|
91
|
+
``READY`` once, then ``OK`` / ``ERR ...`` per request.
|
|
92
|
+
"""
|
|
93
|
+
import numpy as np
|
|
94
|
+
|
|
95
|
+
# Preload cupy so the CUDA context is created once, before READY.
|
|
96
|
+
try:
|
|
97
|
+
import cupy as cp
|
|
98
|
+
probe = cp.zeros(1)
|
|
99
|
+
cp.cuda.Stream.null.synchronize()
|
|
100
|
+
del probe
|
|
101
|
+
except Exception as exc:
|
|
102
|
+
sys.stdout.write(f'ERR CUDA unavailable: {exc}\n')
|
|
103
|
+
sys.stdout.flush()
|
|
104
|
+
return
|
|
105
|
+
|
|
106
|
+
sys.stdout.write('READY\n')
|
|
107
|
+
sys.stdout.flush()
|
|
108
|
+
|
|
109
|
+
for line in sys.stdin:
|
|
110
|
+
line = line.strip()
|
|
111
|
+
if not line:
|
|
112
|
+
continue
|
|
113
|
+
if line == 'QUIT':
|
|
114
|
+
break
|
|
115
|
+
try:
|
|
116
|
+
inp, out, method, pca, tile = line.split('\t')
|
|
117
|
+
X = np.load(inp)
|
|
118
|
+
Z = compute_linkage(X, method=method, pca_n=int(pca), tile=int(tile))
|
|
119
|
+
np.save(out, Z)
|
|
120
|
+
sys.stdout.write('OK\n')
|
|
121
|
+
except Exception as e:
|
|
122
|
+
sys.stdout.write(f'ERR {e}\n')
|
|
123
|
+
sys.stdout.flush()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main():
|
|
127
|
+
ap = argparse.ArgumentParser()
|
|
128
|
+
ap.add_argument('--in', dest='inp')
|
|
129
|
+
ap.add_argument('--out', dest='out')
|
|
130
|
+
ap.add_argument('--method', default='ward')
|
|
131
|
+
ap.add_argument('--pca', type=int, default=0)
|
|
132
|
+
ap.add_argument('--tile', type=int, default=4096)
|
|
133
|
+
ap.add_argument('--serve', action='store_true')
|
|
134
|
+
args = ap.parse_args()
|
|
135
|
+
|
|
136
|
+
if args.serve:
|
|
137
|
+
serve()
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
import numpy as np
|
|
141
|
+
X = np.load(args.inp)
|
|
142
|
+
Z = compute_linkage(X, method=args.method, pca_n=args.pca, tile=args.tile)
|
|
143
|
+
np.save(args.out, Z)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
if __name__ == '__main__':
|
|
147
|
+
main()
|
tilesig/_version.py
ADDED