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,104 @@
1
+ """Collection band sizes/gaps shared by layout, drawing and component queries."""
2
+ from collections.abc import Mapping
3
+ import uuid
4
+ import numpy as np
5
+ from .annotation import SimpleAnnotation
6
+
7
+
8
+ def _values(value,names,label,default=None):
9
+ if value is None:return [default]*len(names)
10
+ if isinstance(value,Mapping):
11
+ if set(value)-set(names):raise ValueError('unknown '+label+' tracks')
12
+ return [value.get(n,default) for n in names]
13
+ if isinstance(value,str) or np.isscalar(value):return [value]*len(names)
14
+ values=list(value)
15
+ if len(values)!=len(names):raise ValueError(label+' must match the annotation track count')
16
+ return values
17
+
18
+
19
+ def configure(collection,*,simple_anno_size=None,annotation_height=None,annotation_width=None,
20
+ gap=None,annotation_label=None,annotation_name_side=None,show_annotation_name=True,height=None,width=None,gp=None,annotation_name_align=False):
21
+ if not isinstance(annotation_name_align,(bool,np.bool_)):raise TypeError('annotation_name_align must be boolean')
22
+ # A value token survives copies without retaining references to source tracks.
23
+ # Name placement resolves only the active members present in the current plot.
24
+ alignment=uuid.uuid4().hex if annotation_name_align else None
25
+ row=collection.which=='row';names=[str(h.label) for h in collection]
26
+ if (row and annotation_height is not None) or (not row and annotation_width is not None):
27
+ raise ValueError('annotation_height is for column orientation; annotation_width is for row orientation')
28
+ if (row and height is not None) or (not row and width is not None):raise ValueError('height is for column annotations; width is for row annotations')
29
+ from .graphics import validate_gp,_vector
30
+ style=validate_gp(gp,{'col','lwd'})
31
+ if any(_vector(v,k) for k,v in style.items()):raise ValueError('collection gp must be uniform; use anno_simple for item styling')
32
+ if simple_anno_size is not None and (not np.isscalar(simple_anno_size) or not np.isfinite(simple_anno_size) or simple_anno_size<=0):raise ValueError('simple_anno_size must be positive finite mm')
33
+ sizes=_values(annotation_width if row else annotation_height,names,'annotation size')
34
+ labels=_values(annotation_label,names,'annotation_label')
35
+ sides=_values(annotation_name_side,names,'annotation_name_side')
36
+ visibility=_values(show_annotation_name,names,'show_annotation_name',True)
37
+ gaps=[]
38
+ if gap is not None:
39
+ gaps=[gap]*max(0,len(names)-1) if np.isscalar(gap) else list(gap)
40
+ if len(gaps)!=max(0,len(names)-1) or any(not np.isscalar(g) or not np.isfinite(g) or g<0 for g in gaps):raise ValueError('gap must be nonnegative finite mm, scalar or one per adjacent pair')
41
+ total=width if row else height
42
+ if total is not None:
43
+ if simple_anno_size is not None or annotation_width is not None or annotation_height is not None:raise ValueError('total size and individual annotation sizes conflict')
44
+ # An explicitly sized collection has an explicit gap in mm, including
45
+ # the unchanged default1pt clearance converted to mm.
46
+ if gap is None:gaps=[25.4/72]*max(0,len(names)-1);gap=25.4/72
47
+ bands=sum(getattr(h,'n_tracks',len(h.df.columns) if h.df is not None else 1) for h in collection)
48
+ if not bands or not np.isscalar(total) or not np.isfinite(total) or total<=sum(gaps):raise ValueError('total annotation size must exceed gaps')
49
+ # Uniform band allocation is an explicit Python subset of R resizing.
50
+ internal=sum(max(0,getattr(h,'n_tracks',len(h.df.columns) if h.df is not None else 1)-1) for h in collection)*25.4/72
51
+ size=(float(total)-sum(gaps)-internal)/bands
52
+ if size<=0:raise ValueError('total annotation size must exceed internal gaps')
53
+ sizes=[size]*len(names)
54
+ token=uuid.uuid4().hex if gap is not None else None
55
+ for i,h in enumerate(collection):
56
+ h._annotation_name_alignment=alignment
57
+ if style and isinstance(h,SimpleAnnotation):h._simple_gp={**getattr(h,'_simple_gp',{}),**style}
58
+ size=sizes[i] if sizes[i] is not None else simple_anno_size if isinstance(h,SimpleAnnotation) else None
59
+ if size is not None:
60
+ if not np.isscalar(size) or not np.isfinite(size) or size<=0:raise ValueError('annotation sizes must be positive finite mm')
61
+ h.height=None;h._fixed_height_mm=float(size)
62
+ if labels[i] is not None:h._annotation_label=str(labels[i])
63
+ if sides[i] is not None:
64
+ if sides[i] not in (('top','bottom') if row else ('left','right')):raise ValueError('annotation name side conflicts with which orientation')
65
+ h._annotation_name_side=sides[i]
66
+ if not isinstance(visibility[i],(bool,np.bool_)):raise TypeError('show_annotation_name values must be boolean')
67
+ h._show_annotation_name=bool(visibility[i])
68
+ if token is not None:
69
+ h._annotation_collection=token;h._annotation_collection_index=i
70
+ if i<len(gaps):h._annotation_gap_after_mm=float(gaps[i])
71
+
72
+
73
+ def between(p,first,second):
74
+ if (getattr(first,'_annotation_collection',None) is not None and
75
+ first._annotation_collection==getattr(second,'_annotation_collection',None) and
76
+ first._annotation_collection_index+1==second._annotation_collection_index):
77
+ return p._appearance.mm(first._annotation_gap_after_mm)
78
+ return p._annot_gap_px
79
+
80
+
81
+ def ordered(p,tracks,backwards=False):
82
+ items=list(reversed(tracks)) if backwards else list(tracks)
83
+ for i,h in enumerate(items):
84
+ gap=p._annot_gap_px
85
+ if i+1<len(items):gap=between(p,items[i+1],h) if backwards else between(p,h,items[i+1])
86
+ yield h,gap
87
+
88
+
89
+ def thickness(p,tracks):
90
+ total=0.
91
+ for i,h in enumerate(tracks):
92
+ n=getattr(h,'n_tracks',len(h.df.columns) if h.df is not None else 1)
93
+ total+=n*p._annot_height(h)+max(0,n-1)*p._annot_gap_px
94
+ if i:total+=between(p,tracks[i-1],h)
95
+ return total
96
+
97
+
98
+ def draw(p,f,tracks,start_x,start_y,pixel_size,total_items,direction):
99
+ backwards=direction in ('up','left');vertical=direction in ('left','right')
100
+ cursor=start_x if vertical else start_y
101
+ for h,gap in ordered(p,tracks,backwards):
102
+ p._draw_annotations(f,[h],cursor if vertical else start_x,start_y if vertical else cursor,pixel_size,total_items,direction)
103
+ n=getattr(h,'n_tracks',len(h.df.columns) if h.df is not None else 1)
104
+ cursor+=(-1 if backwards else 1)*(n*p._annot_height(h)+max(0,n-1)*p._annot_gap_px+gap)
@@ -0,0 +1,174 @@
1
+ """Measured annotation names shared by numeric and simple tracks."""
2
+ from math import radians,cos,sin
3
+ from .style import text_width
4
+ from .graphics import gp_value,color,font_face
5
+
6
+
7
+ def name_side(track):
8
+ from .annotation import SimpleAnnotation
9
+ if track.side in ('left','right'):
10
+ default=track.side if isinstance(track,SimpleAnnotation) else 'top'
11
+ else:default='right'
12
+ return getattr(track,'_annotation_name_side',default)
13
+
14
+
15
+ def name_rotation(track):
16
+ return float(getattr(track,'_annotation_name_rot',-90 if name_side(track) in ('left','right') and track.side in ('left','right') else 0))
17
+
18
+
19
+ def name_style(track,p):
20
+ gp=getattr(track,'_annotation_name_gp',{})
21
+ size=(p._appearance.pt(float(gp_value(gp,'fontsize',0,12))) if 'fontsize' in gp or track.fontsize is None else float(track.fontsize))
22
+ rgb=color(gp_value(gp,'col',0,'black'))
23
+ return size,rgb,font_face(gp_value(gp,'fontface',0,'plain'))[0]
24
+
25
+
26
+ def name_family(track):
27
+ family=gp_value(getattr(track,'_annotation_name_gp',{}),'fontfamily',0)
28
+ if family is None:return None
29
+ from .style import resolved_font_family
30
+ return resolved_font_family(family)
31
+
32
+
33
+ def name_distance(track,p):
34
+ """Distance from the shared item boundary, including numeric axis clearance.
35
+
36
+ R aligns visible non-simple names separately on each name side. Resolve the
37
+ effective distance at layout time because native axis padding depends on DPI,
38
+ fonts and current data. Simple multi-band tracks keep their own name positions.
39
+ """
40
+ from .annotation import SimpleAnnotation
41
+ def side(h):
42
+ return name_side(h)
43
+ def distance(h):
44
+ return p._appearance.mm(float(getattr(h,'_annotation_name_offset',1)))+getattr(h,'axis_padding',lambda p:{})(p).get(side(h),0)
45
+ result=distance(track)
46
+ token=getattr(track,'_annotation_name_alignment',None)
47
+ if token is None or isinstance(track,SimpleAnnotation):return result
48
+ for peer in getattr(p,track.side+'_annotations',[]):
49
+ label=getattr(peer,'_annotation_label',peer.label)
50
+ if (getattr(peer,'_annotation_name_alignment',None)==token and
51
+ not isinstance(peer,SimpleAnnotation) and
52
+ getattr(peer,'_show_annotation_name',True) and label is not None and str(label) and
53
+ side(peer)==side(track)):
54
+ result=max(result,distance(peer))
55
+ return result
56
+
57
+
58
+ def name_extent(track,p,label=None):
59
+ if not getattr(track,'_show_annotation_name',True):return 0
60
+ label=getattr(track,'_annotation_label',track.label if label is None else label)
61
+ if label is None or not str(label):return 0
62
+ size,_,bold=name_style(track,p)
63
+ vertical=track.side in ('left','right')
64
+ if vertical and name_side(track) in ('left','right'):return 0
65
+ angle=name_rotation(track)
66
+ italic=font_face(gp_value(getattr(track,'_annotation_name_gp',{}),'fontface',0,'plain'))[1]
67
+ width=text_width(label,size,bold,family=name_family(track) or p._appearance.font_family,italic=italic)
68
+ theta=radians(angle)
69
+ extent=abs(sin(theta))*width+abs(cos(theta))*size if vertical else abs(cos(theta))*width+abs(sin(theta))*size
70
+ return extent+name_distance(track,p)+size*.5
71
+
72
+
73
+ def name_geometry(track,p,start,end,cross,height,vertical,label=None):
74
+ if not getattr(track,'_show_annotation_name',True):return None
75
+ label=getattr(track,'_annotation_label',track.label if label is None else label)
76
+ if label is None or not str(label):return None
77
+ size,rgb,bold=name_style(track,p)
78
+ offset=name_distance(track,p)
79
+ side=name_side(track)
80
+ if vertical:
81
+ rotation=name_rotation(track)
82
+ if side in ('left','right'):
83
+ width=text_width(label,size,bold,family=name_family(track) or p._appearance.font_family)
84
+ theta=radians(rotation);half=(abs(cos(theta))*width+abs(sin(theta))*size)/2
85
+ x=cross-offset-half if side=='left' else cross+height+offset+half
86
+ y=(start+end)/2;anchor='middle'
87
+ else:
88
+ x=cross+height/2;y=start-offset if side=='top' else end+offset
89
+ anchor='start' if side=='top' else 'end'
90
+ if rotation==0:
91
+ anchor='middle';y+=-size/2 if side=='top' else size/2
92
+ else:
93
+ x=start-offset if side=='left' else end+offset;y=cross+height/2
94
+ rotation=float(getattr(track,'_annotation_name_rot',0));anchor='end' if side=='left' else 'start'
95
+ italic=font_face(gp_value(getattr(track,'_annotation_name_gp',{}),'fontface',0,'plain'))[1]
96
+ dx,dy=getattr(p,'_annotation_name_shifts',{}).get((id(track),str(label)),(0.,0.))
97
+ return x+dx,y+dy,str(label),size,anchor,bold,rotation,rgb,italic
98
+
99
+
100
+ def draw_name(track,f,p,start,end,cross,height,vertical,label=None):
101
+ geometry=name_geometry(track,p,start,end,cross,height,vertical,label)
102
+ if geometry is None:return
103
+ from .appearance import _text
104
+ x,y,label,size,anchor,bold,rotation,rgb,italic=geometry
105
+ _text(f,x,y,label,size,anchor,bold=bold,rotation=rotation or None,color=rgb,italic=italic,family=name_family(track))
106
+
107
+
108
+ def figure_name_bounds(p,body_width,body_height,gap):
109
+ """Reserve actual glyph envelopes and keep corner names clear of axes."""
110
+ from .annotation import SimpleAnnotation
111
+ from .annotation_layout import ordered
112
+ from .name_layout import envelope,union
113
+ p._annotation_name_shifts={}
114
+ records=[];axis_boxes=[];panels=[]
115
+ for side in ('top','bottom','left','right'):
116
+ vertical=side in ('left','right');backwards=side in ('top','left')
117
+ cursor=-gap if backwards else body_width+gap if vertical else body_height+gap
118
+ if vertical:cursor+=(-1 if backwards else 1)*getattr(p,'_annotation_offsets',{}).get(side,0)
119
+ for track,next_gap in ordered(p,getattr(p,side+'_annotations'),backwards):
120
+ height=p._annot_height(track)
121
+ labels=list(track.df.columns) if isinstance(track,SimpleAnnotation) and track.df is not None else [track.label]
122
+ if backwards:labels=labels[::-1]
123
+ for label in labels:
124
+ near=cursor-height if backwards else cursor
125
+ geometry=name_geometry(track,p,0,body_height if vertical else body_width,near,height,vertical,label)
126
+ if geometry is not None:
127
+ x,y,label,size,anchor,bold,rotation,_,italic=geometry
128
+ node=dict(x=x,y=y,text=label,size=size,anchor=anchor,bold=bold,rotation=rotation,italic=italic,family=name_family(track) or p._appearance.font_family)
129
+ records.append((track,str(label),vertical,node))
130
+ panel=(near,0,near+height,body_height) if vertical else (0,near,body_width,near+height)
131
+ panels.append((track,panel))
132
+ for axis_side,padding in getattr(track,'axis_padding',lambda p:{})(p).items():
133
+ x0,y0,x1,y1=panel
134
+ if axis_side=='top':box=(x0,y0-padding,x1,y0)
135
+ elif axis_side=='bottom':box=(x0,y1,x1,y1+padding)
136
+ elif axis_side=='left':box=(x0-padding,y0,x0,y1)
137
+ else:box=(x1,y0,x1+padding,y1)
138
+ axis_boxes.append(box)
139
+ cursor+=(-1 if backwards else 1)*(height+p._annot_gap_px)
140
+ cursor+=(-1 if backwards else 1)*(next_gap-p._annot_gap_px)
141
+ def intersects(a,b):return min(a[2],b[2])>max(a[0],b[0]) and min(a[3],b[3])>max(a[1],b[1])
142
+ for track,label,vertical,node in records:
143
+ box=envelope(node,p._appearance.font_family)
144
+ side=name_side(track)
145
+ # Matrix simple tracks own several bands; sibling bands also obscure names.
146
+ obstacles=[b for _,b in panels] if vertical and side in ('left','right') else []
147
+ obstacles+=axis_boxes
148
+ if vertical and side in ('left','right'):
149
+ obstacles+=[envelope(peer,p._appearance.font_family) for owner,other,_,peer in records if peer is not node]
150
+ for _ in range(len(obstacles)+1):
151
+ collisions=[b for b in obstacles if intersects(box,b)]
152
+ if not collisions or side not in ('left','right'):break
153
+ dx=(min(b[0] for b in collisions)-gap-box[2]) if side=='left' else (max(b[2] for b in collisions)+gap-box[0])
154
+ node['x']+=dx
155
+ old_dx,dy=p._annotation_name_shifts.get((id(track),label),(0.,0.))
156
+ p._annotation_name_shifts[(id(track),label)]=(old_dx+dx,dy)
157
+ box=envelope(node,p._appearance.font_family)
158
+ # Adjacent row plots can be narrower than their upright titles. Stagger
159
+ # only unaligned titles; explicit collection alignment retains precedence.
160
+ for track,label,vertical,node in records:
161
+ side=name_side(track)
162
+ if not vertical or side not in ('top','bottom') or node['rotation']!=0 or getattr(track,'_annotation_name_alignment',None):continue
163
+ box=envelope(node,p._appearance.font_family)
164
+ others=[envelope(peer,p._appearance.font_family) for owner,other,_,peer in records if peer is not node]
165
+ for _ in range(len(records)+1):
166
+ collisions=[b for b in others+axis_boxes if intersects(box,b)]
167
+ if not collisions:break
168
+ dy=min(b[1] for b in collisions)-gap-box[3] if side=='top' else max(b[3] for b in collisions)+gap-box[1]
169
+ node['y']+=dy
170
+ dx,old_dy=p._annotation_name_shifts.get((id(track),label),(0.,0.))
171
+ p._annotation_name_shifts[(id(track),label)]=(dx,old_dy+dy)
172
+ box=envelope(node,p._appearance.font_family)
173
+ boxes=[envelope(node,p._appearance.font_family) for _,_,_,node in records]
174
+ return union(boxes) if boxes else None
@@ -0,0 +1,199 @@
1
+ """Explicit, copying annotation operations over the native renderer.
2
+
3
+ Python item indices are zero-based. Operations preserve source IDs and style IDs;
4
+ R S4 replacement/viewport methods become ordinary functions returning new objects.
5
+ """
6
+ import copy
7
+ import numpy as np
8
+ import pandas as pd
9
+ from .annotation import AnnotationBase
10
+
11
+
12
+ def _collection(object):
13
+ from .api import HeatmapAnnotation
14
+ if isinstance(object,HeatmapAnnotation):return object
15
+ if isinstance(object,AnnotationBase):
16
+ result=HeatmapAnnotation(which='row' if object.side in ('left','right') else 'column')
17
+ result.append(object);return result
18
+ raise TypeError('expected an annotation or HeatmapAnnotation')
19
+
20
+
21
+ def _clone(object):
22
+ result=copy.deepcopy(object)
23
+ # Pandas deep copies do not recursively copy object-valued cells.
24
+ for h in _collection(result):
25
+ if h.df is not None:h.df=h.df.map(copy.deepcopy)
26
+ return result
27
+
28
+
29
+ def _bands(h):return getattr(h,'n_tracks',len(h.df.columns) if h.df is not None else 1)
30
+
31
+
32
+ def get_annotation_names(object):return [str(h.label if h.label is not None else f'Annotation {i+1}') for i,h in enumerate(_collection(object))]
33
+
34
+
35
+ def get_annotation(object,name):
36
+ collection=_collection(object);names=get_annotation_names(collection)
37
+ if names.count(str(name))!=1:raise ValueError('annotation name must identify exactly one track')
38
+ return _clone(collection[names.index(str(name))])
39
+
40
+
41
+ def nobs(object):
42
+ counts={len(h.df) for h in _collection(object) if h.df is not None}
43
+ if len(counts)>1:raise ValueError('annotation tracks have different observation lengths')
44
+ return next(iter(counts)) if counts else None
45
+
46
+
47
+ def _indices(selector,index):
48
+ if selector is None:return np.arange(len(index))
49
+ if isinstance(selector,slice):return np.arange(len(index))[selector]
50
+ raw=np.atleast_1d(selector)
51
+ if raw.dtype.kind=='b':
52
+ if len(raw)!=len(index):raise IndexError('boolean selection length must match observations')
53
+ ids=np.flatnonzero(raw)
54
+ elif raw.dtype.kind in 'iu':ids=raw.astype(int)
55
+ else:
56
+ lookup={str(value):i for i,value in enumerate(index)}
57
+ try:ids=np.array([lookup[str(value)] for value in raw],dtype=int)
58
+ except KeyError as e:raise KeyError(f'unknown annotation identifier {e.args[0]}') from e
59
+ if np.any(ids<0) or np.any(ids>=len(index)):raise IndexError('annotation index out of bounds')
60
+ if len(set(ids))!=len(ids):raise ValueError('duplicate annotation observations are not supported')
61
+ return ids
62
+
63
+
64
+ def subset_annotation(object,items=None,tracks=None):
65
+ from .api import HeatmapAnnotation
66
+ source=_collection(object);names=get_annotation_names(source)
67
+ ids=_indices(tracks,pd.Index(names)) if tracks is not None else np.arange(len(source))
68
+ result=HeatmapAnnotation(which=source.which)
69
+ for i in ids:
70
+ h=_clone(source[int(i)])
71
+ if items is not None:
72
+ if h.df is None:raise ValueError('cannot subset observations of an annotation without item data')
73
+ selected=_indices(items,h.df.index);h.df=h.df.iloc[selected].copy()
74
+ if getattr(h,'_graphical_ids',None) is not None:
75
+ h._graphical_ids=h._graphical_ids.reindex(h.df.index.map(str)).copy()
76
+ result.append(h)
77
+ return result if isinstance(object,HeatmapAnnotation) else result[0]
78
+
79
+
80
+ def rename_annotations(object,names):
81
+ from .api import HeatmapAnnotation
82
+ result=_clone(object);collection=_collection(result);old=get_annotation_names(collection)
83
+ if isinstance(names,dict):
84
+ if set(names)-set(old):raise KeyError('unknown annotation names')
85
+ new=[str(names.get(name,name)) for name in old]
86
+ else:new=list(map(str,names))
87
+ if len(new)!=len(old) or len(set(new))!=len(new):raise ValueError('provide unique names for every selected annotation')
88
+ for h,before,after in zip(collection,old,new):
89
+ h.label=after
90
+ if h.df is not None and h.df.shape[1]==1:
91
+ column=h.df.columns[0];h.df=h.df.rename(columns={column:after})
92
+ if hasattr(h,'color_mappings'):h.color_mappings={after:h.color_mappings[column]}
93
+ return result
94
+
95
+
96
+ def concat_annotations(*objects):
97
+ from .api import HeatmapAnnotation
98
+ collections=[_collection(o) for o in objects]
99
+ if not collections:raise ValueError('provide annotations to concatenate')
100
+ if len({c.which for c in collections})!=1:raise ValueError('annotation orientation must agree')
101
+ names=[name for c in collections for name in get_annotation_names(c)]
102
+ if len(set(names))!=len(names):raise ValueError('duplicate annotation names')
103
+ counts={nobs(c) for c in collections}-{None}
104
+ if len(counts)>1:raise ValueError('annotation observation lengths must agree')
105
+ indexed=[h.df.index.map(str) for c in collections for h in c if h.df is not None and not getattr(h,'_positional',False)]
106
+ if indexed and any(set(index)!=set(indexed[0]) for index in indexed):raise ValueError('annotation identifiers must agree')
107
+ result=HeatmapAnnotation(which=collections[0].which)
108
+ for c in collections:
109
+ for source in c:
110
+ h=_clone(source)
111
+ if indexed and h.df is not None and getattr(h,'_positional',False):h._bind_item_ids(indexed[0]);h._positional=False
112
+ result.append(h)
113
+ return result
114
+
115
+
116
+ def attach_annotation(object,annotation,*,side=None):
117
+ from .renderer import ClusterMapPlotter
118
+ if not isinstance(object,ClusterMapPlotter):raise TypeError('attach_annotation currently takes one Heatmap')
119
+ collection=_collection(annotation);side=side or ('right' if collection.which=='row' else 'top')
120
+ if side not in ('left','right','top','bottom') or (side in ('left','right'))!=(collection.which=='row'):raise ValueError('annotation orientation conflicts with side')
121
+ result=copy.copy(object)
122
+ # Restore stable source data if the input has already been drawn/reordered.
123
+ existing=[]
124
+ for i,source in enumerate(object.all_annotations):
125
+ h=_clone(source)
126
+ snapshots=getattr(object,'_annotation_sources',None)
127
+ if snapshots is not None and snapshots[i] is not None:h.df=snapshots[i].map(copy.deepcopy)
128
+ existing.append(h)
129
+ axis=object.df.index if collection.which=='row' else object.df.columns
130
+ # Heatmap.df already includes its explicit permutation. Match constructor
131
+ # attachment by binding new positional data to the pre-permutation input IDs.
132
+ permutation=getattr(object,'_input_row_order' if collection.which=='row' else '_input_col_order',None)
133
+ if permutation is not None and len(permutation)==len(axis) and getattr(object,'_input_applied_to_frame',True):axis=axis[np.argsort(permutation)]
134
+ for source in collection:
135
+ h=_clone(source);h.side=side
136
+ if h.df is not None:
137
+ if len(h.df)!=len(axis):raise ValueError('annotation observations must match heatmap axis length')
138
+ if getattr(h,'_positional',False):h._bind_item_ids(axis);h._positional=False
139
+ elif set(h.df.index.map(str))!=set(axis.map(str)):raise ValueError('annotation identifiers must match heatmap axis')
140
+ existing.append(h)
141
+ result.all_annotations=existing;result._annotation_sources=None
142
+ for direction in ('top','bottom','left','right'):setattr(result,direction+'_annotations',[h for h in existing if h.side==direction])
143
+ return result
144
+
145
+
146
+ def draw_annotation(object,output_path=None,*,items=None,dpi=300,length_mm=180):
147
+ collection=_collection(subset_annotation(object,items=items) if items is not None else object)
148
+ if output_path is not None:return collection.save(output_path,dpi=dpi,length_mm=length_mm)
149
+ return collection._as_plot(dpi=dpi,length_mm=length_mm)._render_svg()[0]
150
+
151
+
152
+ def annotation_size(object,*,dpi=300,length_mm=180):
153
+ p=_collection(object)._as_plot(dpi=dpi,length_mm=length_mm);p._compute_layout()
154
+ thickness=sum(_bands(h)*p._annot_height(h) for h in p.all_annotations)*25.4/p.dpi
155
+ row=_collection(object).which=='row'
156
+ return {'width_mm':thickness if row else length_mm,'height_mm':length_mm if row else thickness}
157
+
158
+
159
+ def resize_annotation(object,*,size):
160
+ if not np.isscalar(size) or not np.isfinite(size) or size<=0:raise ValueError('annotation size must be finite positive mm')
161
+ result=_clone(object);collection=_collection(result)
162
+ if not collection:raise ValueError('annotation collection is empty')
163
+ for h in collection:
164
+ h.height=None;h._fixed_height_mm=float(size)/sum(_bands(t) for t in collection)
165
+ return result
166
+
167
+
168
+ def get_color_mapping_list(object):
169
+ from .style import ColorMapping
170
+ from matplotlib.colors import to_hex
171
+ p=_collection(object)._as_plot(dpi=96);p._compute_layout();result={}
172
+ for name,h in zip(get_annotation_names(object),p.all_annotations):
173
+ if hasattr(h,'color_mappings'):result[name]=copy.deepcopy(h.color_mappings)
174
+ elif hasattr(h,'colors') and h.df is not None:
175
+ maps={}
176
+ for col in h.df:
177
+ values=list(dict.fromkeys(h.df[col].dropna().astype(str)))
178
+ rgb=p._map_colors(np.asarray(values),h.colors)
179
+ if values:maps[str(col)]=ColorMapping(colors={v:to_hex(c[::-1]/255) for v,c in zip(values,np.asarray(rgb))},na_col=getattr(h,'na_col','#BEBEBE'))
180
+ result[name]=maps
181
+ return result
182
+
183
+
184
+ def get_legend_param_list(object):return {name:copy.deepcopy(getattr(h,'_annotation_legend_param',{})) for name,h in zip(get_annotation_names(object),_collection(object))}
185
+
186
+
187
+ def draw_annotation_legend(object,output_path=None,*,dpi=300,**kwargs):
188
+ from .legends import PackedLegends
189
+ from .renderer import ClusterMapPlotter
190
+ p=object if isinstance(object,ClusterMapPlotter) else _collection(object)._as_plot(dpi=dpi)
191
+ p._compute_layout()
192
+ legends=[lg for kind,lg,side in p._last_layout['legend_objects'] if kind=='annotation']
193
+ if not legends:return None
194
+ scene=PackedLegends(*legends,**kwargs)
195
+ if output_path is not None:scene.save(output_path,dpi=dpi)
196
+ return scene
197
+
198
+
199
+ __all__=['get_annotation_names','get_annotation','nobs','subset_annotation','rename_annotations','concat_annotations','attach_annotation','draw_annotation','annotation_size','resize_annotation','get_color_mapping_list','get_legend_param_list','draw_annotation_legend']