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/axes.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Portable annotation axes, in the same coordinate system as the fast renderer."""
|
|
2
|
+
from copy import deepcopy
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from xml.sax.saxutils import escape, quoteattr
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from matplotlib.colors import to_hex
|
|
9
|
+
|
|
10
|
+
from .style import Appearance, text_width
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def default_axis_param(which='column'):
|
|
14
|
+
if which not in ('column','row'):raise ValueError('which must be column or row')
|
|
15
|
+
return dict(at=None,labels=None,labels_rot=0,
|
|
16
|
+
gp={'fontsize':8},side='left' if which=='column' else 'top',
|
|
17
|
+
facing='outside',direction='normal')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def axis_parameters(params=None,which='column'):
|
|
21
|
+
result=default_axis_param(which)
|
|
22
|
+
params=deepcopy(params or {})
|
|
23
|
+
unknown=set(params)-set(result)
|
|
24
|
+
if unknown:raise TypeError('unknown axis parameters: '+', '.join(sorted(unknown)))
|
|
25
|
+
result.update(params)
|
|
26
|
+
allowed=('top','bottom') if which=='row' else ('left','right')
|
|
27
|
+
if result['side'] not in allowed:raise ValueError(f"axis side for {which} annotations must be one of {allowed}")
|
|
28
|
+
# Validate even before the actual data scale is available.
|
|
29
|
+
AnnotationAxis(scale=(0,1),**result)
|
|
30
|
+
return result
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AnnotationAxis:
|
|
34
|
+
"""Numeric ticks, labels and physical text measurements.
|
|
35
|
+
|
|
36
|
+
``gp`` maps fontsize (points), col and lwd (points). All text/line geometry
|
|
37
|
+
is portable to SVG, PNG and PDF. Explicit native values are never rescaled.
|
|
38
|
+
"""
|
|
39
|
+
def __init__(self,at=None,labels=None,labels_rot=0,gp=None,side='left',
|
|
40
|
+
facing='outside',direction='normal',scale=None):
|
|
41
|
+
if side not in ('left','right','top','bottom'):raise ValueError('invalid axis side')
|
|
42
|
+
if facing not in ('inside','outside'):raise ValueError('facing must be inside or outside')
|
|
43
|
+
if direction not in ('normal','reverse'):raise ValueError('direction must be normal or reverse')
|
|
44
|
+
if scale is None:raise ValueError('an explicit scale is required outside a heatmap annotation')
|
|
45
|
+
values=np.asarray(scale,dtype=float)
|
|
46
|
+
if values.shape!=(2,) or not np.isfinite(values).all() or values[1]<=values[0]:raise ValueError('scale must contain two increasing finite numbers')
|
|
47
|
+
gp=deepcopy(gp or {})
|
|
48
|
+
unknown=set(gp)-{'fontsize','col','lwd'}
|
|
49
|
+
if unknown:raise TypeError('unknown axis gp parameters: '+', '.join(sorted(unknown)))
|
|
50
|
+
self.fontsize=float(gp.get('fontsize',8));self.linewidth=float(gp.get('lwd',.5))
|
|
51
|
+
if not np.isfinite([self.fontsize,self.linewidth,labels_rot]).all() or self.fontsize<=0 or self.linewidth<0:raise ValueError('axis sizes must be finite; fontsize must be positive')
|
|
52
|
+
self.color=to_hex(gp.get('col','black'))
|
|
53
|
+
self.scale=values;self.side=side;self.facing=facing;self.direction=direction;self.labels_rot=float(labels_rot)
|
|
54
|
+
self._auto_ticks=at is None and labels is None
|
|
55
|
+
if at is None:
|
|
56
|
+
from .appearance import nice_ticks
|
|
57
|
+
at=nice_ticks(*values)
|
|
58
|
+
self.at=np.asarray(at,dtype=float)
|
|
59
|
+
if self.at.ndim!=1 or not np.isfinite(self.at).all():raise ValueError('at must be a finite vector')
|
|
60
|
+
self.labels=[f'{v:g}' for v in self.at] if labels is None else list(map(str,labels))
|
|
61
|
+
if len(self.labels)!=len(self.at):raise ValueError('labels must have the same length as at')
|
|
62
|
+
|
|
63
|
+
def padding(self,a):
|
|
64
|
+
if self.facing=='inside':return 0.
|
|
65
|
+
font=a.pt(self.fontsize)
|
|
66
|
+
theta=math.radians(self.labels_rot)
|
|
67
|
+
widths=[text_width(s,font,family=a.font_family) for s in self.labels]
|
|
68
|
+
if self.side in ('left','right'):
|
|
69
|
+
extent=max((abs(math.cos(theta))*w+abs(math.sin(theta))*font for w in widths),default=0)
|
|
70
|
+
else:extent=max((abs(math.sin(theta))*w+abs(math.cos(theta))*font for w in widths),default=0)
|
|
71
|
+
return a.mm(2)+extent+a.pt(1)
|
|
72
|
+
|
|
73
|
+
def draw_at(self,f,start,end,position,a=None):
|
|
74
|
+
"""Draw along a value axis; start/end are coordinates for min/max."""
|
|
75
|
+
a=a or Appearance(96)
|
|
76
|
+
horizontal=self.side in ('top','bottom')
|
|
77
|
+
sign=(-1 if self.side in ('left','top') else 1)*(1 if self.facing=='outside' else -1)
|
|
78
|
+
tick=a.mm(1);label_offset=a.mm(2);font=a.pt(self.fontsize)
|
|
79
|
+
def line(x1,y1,x2,y2):
|
|
80
|
+
f.write(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{self.color}" stroke-width="{a.pt(self.linewidth)}"/>')
|
|
81
|
+
line(start,position,end,position) if horizontal else line(position,start,position,end)
|
|
82
|
+
visible=[]
|
|
83
|
+
for index,(v,label) in enumerate(zip(self.at,self.labels)):
|
|
84
|
+
fraction=(v-self.scale[0])/(self.scale[1]-self.scale[0])
|
|
85
|
+
if self.direction=='reverse':fraction=1-fraction
|
|
86
|
+
if not 0<=fraction<=1:continue
|
|
87
|
+
value=start+fraction*(end-start)
|
|
88
|
+
width=text_width(label,font,family=a.font_family)
|
|
89
|
+
theta=math.radians(self.labels_rot)
|
|
90
|
+
extent=abs(math.cos(theta))*width+abs(math.sin(theta))*font if horizontal else abs(math.sin(theta))*width+abs(math.cos(theta))*font
|
|
91
|
+
center=value
|
|
92
|
+
if horizontal and self._auto_ticks and extent<=abs(end-start):
|
|
93
|
+
center=min(max(value,min(start,end)+extent/2),max(start,end)-extent/2)
|
|
94
|
+
visible.append((index,center,extent))
|
|
95
|
+
allowed={i for i,_,_ in visible}
|
|
96
|
+
centers={i:center for i,center,_ in visible}
|
|
97
|
+
if self._auto_ticks:
|
|
98
|
+
chosen=[]
|
|
99
|
+
for item in sorted(visible,key=lambda item:item[1]):
|
|
100
|
+
if not chosen or item[1]-item[2]/2>=chosen[-1][1]+chosen[-1][2]/2+a.mm(.75):chosen.append(item)
|
|
101
|
+
allowed={i for i,_,_ in chosen}
|
|
102
|
+
for index,(v,label) in enumerate(zip(self.at,self.labels)):
|
|
103
|
+
fraction=(v-self.scale[0])/(self.scale[1]-self.scale[0])
|
|
104
|
+
if fraction<0 or fraction>1:continue
|
|
105
|
+
if self.direction=='reverse':fraction=1-fraction
|
|
106
|
+
value=start+fraction*(end-start)
|
|
107
|
+
if horizontal:
|
|
108
|
+
line(value,position,value,position+sign*tick)
|
|
109
|
+
x,y=centers.get(index,value),position+sign*label_offset
|
|
110
|
+
# Account for the rotated text half-height so outside labels
|
|
111
|
+
# remain outside without placing their center on the edge.
|
|
112
|
+
width=text_width(label,font,family=a.font_family)
|
|
113
|
+
theta=math.radians(self.labels_rot)
|
|
114
|
+
y+=sign*(abs(math.sin(theta))*width+abs(math.cos(theta))*font)/2
|
|
115
|
+
anchor='middle'
|
|
116
|
+
else:
|
|
117
|
+
line(position,value,position+sign*tick,value)
|
|
118
|
+
x,y=position+sign*label_offset,value
|
|
119
|
+
anchor='end' if sign<0 else 'start'
|
|
120
|
+
if index not in allowed:continue
|
|
121
|
+
rotation=f' transform="rotate({-self.labels_rot},{x},{y})"' if self.labels_rot else ''
|
|
122
|
+
f.write(f'<text x="{x}" y="{y}" font-family={quoteattr(a.font_family)} font-size="{font}" fill="{self.color}" text-anchor="{anchor}" dominant-baseline="middle"{rotation}>{escape(label)}</text>')
|
|
123
|
+
|
|
124
|
+
def save(self,path,fmt=None,dpi=300,length_mm=40):
|
|
125
|
+
from .pdf_renderer import PdfSink
|
|
126
|
+
from .api import _save_ops
|
|
127
|
+
if not np.isfinite(length_mm) or length_mm<=0:raise ValueError('length_mm must be positive and finite')
|
|
128
|
+
a=Appearance(dpi);pad=a.mm(3)+self.padding(a)
|
|
129
|
+
length=a.mm(length_mm)
|
|
130
|
+
horizontal=self.side in ('top','bottom')
|
|
131
|
+
w,h=(length+2*pad,2*pad) if horizontal else (2*pad,length+2*pad)
|
|
132
|
+
position=pad
|
|
133
|
+
sink=PdfSink()
|
|
134
|
+
start,end=(pad,pad+length) if horizontal else (pad+length,pad)
|
|
135
|
+
self.draw_at(sink,start,end,position,a)
|
|
136
|
+
_save_ops(sink,math.ceil(w),math.ceil(h),dpi,a.font_family,path,fmt)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def annotation_axis_grob(**kwargs):return AnnotationAxis(**kwargs)
|
|
140
|
+
|
|
141
|
+
def grid_annotation_axis(sink,*,start,end,position,appearance=None,**kwargs):
|
|
142
|
+
"""Draw an axis onto a portable sink instead of R's implicit viewport."""
|
|
143
|
+
axis=AnnotationAxis(**kwargs);axis.draw_at(sink,start,end,position,appearance);return axis
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
__all__=['AnnotationAxis','default_axis_param','annotation_axis_grob','grid_annotation_axis']
|
tilesig/barplot.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Bounded native raster bars with explicit baseline, spacing and number styles."""
|
|
2
|
+
import base64
|
|
3
|
+
import math
|
|
4
|
+
from xml.sax.saxutils import escape
|
|
5
|
+
|
|
6
|
+
import cv2
|
|
7
|
+
import numpy as np
|
|
8
|
+
from .slice_geometry import gap_at
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from matplotlib.colors import to_rgb
|
|
11
|
+
|
|
12
|
+
from .annotation import AnnotationBase, _resolve_fontsize
|
|
13
|
+
from .renderer import _generate_distinct_colors
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
_UNSET=object()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class StackedBarAnnotation(AnnotationBase):
|
|
20
|
+
n_tracks=1
|
|
21
|
+
_draws_own_border=True
|
|
22
|
+
def __init__(self,x,*,colors=None,beside=False,bar_width=.6,ylim=None,baseline=0,
|
|
23
|
+
border=True,show_values=False,show_legend=False,background_color=_UNSET,axis=True,axis_param=None,which=None,gp=None,item_colors=None,numbers_format=None,add_numbers=None,attach=None,extend=None,numbers_gp=None,numbers_rot=None,numbers_offset=None,background=_UNSET,width=None,**kwargs):
|
|
24
|
+
from .graphics import validate_gp,gp_value
|
|
25
|
+
self.gp=validate_gp(gp,{'fill','col','lwd'})
|
|
26
|
+
self._background_grid=isinstance(background,(bool,np.bool_)) and bool(background)
|
|
27
|
+
if background is not _UNSET:
|
|
28
|
+
if background_color is not _UNSET:raise TypeError('background and background_color both supplied')
|
|
29
|
+
if isinstance(background,(bool,np.bool_)):background_color='#dddddd' if background else 'white'
|
|
30
|
+
elif isinstance(background,str):background_color=background
|
|
31
|
+
else:raise TypeError('background must be boolean or a native color string')
|
|
32
|
+
if background_color is _UNSET:background_color='white'
|
|
33
|
+
to_rgb(background_color)
|
|
34
|
+
self.numbers_gp=validate_gp(numbers_gp,{'col','fontsize','fontface','fontfamily'})
|
|
35
|
+
self._styled_numbers=any(v is not None for v in (numbers_gp,numbers_rot,numbers_offset))
|
|
36
|
+
self._auto_numbers_position=numbers_offset is None
|
|
37
|
+
if numbers_rot is not None and (not np.isscalar(numbers_rot) or not np.isfinite(numbers_rot)):raise ValueError('numbers_rot must be finite')
|
|
38
|
+
if numbers_offset is not None and (not np.isscalar(numbers_offset) or not np.isfinite(numbers_offset) or numbers_offset<0):raise ValueError('numbers_offset must be finite nonnegative mm')
|
|
39
|
+
if extend is not None and (not np.isscalar(extend) or not np.isfinite(extend) or extend<0):raise ValueError('extend must be finite nonnegative')
|
|
40
|
+
if attach is not None and not isinstance(attach,(bool,np.bool_)):raise TypeError('attach must be boolean')
|
|
41
|
+
self.attach=True if attach is None else bool(attach)
|
|
42
|
+
self.extend=extend;self.numbers_rot=0 if numbers_rot is None else float(numbers_rot)
|
|
43
|
+
self.numbers_offset=0 if numbers_offset is None else float(numbers_offset)
|
|
44
|
+
if 'fill' in self.gp:
|
|
45
|
+
if colors is not None and colors!='#cccccc':raise ValueError('supply either colors or gp fill')
|
|
46
|
+
colors=self.gp['fill']
|
|
47
|
+
from .axes import axis_parameters
|
|
48
|
+
if which not in (None,'row','column'):raise ValueError('which must be row or column')
|
|
49
|
+
side=kwargs.setdefault('side','left' if which=='row' else 'top')
|
|
50
|
+
if side not in ('top','bottom','left','right'):raise ValueError('invalid annotation side')
|
|
51
|
+
if which is not None and ((side in ('left','right'))!=(which=='row')):raise ValueError('side conflicts with which')
|
|
52
|
+
if width is not None:
|
|
53
|
+
if side not in ('left','right'):raise ValueError('width is a physical mm thickness for row barplots only')
|
|
54
|
+
if kwargs.get('height') is not None:raise TypeError('width and native height both supplied')
|
|
55
|
+
if not np.isscalar(width) or not np.isfinite(width) or width<=0:raise ValueError('width must be positive finite mm')
|
|
56
|
+
unknown=set(kwargs)-{'side','height','fontsize','label'}
|
|
57
|
+
if unknown:raise TypeError('unsupported barplot options: '+', '.join(sorted(unknown)))
|
|
58
|
+
self.axis=bool(axis);self.axis_param=dict(axis_param or {})
|
|
59
|
+
axis_parameters(self.axis_param,'row' if side in ('left','right') else 'column')
|
|
60
|
+
positional=not isinstance(x,(pd.Series,pd.DataFrame))
|
|
61
|
+
frame=x.to_frame() if isinstance(x,pd.Series) else pd.DataFrame(x).copy()
|
|
62
|
+
frame=frame.apply(pd.to_numeric,errors='raise')
|
|
63
|
+
super().__init__(df=frame,**kwargs)
|
|
64
|
+
if width is not None:self._fixed_height_mm=float(width)
|
|
65
|
+
self._positional=positional
|
|
66
|
+
self._graphical_ids=pd.Series(np.arange(len(frame)),index=frame.index.map(str))
|
|
67
|
+
if add_numbers is not None:show_values=bool(add_numbers)
|
|
68
|
+
if numbers_format is not None and not callable(numbers_format) and not isinstance(numbers_format,str):raise TypeError('numbers_format must be a format spec or callable')
|
|
69
|
+
self.numbers_format=numbers_format
|
|
70
|
+
self.item_colors=None
|
|
71
|
+
if item_colors is not None:
|
|
72
|
+
from .specialized_support import color_by_ids
|
|
73
|
+
if frame.shape[1]!=1:raise ValueError('item_colors requires a single bar series')
|
|
74
|
+
self.item_colors=pd.Series(color_by_ids(item_colors,frame.index))
|
|
75
|
+
if not 0<bar_width<=1:raise ValueError('bar_width must be in (0,1]')
|
|
76
|
+
if isinstance(baseline,str):
|
|
77
|
+
if baseline not in ('min','max'):raise ValueError('baseline must be finite numeric, min or max')
|
|
78
|
+
elif not np.isscalar(baseline) or not np.isfinite(baseline):raise ValueError('baseline must be finite numeric, min or max')
|
|
79
|
+
if frame.shape[1]>1 and not beside and baseline!=0:
|
|
80
|
+
raise ValueError('nonzero baseline is ambiguous for stacked multiseries bars; use beside=True or baseline=0')
|
|
81
|
+
self.baseline=baseline
|
|
82
|
+
if ylim is not None and (len(ylim)!=2 or not np.isfinite(ylim).all() or ylim[1]<=ylim[0]):raise ValueError('ylim must be an increasing finite pair')
|
|
83
|
+
self.beside=bool(beside);self.bar_width=bar_width;self.ylim=ylim
|
|
84
|
+
self.border=bool(border);self.show_values=bool(show_values);self.background_color=background_color
|
|
85
|
+
self._show_legend=bool(show_legend)
|
|
86
|
+
if isinstance(colors,str):colors={c:colors for c in frame.columns}
|
|
87
|
+
if colors is not None and not isinstance(colors,dict):
|
|
88
|
+
if not len(colors):raise ValueError('colors must not be empty')
|
|
89
|
+
colors={c:colors[i%len(colors)] for i,c in enumerate(frame.columns)}
|
|
90
|
+
auto=_generate_distinct_colors(len(frame.columns)) if any(c not in (colors or {}) for c in frame.columns) else []
|
|
91
|
+
self.colors={str(c):colors[c] if colors is not None and c in colors else tuple(v/255 for v in auto[i]) for i,c in enumerate(frame.columns)}
|
|
92
|
+
self.legend_colors=self.colors
|
|
93
|
+
|
|
94
|
+
def _bind_item_ids(self,names):
|
|
95
|
+
super()._bind_item_ids(names)
|
|
96
|
+
if self.item_colors is not None:
|
|
97
|
+
self.item_colors=self.item_colors.copy(deep=True)
|
|
98
|
+
self.item_colors.index=pd.Index(names).map(str)
|
|
99
|
+
|
|
100
|
+
def _format_number(self,value):
|
|
101
|
+
if callable(self.numbers_format):return str(self.numbers_format(value))
|
|
102
|
+
return format(value,self.numbers_format or 'g')
|
|
103
|
+
|
|
104
|
+
def _resolved_baseline(self,values):
|
|
105
|
+
if self.baseline=='min':return float(values.min()) if values.size else 0.
|
|
106
|
+
if self.baseline=='max':return float(values.max()) if values.size else 0.
|
|
107
|
+
return float(self.baseline)
|
|
108
|
+
|
|
109
|
+
def _range(self):
|
|
110
|
+
values=self.df.to_numpy(dtype=float)
|
|
111
|
+
if np.isinf(values).any():raise ValueError('bar data contain infinite values')
|
|
112
|
+
values=np.nan_to_num(values,nan=0)
|
|
113
|
+
baseline=self._resolved_baseline(values)
|
|
114
|
+
if values.shape[1]==1:
|
|
115
|
+
low=float(values.min()) if values.size else baseline
|
|
116
|
+
high=float(values.max()) if values.size else baseline
|
|
117
|
+
elif self.beside:
|
|
118
|
+
low=baseline+float(values.min());high=baseline+float(values.max())
|
|
119
|
+
else:
|
|
120
|
+
low=float(np.minimum(values,0).sum(axis=1).min())
|
|
121
|
+
high=float(np.maximum(values,0).sum(axis=1).max())
|
|
122
|
+
lo,hi=self.ylim if self.ylim is not None else (min(baseline,low),max(baseline,high))
|
|
123
|
+
if not np.isfinite([lo,hi]).all():raise ValueError('bar range is not finite')
|
|
124
|
+
if hi<=lo:hi=lo+1
|
|
125
|
+
if self.extend is not None:
|
|
126
|
+
span=hi-lo
|
|
127
|
+
# Explicit extension follows the native axis range with one-sided
|
|
128
|
+
# padding when the baseline is an extreme, otherwise both sides.
|
|
129
|
+
fractions=self.baseline==0 and not self.beside and np.all(np.abs(values.sum(axis=1)-1)<1e-6)
|
|
130
|
+
if fractions:lo,hi=0.,1.
|
|
131
|
+
elif self.baseline=='min' or baseline<=lo:hi+=self.extend*span
|
|
132
|
+
elif self.baseline=='max' or baseline>=hi:lo-=self.extend*span
|
|
133
|
+
else:lo-=self.extend*span;hi+=self.extend*span
|
|
134
|
+
return values,float(lo),float(hi)
|
|
135
|
+
|
|
136
|
+
def _axis_model(self,vertical):
|
|
137
|
+
from .axes import AnnotationAxis,axis_parameters
|
|
138
|
+
_,lo,hi=self._range()
|
|
139
|
+
return AnnotationAxis(scale=(lo,hi),**axis_parameters(self.axis_param,'row' if vertical else 'column'))
|
|
140
|
+
|
|
141
|
+
def axis_padding(self,renderer):
|
|
142
|
+
padding={}
|
|
143
|
+
if self.axis:
|
|
144
|
+
axis=self._axis_model(self.side in ('left','right'))
|
|
145
|
+
padding[axis.side]=axis.padding(renderer._appearance)
|
|
146
|
+
if self.show_values and self._styled_numbers:
|
|
147
|
+
from .graphics import gp_value,font_face
|
|
148
|
+
from .name_layout import envelope
|
|
149
|
+
a=renderer._appearance
|
|
150
|
+
# Use the same private NA-to-zero values as the drawing path.
|
|
151
|
+
for i,row in enumerate(self._range()[0]):
|
|
152
|
+
for j,value in enumerate(row):
|
|
153
|
+
style_id=int(self._graphical_ids.get(str(self.df.index[i]),i)) if self.df.shape[1]==1 else j
|
|
154
|
+
size=a.pt(float(gp_value(self.numbers_gp,'fontsize',style_id))) if 'fontsize' in self.numbers_gp else _resolve_fontsize(renderer,self.fontsize)
|
|
155
|
+
bold,italic=font_face(gp_value(self.numbers_gp,'fontface',style_id,'plain'))
|
|
156
|
+
node=dict(text=self._format_number(value),size=size,bold=bold,italic=italic,anchor='middle',rotation=-self.numbers_rot,x=0,y=0)
|
|
157
|
+
family=gp_value(self.numbers_gp,'fontfamily',style_id,a.font_family)
|
|
158
|
+
x0,y0,x1,y1=envelope(node,family)
|
|
159
|
+
for side,extent in [('left',-x0),('right',x1),('top',-y0),('bottom',y1)]:
|
|
160
|
+
padding[side]=max(padding.get(side,0),extent+a.mm(self.numbers_offset))
|
|
161
|
+
return padding
|
|
162
|
+
|
|
163
|
+
def draw(self,f,start_x,start_y,pixel_size,bounds,gap_pixels,direction,renderer):
|
|
164
|
+
vertical=direction in ('left','right')
|
|
165
|
+
height=max(1,round(renderer._annot_height(self)))
|
|
166
|
+
values,lo,hi=self._range()
|
|
167
|
+
baseline=self._resolved_baseline(values)
|
|
168
|
+
cursor=start_y if vertical else start_x
|
|
169
|
+
cross=start_x if vertical else start_y
|
|
170
|
+
if direction in ('up','left'):cross-=height
|
|
171
|
+
bg=np.rint(np.asarray(to_rgb(self.background_color))[::-1]*255).astype(np.uint8)
|
|
172
|
+
colors=[np.rint(np.asarray(to_rgb(self.colors[str(c)]))[::-1]*255).astype(np.uint8) for c in self.df.columns]
|
|
173
|
+
# Stroke parameters are ID-bound for scalar bars and series-bound for
|
|
174
|
+
# multiseries bars. Raster outlines stay within each bar footprint.
|
|
175
|
+
stroke_colors=[];stroke_widths=[]
|
|
176
|
+
from .graphics import gp_value
|
|
177
|
+
styles=len(values) if values.shape[1]==1 else values.shape[1]
|
|
178
|
+
for i in range(styles if any(k in self.gp for k in ('col','lwd')) else 0):
|
|
179
|
+
style_id=int(self._graphical_ids.get(str(self.df.index[i]),i)) if values.shape[1]==1 else i
|
|
180
|
+
col=gp_value(self.gp,'col',style_id,'black') if 'col' in self.gp or 'lwd' in self.gp else None
|
|
181
|
+
stroke_colors.append(None if col is None else np.rint(np.asarray(to_rgb(col))[::-1]*255).astype(np.uint8))
|
|
182
|
+
stroke_widths.append(renderer._appearance.pt(float(gp_value(self.gp,'lwd',style_id,1))))
|
|
183
|
+
stroke_palette=np.asarray([np.zeros(3,np.uint8) if c is None else c for c in stroke_colors])
|
|
184
|
+
stroke_visible=np.asarray([c is not None for c in stroke_colors])
|
|
185
|
+
stroke_width_array=np.asarray(stroke_widths)
|
|
186
|
+
axis_start=cursor
|
|
187
|
+
reverse=self.axis_param.get('direction')=='reverse'
|
|
188
|
+
base_reverse=direction in ('up','left') and not (vertical and getattr(self,'_cartesian_scale',False))
|
|
189
|
+
grid_ticks=self._axis_model(vertical).at if self._background_grid else ()
|
|
190
|
+
for slice_index,(begin,end) in enumerate(bounds):
|
|
191
|
+
length=(end-begin)*pixel_size
|
|
192
|
+
display=max(1,math.ceil(length))
|
|
193
|
+
for start in range(0,display,1024):
|
|
194
|
+
n=min(1024,display-start)
|
|
195
|
+
source=begin+(np.arange(start,start+n)+.5)*(end-begin)/display
|
|
196
|
+
item=np.minimum(end-1,source.astype(int))
|
|
197
|
+
fractional=source-np.floor(source)
|
|
198
|
+
canvas=np.empty((height,n,3),np.uint8);canvas[:]=bg
|
|
199
|
+
if self._background_grid:
|
|
200
|
+
# The R background is a genuine grid underneath the bars.
|
|
201
|
+
# Build it inside the same bounded raster tiles, including
|
|
202
|
+
# when the caller suppresses axis glyphs.
|
|
203
|
+
half=max(.5,renderer._appearance.pt(.5)/2)
|
|
204
|
+
centers=np.abs(fractional-.5)*pixel_size<=half+1e-9
|
|
205
|
+
canvas[:,centers]=255
|
|
206
|
+
cross_pixels=np.arange(height)+.5
|
|
207
|
+
for tick in grid_ticks:
|
|
208
|
+
fraction=(tick-lo)/(hi-lo)
|
|
209
|
+
if not 0<=fraction<=1:continue
|
|
210
|
+
if base_reverse!=reverse:fraction=1-fraction
|
|
211
|
+
line=np.abs(cross_pixels-fraction*height)<=half+1e-9
|
|
212
|
+
canvas[line,:]=255
|
|
213
|
+
item_palette=None
|
|
214
|
+
if self.item_colors is not None:
|
|
215
|
+
names=self.df.index.map(str)
|
|
216
|
+
if not set(names)<=set(self.item_colors.index):raise ValueError('bar item colors do not cover displayed IDs')
|
|
217
|
+
item_palette=np.asarray([np.rint(np.asarray(to_rgb(self.item_colors.loc[k]))[::-1]*255).astype(np.uint8) for k in names])
|
|
218
|
+
accum_pos=np.zeros(n);accum_neg=np.zeros(n)
|
|
219
|
+
for j in range(values.shape[1]):
|
|
220
|
+
v=values[item,j]
|
|
221
|
+
if self.beside:
|
|
222
|
+
base=np.full(n,baseline)
|
|
223
|
+
if self.attach:
|
|
224
|
+
local=(fractional-(1-self.bar_width)/2)/self.bar_width
|
|
225
|
+
inbar=(local>=j/values.shape[1]) & (local<(j+1)/values.shape[1])
|
|
226
|
+
else:
|
|
227
|
+
local=fractional*values.shape[1]-j
|
|
228
|
+
inbar=np.abs(local-.5)<=self.bar_width/2
|
|
229
|
+
elif values.shape[1]==1:
|
|
230
|
+
base=np.full(n,baseline)
|
|
231
|
+
inbar=np.abs(fractional-.5)<=self.bar_width/2
|
|
232
|
+
else:
|
|
233
|
+
base=np.where(v>=0,accum_pos,accum_neg)
|
|
234
|
+
inbar=np.abs(fractional-.5)<=self.bar_width/2
|
|
235
|
+
accum_pos+=np.maximum(v,0);accum_neg+=np.minimum(v,0)
|
|
236
|
+
endpoint=v if values.shape[1]==1 else base+v
|
|
237
|
+
p0=(base-lo)/(hi-lo);p1=(endpoint-lo)/(hi-lo)
|
|
238
|
+
y0=np.minimum(p0,p1);y1=np.maximum(p0,p1)
|
|
239
|
+
normalized=(np.arange(height)+.5)/height
|
|
240
|
+
if base_reverse!=reverse:normalized=1-normalized
|
|
241
|
+
mask=(normalized[:,None]>=y0) & (normalized[:,None]<y1) & inbar
|
|
242
|
+
if item_palette is None:canvas[mask]=colors[j]
|
|
243
|
+
else:
|
|
244
|
+
item_rgb=np.broadcast_to(item_palette[item][None,:,:],canvas.shape);canvas[mask]=item_rgb[mask]
|
|
245
|
+
# Native raster per-bar outlines, independent of band border.
|
|
246
|
+
if stroke_colors:
|
|
247
|
+
if values.shape[1]==1:
|
|
248
|
+
widths=stroke_width_array[item]
|
|
249
|
+
visible=stroke_visible[item]
|
|
250
|
+
stroke_rgb=np.broadcast_to(stroke_palette[item][None,:,:],canvas.shape)
|
|
251
|
+
else:
|
|
252
|
+
widths=np.full(n,stroke_widths[j]);visible=np.full(n,stroke_colors[j] is not None)
|
|
253
|
+
stroke_rgb=stroke_colors[j]
|
|
254
|
+
if np.any(visible & (widths>0)):
|
|
255
|
+
if self.beside and self.attach:
|
|
256
|
+
left=(1-self.bar_width)/2+j*self.bar_width/values.shape[1]
|
|
257
|
+
right=left+self.bar_width/values.shape[1]
|
|
258
|
+
elif self.beside:
|
|
259
|
+
left=(j+(1-self.bar_width)/2)/values.shape[1]
|
|
260
|
+
right=left+self.bar_width/values.shape[1]
|
|
261
|
+
else:left,right=(1-self.bar_width)/2,(1+self.bar_width)/2
|
|
262
|
+
along_edge=np.minimum(fractional-left,right-fractional)*pixel_size
|
|
263
|
+
across_edge=np.minimum(normalized[:,None]-y0,y1-normalized[:,None])*height
|
|
264
|
+
edge=mask & ((along_edge[None,:]<widths[None,:]) | (across_edge<widths[None,:])) & visible[None,:]
|
|
265
|
+
if values.shape[1]==1:canvas[edge]=stroke_rgb[edge]
|
|
266
|
+
else:canvas[edge]=stroke_rgb
|
|
267
|
+
if vertical:canvas=canvas.transpose(1,0,2)
|
|
268
|
+
xx,yy,ww,hh=(cross,cursor+start*length/display,height,n*length/display) if vertical else (cursor+start*length/display,cross,n*length/display,height)
|
|
269
|
+
ok,buf=cv2.imencode('.png',np.ascontiguousarray(canvas),[cv2.IMWRITE_PNG_COMPRESSION,1])
|
|
270
|
+
if not ok:raise RuntimeError('barplot PNG encoding failed')
|
|
271
|
+
if hasattr(f,'write_image'):f.write_image(xx,yy,ww,hh,buf.tobytes())
|
|
272
|
+
else:
|
|
273
|
+
b64=base64.b64encode(buf).decode()
|
|
274
|
+
f.write(f'<image x="{xx}" y="{yy}" width="{ww}" height="{hh}" preserveAspectRatio="none" href="data:image/png;base64,{b64}" xlink:href="data:image/png;base64,{b64}"/>')
|
|
275
|
+
if self.show_values:
|
|
276
|
+
fontsize=_resolve_fontsize(renderer,self.fontsize)
|
|
277
|
+
# Sample labels to the available display space, while raster
|
|
278
|
+
# bars continue to represent every input item.
|
|
279
|
+
stride=max(1,math.ceil(fontsize*1.5/max(pixel_size,1e-12)))
|
|
280
|
+
for i in range(begin,end,stride):
|
|
281
|
+
pos=neg=0.
|
|
282
|
+
for j,v in enumerate(values[i]):
|
|
283
|
+
base=baseline if self.beside or values.shape[1]==1 else pos if v>=0 else neg
|
|
284
|
+
if v>=0:pos+=v
|
|
285
|
+
else:neg+=v
|
|
286
|
+
if v==0 and not self._styled_numbers:continue
|
|
287
|
+
along=cursor+(i-begin+.5)*pixel_size
|
|
288
|
+
if self.beside:along+=((j+.5)/values.shape[1]-.5)*(self.bar_width if self.attach else 1)*pixel_size
|
|
289
|
+
endpoint=v if values.shape[1]==1 else base+v
|
|
290
|
+
value=endpoint if self._styled_numbers else (base+endpoint)/2
|
|
291
|
+
level=np.clip((value-lo)/(hi-lo),0,1)
|
|
292
|
+
across=cross+height*(1-level if base_reverse!=reverse else level)
|
|
293
|
+
xx,yy=(across,along) if vertical else (along,across)
|
|
294
|
+
if self._styled_numbers:
|
|
295
|
+
from .appearance import _text
|
|
296
|
+
from .graphics import gp_value,font_face,color
|
|
297
|
+
from .style import resolved_font_family
|
|
298
|
+
a=renderer._appearance
|
|
299
|
+
style_id=int(self._graphical_ids.get(str(self.df.index[i]),i)) if values.shape[1]==1 else j
|
|
300
|
+
size=a.pt(float(gp_value(self.numbers_gp,'fontsize',style_id))) if 'fontsize' in self.numbers_gp else fontsize
|
|
301
|
+
rgb=color(gp_value(self.numbers_gp,'col',style_id,'black'))
|
|
302
|
+
bold,italic=font_face(gp_value(self.numbers_gp,'fontface',style_id,'plain'))
|
|
303
|
+
family=gp_value(self.numbers_gp,'fontfamily',style_id)
|
|
304
|
+
family=None if family is None else resolved_font_family(family)
|
|
305
|
+
offset=a.mm(self.numbers_offset)*(-1 if base_reverse!=reverse else 1)
|
|
306
|
+
if vertical:xx+=offset
|
|
307
|
+
else:yy+=offset
|
|
308
|
+
if self._auto_numbers_position:
|
|
309
|
+
from .name_layout import envelope
|
|
310
|
+
box=envelope(dict(text=self._format_number(v),x=xx,y=yy,size=size,
|
|
311
|
+
anchor='middle',rotation=-self.numbers_rot,bold=bold,italic=italic),
|
|
312
|
+
family or a.font_family)
|
|
313
|
+
axis=0 if vertical else 1
|
|
314
|
+
if box[axis+2]-box[axis]>height+1e-9:
|
|
315
|
+
raise ValueError('bar number labels do not fit the annotation band; enlarge it, shorten labels, or set an explicit numbers_offset')
|
|
316
|
+
shift=max(cross-box[axis],min(0,cross+height-box[axis+2]))
|
|
317
|
+
if vertical:xx+=shift
|
|
318
|
+
else:yy+=shift
|
|
319
|
+
_text(f,xx,yy,self._format_number(v),size,'middle',bold=bold,italic=italic,
|
|
320
|
+
rotation=-self.numbers_rot or None,color=rgb,family=family)
|
|
321
|
+
else:
|
|
322
|
+
f.write(f'<text x="{xx}" y="{yy}" font-family="Arial" font-size="{fontsize}" text-anchor="middle" dominant-baseline="middle" fill="black">{escape(self._format_number(v))}</text>')
|
|
323
|
+
if self.border:
|
|
324
|
+
xx,yy,ww,hh=(cross,cursor,height,length) if vertical else (cursor,cross,length,height)
|
|
325
|
+
f.write(f'<rect x="{xx}" y="{yy}" width="{ww}" height="{hh}" fill="none" stroke="black" stroke-width="0.5"/>')
|
|
326
|
+
cursor+=length+gap_at(gap_pixels,slice_index)
|
|
327
|
+
if self.axis:
|
|
328
|
+
axis=self._axis_model(vertical)
|
|
329
|
+
position=axis_start if axis.side in ('left','top') else cursor-gap_at(gap_pixels,len(bounds)-1)
|
|
330
|
+
start,end=(cross+height,cross) if base_reverse else (cross,cross+height)
|
|
331
|
+
axis.draw_at(f,start,end,position,renderer._appearance)
|
|
332
|
+
if getattr(renderer,'style','legacy')=='complexheatmap':
|
|
333
|
+
from .annotation_names import draw_name
|
|
334
|
+
draw_name(self,f,renderer,axis_start,cursor-gap_at(gap_pixels,len(bounds)-1),cross,height,vertical)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
__all__=['StackedBarAnnotation']
|
tilesig/block_heatmap.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Native views of a prepared, resolution-independent block grid."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from .api import Heatmap, HeatmapList
|
|
9
|
+
from .block_summary import BlockSummary
|
|
10
|
+
from .style import ColorMapping, colorRamp2
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_FIXED_OPTIONS = {
|
|
14
|
+
"matrix", "df", "config", "style", "mask", "mask_col", "scale", "z_score",
|
|
15
|
+
"row_order", "column_order", "row_split", "split", "col_split", "column_split",
|
|
16
|
+
"row_cluster", "col_cluster", "cluster_rows", "cluster_columns",
|
|
17
|
+
"row_km", "column_km", "km", "row_km_repeats", "column_km_repeats",
|
|
18
|
+
"row_cluster_map", "col_cluster_map", "cluster_row_slices", "cluster_column_slices",
|
|
19
|
+
"cluster_dendrogram", "cluster_order", "row_cluster_order", "col_cluster_order", "reverse_columns",
|
|
20
|
+
"row_compression", "col_compression", "raster_resize_mat", "df_filter",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _panel_options(common, specific, name):
|
|
25
|
+
if specific is not None and not isinstance(specific, Mapping):
|
|
26
|
+
raise TypeError(f"{name} must be a mapping of native Heatmap options")
|
|
27
|
+
resolved = {**common, **(specific if specific is not None else {})}
|
|
28
|
+
fixed = _FIXED_OPTIONS.intersection(resolved)
|
|
29
|
+
if resolved.get("ordering") is not None:
|
|
30
|
+
fixed.add("ordering")
|
|
31
|
+
if fixed:
|
|
32
|
+
raise ValueError("Options controlled by the block summary: " + ", ".join(sorted(fixed)))
|
|
33
|
+
resolved["ordering"] = None
|
|
34
|
+
return resolved
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _numeric_palette(options):
|
|
38
|
+
palette = options.get("col", options.get("cmap"))
|
|
39
|
+
if isinstance(palette, Mapping) or isinstance(palette, ColorMapping) and palette.is_categorical:
|
|
40
|
+
raise ValueError("Block heatmaps require a continuous colour mapping")
|
|
41
|
+
return palette
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _panel(summary, values, options):
|
|
45
|
+
missing = values.isna()
|
|
46
|
+
has_missing = missing.to_numpy().any()
|
|
47
|
+
if has_missing:
|
|
48
|
+
# A display mask retains empty axes while keeping the prepared statistics intact.
|
|
49
|
+
values = values.fillna(options["vmin"])
|
|
50
|
+
plot = Heatmap(
|
|
51
|
+
values, scale="none", style="complexheatmap", row_cluster=False, col_cluster=False,
|
|
52
|
+
cluster_dendrogram=False, reverse_columns=False,
|
|
53
|
+
row_compression=1, col_compression=1, row_split=summary.row_groups,
|
|
54
|
+
column_split=summary.column_groups, **options,
|
|
55
|
+
)
|
|
56
|
+
if has_missing:
|
|
57
|
+
from .cell_mask import CellMask
|
|
58
|
+
plot._cell_mask = CellMask.from_missing(missing)
|
|
59
|
+
return plot
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _mean_panel(summary, options):
|
|
63
|
+
values = summary.means
|
|
64
|
+
palette = _numeric_palette(options)
|
|
65
|
+
if isinstance(palette, ColorMapping):
|
|
66
|
+
low, high = palette.breaks[[0, -1]]
|
|
67
|
+
elif values.notna().to_numpy().any():
|
|
68
|
+
low, high = values.min().min(), values.max().max()
|
|
69
|
+
else:
|
|
70
|
+
low, high = 0., 1.
|
|
71
|
+
low = float(low if options.get("vmin") is None else options["vmin"])
|
|
72
|
+
high = float(high if options.get("vmax") is None else options["vmax"])
|
|
73
|
+
if not np.isfinite([low, high]).all() or low > high:
|
|
74
|
+
raise ValueError("Block mean colour limits must be finite and ordered")
|
|
75
|
+
options.update(vmin=low, vmax=high)
|
|
76
|
+
options.setdefault("name", "Block mean")
|
|
77
|
+
options.setdefault("column_title", "Block mean")
|
|
78
|
+
labels = options.get("cell_labels")
|
|
79
|
+
if isinstance(labels, (bool, np.bool_)) and labels:
|
|
80
|
+
options["cell_labels"] = values
|
|
81
|
+
return _panel(summary, values, options)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _share_panel(summary, options, show_counts):
|
|
85
|
+
values = summary.share
|
|
86
|
+
palette = _numeric_palette(options)
|
|
87
|
+
low, high = palette.breaks[[0, -1]] if isinstance(palette, ColorMapping) else (0., 1.)
|
|
88
|
+
low = float(low if options.get("vmin") is None else options["vmin"])
|
|
89
|
+
high = float(high if options.get("vmax") is None else options["vmax"])
|
|
90
|
+
if not 0 <= low < high <= 1:
|
|
91
|
+
raise ValueError("Share colour limits must increase within [0, 1]")
|
|
92
|
+
options.update(vmin=low, vmax=high)
|
|
93
|
+
if palette is None:
|
|
94
|
+
space = options.pop("color_space", None) or "LAB"
|
|
95
|
+
options["col"] = colorRamp2([low, high], ["#f6faf9", "#68aaa0"], space=space)
|
|
96
|
+
legend = dict(options.get("heatmap_legend_param") or {})
|
|
97
|
+
ticks = list(legend.get("at", np.linspace(low, high, 5)))
|
|
98
|
+
legend["at"] = ticks
|
|
99
|
+
legend.setdefault("labels", [f"{100 * tick:g}%" for tick in ticks])
|
|
100
|
+
options["heatmap_legend_param"] = legend
|
|
101
|
+
threshold_label = str(summary.threshold).removesuffix(".0")
|
|
102
|
+
title = f"Share above {threshold_label}"
|
|
103
|
+
options.setdefault("name", title)
|
|
104
|
+
options.setdefault("column_title", f"{title} (hits / measured)" if show_counts else title)
|
|
105
|
+
options.setdefault("number_format", "%.1f%%")
|
|
106
|
+
labels = options.get("cell_labels")
|
|
107
|
+
if show_counts:
|
|
108
|
+
if labels is not None and (not isinstance(labels, (bool, np.bool_)) or labels):
|
|
109
|
+
raise ValueError("show_counts conflicts with share cell_labels")
|
|
110
|
+
budget = options.get("max_number_labels", 10000)
|
|
111
|
+
if not isinstance(budget, (int, np.integer)) or budget < values.size:
|
|
112
|
+
raise ValueError("cell label budget exceeded; increase max_number_labels explicitly")
|
|
113
|
+
counts = [
|
|
114
|
+
[f"{hit} / {count}" if count else None for hit, count in zip(hits, measured)]
|
|
115
|
+
for hits, measured in zip(summary.hits.to_numpy(), summary.measured.to_numpy())
|
|
116
|
+
]
|
|
117
|
+
options["cell_labels"] = pd.DataFrame(counts, index=values.index, columns=values.columns)
|
|
118
|
+
elif isinstance(labels, (bool, np.bool_)) and labels:
|
|
119
|
+
options["cell_labels"] = 100 * values
|
|
120
|
+
return _panel(summary, values, options)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def block_heatmap(summary, *, view="mean", show_counts=False, mean_options=None,
|
|
124
|
+
share_options=None, gap_mm=7, **heatmap_options):
|
|
125
|
+
"""Draw block means, exceedance shares, or both on the same fixed grid.
|
|
126
|
+
|
|
127
|
+
Use :func:`prepare_block_summary` once, then keep its result for multiple
|
|
128
|
+
views or export sizes. Each panel uses the prepared row and column order.
|
|
129
|
+
Empty blocks are drawn in the missing-cell colour.
|
|
130
|
+
Colour limits affect drawing only. In the share view colours use fractions
|
|
131
|
+
and legend labels use percentages.
|
|
132
|
+
|
|
133
|
+
Example:
|
|
134
|
+
import tilesig as ts
|
|
135
|
+
|
|
136
|
+
summary = ts.prepare_block_summary(matrix, block_shape=(4, 8), threshold=2.)
|
|
137
|
+
plot = ts.block_heatmap(summary, view="both", show_counts=True)
|
|
138
|
+
plot.save("blocks.png")
|
|
139
|
+
"""
|
|
140
|
+
if not isinstance(summary, BlockSummary):
|
|
141
|
+
raise TypeError("summary must come from prepare_block_summary")
|
|
142
|
+
if view not in ("mean", "share", "both"):
|
|
143
|
+
raise ValueError("view must be mean, share or both")
|
|
144
|
+
if not isinstance(show_counts, (bool, np.bool_)):
|
|
145
|
+
raise TypeError("show_counts must be boolean")
|
|
146
|
+
if show_counts and view == "mean":
|
|
147
|
+
raise ValueError("show_counts requires the share panel")
|
|
148
|
+
if view != "mean" and summary.threshold is None:
|
|
149
|
+
raise ValueError("Prepare the block summary with a threshold to show shares")
|
|
150
|
+
common = {"show_row_names": False, "show_column_names": False, **heatmap_options}
|
|
151
|
+
if view != "share":
|
|
152
|
+
mean = _mean_panel(summary, _panel_options(common, mean_options, "mean_options"))
|
|
153
|
+
if view == "mean":
|
|
154
|
+
return mean
|
|
155
|
+
share = _share_panel(summary, _panel_options(common, share_options, "share_options"), show_counts)
|
|
156
|
+
if view == "share":
|
|
157
|
+
return share
|
|
158
|
+
return HeatmapList(mean, share, gap_mm=gap_mm)
|