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/text_boxes.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Measured, Unicode text boxes rendered directly through the native sinks."""
|
|
2
|
+
import math
|
|
3
|
+
import numpy as np
|
|
4
|
+
from PIL import ImageFont
|
|
5
|
+
|
|
6
|
+
from .style import Appearance,font_path,text_width
|
|
7
|
+
from .graphics import validate_gp,gp_value,color,font_face
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _texts(text):
|
|
11
|
+
if text is None:return []
|
|
12
|
+
if isinstance(text,str) or np.isscalar(text):return [str(text)]
|
|
13
|
+
return [str(value) if value is not None else '' for value in text]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _font(gp,i,a):
|
|
17
|
+
size=a.pt(float(gp_value(gp,'fontsize',i,12)))
|
|
18
|
+
family=str(gp_value(gp,'fontfamily',i,a.font_family))
|
|
19
|
+
bold,italic=font_face(gp_value(gp,'fontface',i,'plain'))
|
|
20
|
+
return size,family,bold,italic
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _text_size(text,size,family,bold,italic=False):
|
|
24
|
+
font=ImageFont.truetype(font_path(bold,family,italic),max(1,round(size)))
|
|
25
|
+
lines=str(text).split('\n')
|
|
26
|
+
width=max((font.getlength(line) for line in lines),default=0)
|
|
27
|
+
heights=[font.getbbox(line)[3]-font.getbbox(line)[1] if line else 0 for line in lines]
|
|
28
|
+
height=max(heights,default=0)+max(0,len(lines)-1)*size*1.2
|
|
29
|
+
return width,height
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _convert(value,a,unit):
|
|
33
|
+
if unit=='px':return value
|
|
34
|
+
if unit=='mm':return value/a.dpi*25.4
|
|
35
|
+
if unit=='cm':return value/a.dpi*2.54
|
|
36
|
+
if unit=='pt':return value/a.dpi*72
|
|
37
|
+
if unit in ('in','inches'):return value/a.dpi
|
|
38
|
+
raise ValueError('unit must be mm, cm, pt, px or inches')
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _max_text(text,gp,rot,unit,dpi,axis):
|
|
42
|
+
if not np.isfinite([rot,dpi]).all() or dpi<=0:raise ValueError('rotation and DPI must be finite; DPI must be positive')
|
|
43
|
+
gp=validate_gp(gp,{'fontsize','fontfamily','fontface','col','fill'})
|
|
44
|
+
a=Appearance(dpi);theta=math.radians(rot)
|
|
45
|
+
sizes=[]
|
|
46
|
+
for i,item in enumerate(_texts(text)):
|
|
47
|
+
size,family,bold,italic=_font(gp,i,a)
|
|
48
|
+
w,h=_text_size(item,size,family,bold,italic)
|
|
49
|
+
sizes.append(abs(math.cos(theta))*w+abs(math.sin(theta))*h if axis==0 else abs(math.sin(theta))*w+abs(math.cos(theta))*h)
|
|
50
|
+
return _convert(max(sizes,default=0),a,unit)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def max_text_width(text,gp=None,rot=0,*,unit='mm',dpi=300):return _max_text(text,gp,rot,unit,dpi,0)
|
|
54
|
+
def max_text_height(text,gp=None,rot=0,*,unit='mm',dpi=300):return _max_text(text,gp,rot,unit,dpi,1)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class TextBox:
|
|
58
|
+
"""Flow text segments with physical font sizes and measured backgrounds.
|
|
59
|
+
|
|
60
|
+
``max_width`` is content width in mm; padding/line_space/text_space are
|
|
61
|
+
points. A long unbreakable word can expand the content width, matching R's
|
|
62
|
+
textbox intent. Per-segment colors/font sizes/bold faces are supported.
|
|
63
|
+
Mixed font families in one box and R viewport objects are not supported.
|
|
64
|
+
"""
|
|
65
|
+
def __init__(self,text,*,gp=None,background_gp=None,round_corners=False,r=.1,
|
|
66
|
+
line_space=4,text_space=4,max_width=100,padding=4,
|
|
67
|
+
first_text_from='top',add_new_line=False,word_wrap=False):
|
|
68
|
+
if not np.isfinite([line_space,text_space,max_width,r]).all() or max_width<=0:raise ValueError('max_width must be positive and all sizes finite')
|
|
69
|
+
if min(line_space,text_space,r)<0 or r>.5:raise ValueError('spaces must be nonnegative and r must lie in [0,.5]')
|
|
70
|
+
if first_text_from not in ('top','bottom'):raise ValueError('first_text_from must be top or bottom')
|
|
71
|
+
self.text=_texts(text)
|
|
72
|
+
self.gp=validate_gp(gp,{'col','fontsize','fontface','fontfamily'})
|
|
73
|
+
self.background_gp=validate_gp(background_gp or {'col':'black','fill':None},{'col','fill','lwd'})
|
|
74
|
+
families={str(gp_value(self.gp,'fontfamily',i,'DejaVu Sans')) for i in range(max(1,len(self.text)))}
|
|
75
|
+
if len(families)>1:raise ValueError('a textbox currently requires one fontfamily')
|
|
76
|
+
self.font_family=next(iter(families))
|
|
77
|
+
pads=np.atleast_1d(np.asarray(padding,dtype=float))
|
|
78
|
+
if pads.shape not in ((1,),(2,),(4,)) or not np.isfinite(pads).all() or np.any(pads<0):raise ValueError('padding must have 1,2 or 4 nonnegative point values')
|
|
79
|
+
if len(pads)==1:pads=np.repeat(pads,4)
|
|
80
|
+
elif len(pads)==2:pads=np.array([pads[0],pads[1],pads[0],pads[1]])
|
|
81
|
+
self.padding=pads;self.max_width=float(max_width)
|
|
82
|
+
self.line_space=float(line_space);self.text_space=float(text_space)
|
|
83
|
+
self.first_text_from=first_text_from;self.add_new_line=bool(add_new_line);self.word_wrap=bool(word_wrap)
|
|
84
|
+
self.round_corners=bool(round_corners);self.r=float(r)
|
|
85
|
+
|
|
86
|
+
def _layout(self,a):
|
|
87
|
+
segments=[]
|
|
88
|
+
for i,text in enumerate(self.text):
|
|
89
|
+
size,family,bold,italic=_font(self.gp,i,a)
|
|
90
|
+
# Explicit newlines are retained even when word wrapping is off.
|
|
91
|
+
paragraphs=text.split('\n')
|
|
92
|
+
for paragraph_id,paragraph in enumerate(paragraphs):
|
|
93
|
+
words=paragraph.split() if self.word_wrap else [paragraph]
|
|
94
|
+
if not words:words=['']
|
|
95
|
+
for word in words:
|
|
96
|
+
segments.append([word,size,family,bold,italic,color(gp_value(self.gp,'col',i,'black')),False])
|
|
97
|
+
if paragraph_id<len(paragraphs)-1:segments[-1][-1]=True
|
|
98
|
+
if self.add_new_line and segments:segments[-1][-1]=True
|
|
99
|
+
width_limit=max([a.mm(self.max_width)]+[text_width(s[0],s[1],s[3],s[2],s[4]) for s in segments])
|
|
100
|
+
gap=a.pt(self.text_space);line_gap=a.pt(self.line_space)
|
|
101
|
+
lines=[];line=[];width=0
|
|
102
|
+
for segment in segments:
|
|
103
|
+
w=text_width(segment[0],segment[1],segment[3],segment[2],segment[4])
|
|
104
|
+
if line and (width+gap+w>width_limit or line[-1][0][-1]):
|
|
105
|
+
lines.append((line,width,max(node[0][1] for node in line)));line=[];width=0
|
|
106
|
+
x=width+(gap if line else 0)
|
|
107
|
+
line.append((segment,x,w));width=x+w
|
|
108
|
+
if line:lines.append((line,width,max(node[0][1] for node in line)))
|
|
109
|
+
content_w=max((w for _,w,_ in lines),default=0)
|
|
110
|
+
content_h=sum(h for _,_,h in lines)+max(0,len(lines)-1)*line_gap
|
|
111
|
+
bottom,left,top,right=[a.pt(v) for v in self.padding]
|
|
112
|
+
nodes=[];cursor=0
|
|
113
|
+
for line,_,height in lines:
|
|
114
|
+
y=cursor+height/2
|
|
115
|
+
if self.first_text_from=='bottom':y=content_h-y
|
|
116
|
+
for segment,x,_ in line:
|
|
117
|
+
word,size,family,bold,italic,rgb,_=segment
|
|
118
|
+
nodes.append((left+x,top+y,word,size,family,bold,italic,rgb))
|
|
119
|
+
cursor+=height+line_gap
|
|
120
|
+
return content_w+left+right,content_h+top+bottom,nodes
|
|
121
|
+
|
|
122
|
+
def measure(self,*,dpi=300,unit='mm'):
|
|
123
|
+
a=Appearance(dpi,font_family=self.font_family);w,h,_=self._layout(a)
|
|
124
|
+
return _convert(w,a,unit),_convert(h,a,unit)
|
|
125
|
+
|
|
126
|
+
def draw(self,sink,x=0,y=0,*,dpi=300):
|
|
127
|
+
from .appearance import _text
|
|
128
|
+
a=Appearance(dpi,font_family=self.font_family);w,h,nodes=self._layout(a)
|
|
129
|
+
fill=color(gp_value(self.background_gp,'fill',0));stroke=color(gp_value(self.background_gp,'col',0,'black'))
|
|
130
|
+
linewidth=a.pt(float(gp_value(self.background_gp,'lwd',0,.75)))
|
|
131
|
+
if self.round_corners and self.r:
|
|
132
|
+
radius=min(w,h)*self.r;points=[]
|
|
133
|
+
for cx,cy,start in ((x+w-radius,y+radius,-90),(x+w-radius,y+h-radius,0),(x+radius,y+h-radius,90),(x+radius,y+radius,180)):
|
|
134
|
+
points.extend((cx+radius*np.cos(t),cy+radius*np.sin(t)) for t in np.linspace(np.deg2rad(start),np.deg2rad(start+90),9))
|
|
135
|
+
pts=' '.join(f'{xx},{yy}' for xx,yy in points)
|
|
136
|
+
sink.write(f'<polygon points="{pts}" fill="{fill}" stroke="{stroke}" stroke-width="{linewidth}"/>')
|
|
137
|
+
else:sink.write(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" fill="{fill}" stroke="{stroke}" stroke-width="{linewidth}"/>')
|
|
138
|
+
for xx,yy,text,size,family,bold,italic,rgb in nodes:_text(sink,x+xx,y+yy,text,size,bold=bold,italic=italic,color=rgb)
|
|
139
|
+
return w,h
|
|
140
|
+
|
|
141
|
+
def save(self,path,fmt=None,dpi=300):
|
|
142
|
+
from .pdf_renderer import PdfSink
|
|
143
|
+
from .api import _save_ops
|
|
144
|
+
if not np.isfinite(dpi) or dpi<=0:raise ValueError('DPI must be positive and finite')
|
|
145
|
+
w,h=self.measure(dpi=dpi,unit='px');pad=max(2,dpi/72)
|
|
146
|
+
if (w+2*pad)*(h+2*pad)>20_000_000 or max(w,h)+2*pad>10_000:raise ValueError('textbox exceeds canvas budget; reduce DPI/text size or split the text')
|
|
147
|
+
sink=PdfSink();self.draw(sink,pad,pad,dpi=dpi)
|
|
148
|
+
_save_ops(sink,math.ceil(w+2*pad),math.ceil(h+2*pad),dpi,self.font_family,path,fmt)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def textbox_grob(text,**kwargs):return TextBox(text,**kwargs)
|
|
152
|
+
|
|
153
|
+
def grid_textbox(sink,text,*,x=0,y=0,dpi=300,**kwargs):
|
|
154
|
+
"""Draw at explicit top-left pixel coordinates instead of R viewport state."""
|
|
155
|
+
box=TextBox(text,**kwargs);box.draw(sink,x,y,dpi=dpi);return box
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
__all__=['TextBox','textbox_grob','grid_textbox','max_text_width','max_text_height']
|
tilesig/text_layout.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Deterministic one-dimensional label alignment without a plotting backend."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def smartAlign2(start,end=None,range=None,plot=False):
|
|
7
|
+
"""Align intervals within a range, retaining lengths and input identities.
|
|
8
|
+
|
|
9
|
+
A bounded isotonic fit minimizes squared displacement when nonoverlap is
|
|
10
|
+
feasible. Overfull ranges retain sizes and distribute centers as in R's
|
|
11
|
+
documented fallback, with deterministic tie ordering. Returns start/end
|
|
12
|
+
columns. R's optional diagnostic plotting is not an implicit side effect.
|
|
13
|
+
"""
|
|
14
|
+
if plot:raise ValueError('plot=True is unsupported; inspect the returned start/end coordinates')
|
|
15
|
+
if end is None:
|
|
16
|
+
data=np.asarray(start,dtype=float)
|
|
17
|
+
if data.ndim!=2 or data.shape[1]!=2:raise ValueError('provide start/end vectors or a two-column matrix')
|
|
18
|
+
start,end=data[:,0],data[:,1]
|
|
19
|
+
start=np.atleast_1d(np.asarray(start,dtype=float));end=np.atleast_1d(np.asarray(end,dtype=float))
|
|
20
|
+
if start.ndim!=1 or start.shape!=end.shape or not np.isfinite(start).all() or not np.isfinite(end).all() or np.any(end<start):raise ValueError('start/end must be equally sized finite vectors with end>=start')
|
|
21
|
+
if not len(start):return pd.DataFrame({'start':[],'end':[]})
|
|
22
|
+
limits=np.asarray([start.min(),end.max()] if range is None else range,dtype=float)
|
|
23
|
+
if limits.shape!=(2,) or not np.isfinite(limits).all() or limits[1]<limits[0]:raise ValueError('range must be an increasing finite pair')
|
|
24
|
+
target=(start+end)/2;order=np.argsort(target,kind='stable')
|
|
25
|
+
sizes=(end-start)[order];targets=target[order];span=limits[1]-limits[0]
|
|
26
|
+
offsets=np.r_[0.,np.cumsum((sizes[:-1]+sizes[1:])/2)]
|
|
27
|
+
if sizes.sum()>span:
|
|
28
|
+
first=limits[0]+sizes[0]/2;last=limits[1]-sizes[-1]/2
|
|
29
|
+
centers=first+offsets/offsets[-1]*(last-first) if len(offsets)>1 and offsets[-1] else np.full(len(start),(limits[0]+limits[1])/2)
|
|
30
|
+
else:
|
|
31
|
+
means=[];weights=[]
|
|
32
|
+
for value in targets-offsets:
|
|
33
|
+
means.append(float(value));weights.append(1)
|
|
34
|
+
while len(means)>1 and means[-2]>means[-1]:
|
|
35
|
+
weight=weights[-2]+weights[-1]
|
|
36
|
+
average=(means[-2]*weights[-2]+means[-1]*weights[-1])/weight
|
|
37
|
+
means[-2:]=[average];weights[-2:]=[weight]
|
|
38
|
+
z=np.repeat(means,weights)
|
|
39
|
+
low=limits[0]+sizes[0]/2;high=limits[1]-sizes[-1]/2-offsets[-1]
|
|
40
|
+
centers=np.clip(z,low,high)+offsets
|
|
41
|
+
aligned=np.empty((len(start),2));aligned[order,0]=centers-sizes/2;aligned[order,1]=centers+sizes/2
|
|
42
|
+
return pd.DataFrame(aligned,columns=['start','end'])
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
__all__=['smartAlign2']
|
tilesig/text_styles.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Physical text styling bound to original IDs, without a plotting backend."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from .graphics import validate_gp,gp_value,font_face,color,_vector
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def initialize(p):
|
|
7
|
+
p._name_gp={};p._title_gp={}
|
|
8
|
+
for axis in ('row','column'):
|
|
9
|
+
p._name_gp[axis]=validate_gp(p._visual_options.get(axis+'_names_gp'),{'col','fontsize','fontface','fontfamily'})
|
|
10
|
+
gp=p._name_gp[axis]
|
|
11
|
+
if 'fontfamily' in gp:
|
|
12
|
+
from .style import resolved_font_family
|
|
13
|
+
import warnings
|
|
14
|
+
value=gp['fontfamily'];values=list(value) if _vector(value,'fontfamily') else [value]
|
|
15
|
+
if not values or any(not isinstance(v,str) or not v.strip() for v in values):
|
|
16
|
+
raise ValueError('gp fontfamily must contain nonempty family names')
|
|
17
|
+
resolved=[]
|
|
18
|
+
for family in values:
|
|
19
|
+
actual=resolved_font_family(family)
|
|
20
|
+
if actual.casefold()!=family.casefold():
|
|
21
|
+
warnings.warn(f'font family {family!r} resolves to {actual!r}; using the resolved family for measurements and all exports',UserWarning,stacklevel=2)
|
|
22
|
+
resolved.append(actual)
|
|
23
|
+
gp['fontfamily']=resolved if _vector(value,'fontfamily') else resolved[0]
|
|
24
|
+
raw=dict(p._visual_options.get(axis+'_title_gp') or {})
|
|
25
|
+
border=raw.pop('border',None)
|
|
26
|
+
gp=validate_gp(raw,{'col','fontsize','fontface','fontfamily','fill','lwd'})
|
|
27
|
+
if border is not None:gp['border']=validate_gp({'col':border},{'col'})['col']
|
|
28
|
+
p._title_gp[axis]=gp
|
|
29
|
+
side=p._visual_options.get(axis+'_title_side','left' if axis=='row' else 'top')
|
|
30
|
+
if side not in (('left','right') if axis=='row' else ('top','bottom')):raise ValueError('invalid title side')
|
|
31
|
+
rot=p._visual_options.get(axis+'_title_rot')
|
|
32
|
+
if rot is not None and not np.isfinite(float(rot)):raise ValueError('title rotation must be finite')
|
|
33
|
+
limit=p._visual_options.get('row_names_max_width_mm' if axis=='row' else 'column_names_max_height_mm',60)
|
|
34
|
+
if not np.isscalar(limit) or not np.isfinite(limit) or limit<=0:raise ValueError('name maximum must be positive finite mm')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def bind_name_ids(p):
|
|
38
|
+
positions=dict(getattr(p,'_name_gp_positions',{}))
|
|
39
|
+
for axis,gp in p._name_gp.items():
|
|
40
|
+
if axis in positions or not any(_vector(v,k) and len(v)>1 for k,v in gp.items()):continue
|
|
41
|
+
names=getattr(p,'_name_gp_input_ids',{}).get(axis)
|
|
42
|
+
if names is None:
|
|
43
|
+
# Source metadata precedes explicit permutations; no matrix read.
|
|
44
|
+
source=getattr(p,'_input_source',p.df)
|
|
45
|
+
if axis=='row' and source is p.df and p.df_filter is not None and p.label in p.df.columns:
|
|
46
|
+
# The native filter promotes the label column to the row axis.
|
|
47
|
+
names=p.df[p.label]
|
|
48
|
+
else:names=source.index if axis=='row' else source.columns
|
|
49
|
+
positions[axis]={str(name):i for i,name in enumerate(names)}
|
|
50
|
+
p._name_gp_positions=positions
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def transform_name_ids(p,row_map=None,column_map=None,subset=False):
|
|
54
|
+
positions={}
|
|
55
|
+
for axis,by_id in getattr(p,'_name_gp_positions',{}).items():
|
|
56
|
+
if subset:
|
|
57
|
+
names=p.df.index if axis=='row' else p.df.columns
|
|
58
|
+
by_id={str(n):by_id[str(n)] for n in names if str(n) in by_id}
|
|
59
|
+
else:
|
|
60
|
+
mapping=(row_map if axis=='row' else column_map) or {}
|
|
61
|
+
by_id={mapping.get(n,n):i for n,i in by_id.items()}
|
|
62
|
+
positions[axis]=by_id
|
|
63
|
+
p._name_gp_positions=positions
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def name_style(p,axis,name):
|
|
67
|
+
row=axis=='row';gp=p._name_gp[axis]
|
|
68
|
+
i=getattr(p,'_name_gp_positions',{}).get(axis,{}).get(str(name),0)
|
|
69
|
+
size=p.row_fontsize if row else p.col_fontsize
|
|
70
|
+
if p._visual_options.get('row_fontsize' if row else 'col_fontsize') is None and 'fontsize' in gp:
|
|
71
|
+
size=p._appearance.pt(float(gp_value(gp,'fontsize',i)))
|
|
72
|
+
bold,italic=font_face(gp_value(gp,'fontface',i,'plain'))
|
|
73
|
+
style=dict(size=size,color=color(gp_value(gp,'col',i,'black')),bold=bold,italic=italic)
|
|
74
|
+
if 'fontfamily' in gp:style['family']=gp_value(gp,'fontfamily',i)
|
|
75
|
+
return style
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def maximum_fontsize(p,axis):
|
|
79
|
+
row=axis=='row';size=p.row_fontsize if row else p.col_fontsize
|
|
80
|
+
gp=p._name_gp[axis]
|
|
81
|
+
if p._visual_options.get('row_fontsize' if row else 'col_fontsize') is None and 'fontsize' in gp:
|
|
82
|
+
value=gp['fontsize'];size=p._appearance.pt(float(max(value) if _vector(value) else value))
|
|
83
|
+
return size
|
tilesig/titles.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Slice-aware titles measured in the native scene coordinate system."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
from .name_layout import envelope, fit_text
|
|
5
|
+
from .text_boxes import TextBox
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _vector(raw):
|
|
9
|
+
return raw is not None and not isinstance(raw,(str,TextBox)) and not np.isscalar(raw)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _values(p,axis,bounds):
|
|
13
|
+
"""Bind explicit vector titles to item IDs at their first resolved layout."""
|
|
14
|
+
raw=p._visual_options.get(axis+'_title');signature=tuple(repr(vars(v)) if isinstance(v,TextBox) else str(v) for v in raw)
|
|
15
|
+
bindings=getattr(p,'_slice_title_bindings',{})
|
|
16
|
+
stored=bindings.get(axis)
|
|
17
|
+
names=p.row_names if axis=='row' else p.col_names
|
|
18
|
+
if stored is None or stored[0]!=signature:
|
|
19
|
+
if len(signature)!=len(bounds):raise ValueError(f'{axis}_title length must equal the number of slices')
|
|
20
|
+
by_id={str(names[i]):title for title,(begin,end) in zip(raw,bounds) for i in range(begin,end)}
|
|
21
|
+
p._slice_title_bindings={**bindings,axis:(signature,by_id)}
|
|
22
|
+
else:by_id=stored[1]
|
|
23
|
+
values=[]
|
|
24
|
+
for begin,end in bounds:
|
|
25
|
+
try:titles={by_id[str(name)] for name in names[begin:end]}
|
|
26
|
+
except KeyError as e:raise ValueError('slice title identifiers no longer match the heatmap axis') from e
|
|
27
|
+
if len(titles)!=1:raise ValueError('slice contains conflicting original title assignments after regrouping')
|
|
28
|
+
values.append(next(iter(titles)))
|
|
29
|
+
return values
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def bind_slice_titles(p):
|
|
33
|
+
"""Resolve vectors on a private selection copy before its groups change."""
|
|
34
|
+
from .graphics import _vector as gp_vector
|
|
35
|
+
axes=[axis for axis in ('row','column') if _vector(p._visual_options.get(axis+'_title'))
|
|
36
|
+
or any(gp_vector(v,k) for k,v in p._title_gp[axis].items())
|
|
37
|
+
or _vector(p._visual_options.get(axis+'_gap_mm'))]
|
|
38
|
+
if not axes:return
|
|
39
|
+
state=np.random.get_state()
|
|
40
|
+
try:p._compute_clustering()
|
|
41
|
+
finally:np.random.set_state(state)
|
|
42
|
+
for axis in axes:
|
|
43
|
+
row=axis=='row';count=p._matrix_sorted.shape[0 if row else 1]
|
|
44
|
+
bounds=p._get_bounds(count,p.row_breaks if row else p.col_breaks)
|
|
45
|
+
if _vector(p._visual_options.get(axis+'_title')):_values(p,axis,bounds)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def transform_title_ids(p,row_map=None,column_map=None,subset=False):
|
|
49
|
+
if not hasattr(p,'_slice_title_bindings'):return
|
|
50
|
+
result={}
|
|
51
|
+
for axis,(signature,by_id) in p._slice_title_bindings.items():
|
|
52
|
+
if subset:
|
|
53
|
+
selected=p.df.index if axis=='row' else p.df.columns
|
|
54
|
+
by_id={str(k):by_id[str(k)] for k in selected if str(k) in by_id}
|
|
55
|
+
else:
|
|
56
|
+
mapping=(row_map if axis=='row' else column_map) or {}
|
|
57
|
+
by_id={mapping.get(k,k):v for k,v in by_id.items()}
|
|
58
|
+
result[axis]=(signature,by_id)
|
|
59
|
+
p._slice_title_bindings=result
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def title_nodes(p,x,y,width,height,occupied):
|
|
63
|
+
"""Resolve automatic slice names, explicit vectors, or whole-axis titles.
|
|
64
|
+
|
|
65
|
+
None selects automatic titles; an explicit empty string disables them.
|
|
66
|
+
Scalar nonempty titles retain the original Python whole-axis behavior.
|
|
67
|
+
"""
|
|
68
|
+
a=p._appearance;nodes=[];gap=a.mm(1)
|
|
69
|
+
for axis in ('row','column'):
|
|
70
|
+
row=axis=='row';key='row' if row else 'col'
|
|
71
|
+
from .graphics import gp_value,font_face,color
|
|
72
|
+
gp=p._title_gp[axis];size=a.pt(float(gp_value(gp,'fontsize',0,13.2)))
|
|
73
|
+
bold,italic=font_face(gp_value(gp,'fontface',0,'plain'))
|
|
74
|
+
side=p._visual_options.get(axis+'_title_side','left' if row else 'top')
|
|
75
|
+
negative=side in ('left','top');across=0 if row else 1
|
|
76
|
+
rotation=p._visual_options.get(axis+'_title_rot')
|
|
77
|
+
rotation=-(90 if side=='left' else 270 if row else 0) if rotation is None else -float(rotation)
|
|
78
|
+
raw=p._visual_options.get(axis+'_title')
|
|
79
|
+
count=p._matrix_sorted.shape[0 if row else 1]
|
|
80
|
+
breaks=p.row_breaks if row else p.col_breaks
|
|
81
|
+
bounds=p._get_bounds(count,breaks)
|
|
82
|
+
labels=getattr(p,'_'+key+'_cluster_labels',None)
|
|
83
|
+
automatic=raw is None
|
|
84
|
+
if automatic:
|
|
85
|
+
if (not row and p.show_cluster_labels) or labels is None:continue
|
|
86
|
+
if len(bounds)==1 and key not in getattr(p,'_explicit_splits',()):continue
|
|
87
|
+
values=[str(labels[begin]) for begin,end in bounds]
|
|
88
|
+
if not any(values):continue
|
|
89
|
+
elif isinstance(raw,(str,TextBox)) or np.isscalar(raw):
|
|
90
|
+
if not str(raw):continue
|
|
91
|
+
values=[raw if isinstance(raw,TextBox) else str(raw)];bounds=[(0,count)]
|
|
92
|
+
else:
|
|
93
|
+
values=_values(p,axis,bounds)
|
|
94
|
+
group=[]
|
|
95
|
+
for index,(text,(begin,end)) in enumerate(zip(values,bounds)):
|
|
96
|
+
if not text:continue
|
|
97
|
+
size=a.pt(float(gp_value(gp,'fontsize',index,13.2)))
|
|
98
|
+
bold,italic=font_face(gp_value(gp,'fontface',index,'plain'))
|
|
99
|
+
rich=text if isinstance(text,TextBox) else None
|
|
100
|
+
if rich is not None:text=' '.join(rich.text)
|
|
101
|
+
cell=p._cell_h if row else p._cell_w
|
|
102
|
+
full_text=text
|
|
103
|
+
if rich is None and (automatic or _vector(raw)):
|
|
104
|
+
projection=abs(np.sin(np.deg2rad(rotation)) if row else np.cos(np.deg2rad(rotation)))
|
|
105
|
+
available=max(0,(end-begin)*cell-a.mm(.5))/max(projection,1e-9)
|
|
106
|
+
text=fit_text(text,size,min(a.mm(60),available),a.font_family,bold,italic)
|
|
107
|
+
from .slice_geometry import slice_gaps
|
|
108
|
+
from .appearance import _coord
|
|
109
|
+
center=_coord(begin,cell,breaks,slice_gaps(p,axis))+(end-begin)*cell/2
|
|
110
|
+
# A scalar title spans the entire body, including all slice gaps.
|
|
111
|
+
if not automatic and (isinstance(raw,(str,TextBox)) or np.isscalar(raw)):
|
|
112
|
+
center=(height if row else width)/2
|
|
113
|
+
n=dict(text=text,x=0. if row else x+center,y=y+center if row else 0.,
|
|
114
|
+
size=size,anchor='middle',rotation=rotation,bold=bold,italic=italic,color=color(getattr(p,'_slice_title_colors',{}).get(axis,{}).get(full_text,gp_value(gp,'col',index,'black'))),
|
|
115
|
+
component=axis+'_title',full_text=full_text,slice_bounds=(begin,end))
|
|
116
|
+
if 'fontfamily' in gp:n['family']=gp_value(gp,'fontfamily',index)
|
|
117
|
+
if rich is not None:
|
|
118
|
+
n['rich_title']=rich;n['title_box']=rich.measure(dpi=a.dpi,unit='px')
|
|
119
|
+
elif 'fill' in gp or 'border' in gp:
|
|
120
|
+
n['title_padding']=a.pt(3)
|
|
121
|
+
n['title_background']=(color(gp_value(gp,'fill',index)),color(gp_value(gp,'border',index)),a.pt(float(gp_value(gp,'lwd',index,.75))))
|
|
122
|
+
group.append(n)
|
|
123
|
+
if group:
|
|
124
|
+
boxes=[envelope(n,a.font_family) for n in group]
|
|
125
|
+
offset=(min(b[across] for b in occupied)-gap-max(b[across+2] for b in boxes)) if negative else (max(b[across+2] for b in occupied)+gap-min(b[across] for b in boxes))
|
|
126
|
+
previous=[]
|
|
127
|
+
for n in group:
|
|
128
|
+
coordinate='x' if row else 'y';along=1 if row else 0;across=0 if row else 1
|
|
129
|
+
n[coordinate]=offset;box=envelope(n,a.font_family)
|
|
130
|
+
previous=[b for b in previous if b[along+2]>box[along]]
|
|
131
|
+
while True:
|
|
132
|
+
collisions=[b for b in previous if min(b[2],box[2])>max(b[0],box[0]) and min(b[3],box[3])>max(b[1],box[1])]
|
|
133
|
+
if not collisions:break
|
|
134
|
+
n[coordinate]+=(min(b[across] for b in collisions)-gap-box[across+2]) if negative else (max(b[across+2] for b in collisions)+gap-box[across])
|
|
135
|
+
box=envelope(n,a.font_family)
|
|
136
|
+
previous.append(box)
|
|
137
|
+
nodes.extend(group)
|
|
138
|
+
occupied.extend(envelope(n,a.font_family) for n in group)
|
|
139
|
+
return nodes
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def draw_title(p,sink,node):
|
|
143
|
+
"""Draw a measured plain or segmented title through the same native sink."""
|
|
144
|
+
from .appearance import _text
|
|
145
|
+
from .graphics import color,gp_value
|
|
146
|
+
a=p._appearance
|
|
147
|
+
if 'title_background' in node:
|
|
148
|
+
fill,stroke,lwd=node['title_background']
|
|
149
|
+
x,y,right,bottom=envelope(node,a.font_family)
|
|
150
|
+
sink.write(f'<rect x="{x}" y="{y}" width="{right-x}" height="{bottom-y}" fill="{fill}" stroke="{stroke}" stroke-width="{lwd}"/>')
|
|
151
|
+
rich=node.get('rich_title')
|
|
152
|
+
if rich is None:
|
|
153
|
+
_text(sink,node['x'],node['y'],node['text'],node['size'],node['anchor'],rotation=node['rotation'] or None,bold=node.get('bold',False),italic=node.get('italic',False),color=node.get('color'),family=node.get('family'))
|
|
154
|
+
return
|
|
155
|
+
from .style import Appearance
|
|
156
|
+
w,h,segments=rich._layout(Appearance(a.dpi,font_family=rich.font_family))
|
|
157
|
+
angle=np.deg2rad(node['rotation'] or 0)
|
|
158
|
+
def point(x,y):
|
|
159
|
+
return node['x']+x*np.cos(angle)-y*np.sin(angle),node['y']+x*np.sin(angle)+y*np.cos(angle)
|
|
160
|
+
local=[(-w/2,-h/2),(w/2,-h/2),(w/2,h/2),(-w/2,h/2)]
|
|
161
|
+
if rich.round_corners and rich.r:
|
|
162
|
+
radius=min(w,h)*rich.r;local=[]
|
|
163
|
+
for cx,cy,start in ((w/2-radius,-h/2+radius,-90),(w/2-radius,h/2-radius,0),(-w/2+radius,h/2-radius,90),(-w/2+radius,-h/2+radius,180)):
|
|
164
|
+
local.extend((cx+radius*np.cos(t),cy+radius*np.sin(t)) for t in np.linspace(np.deg2rad(start),np.deg2rad(start+90),9))
|
|
165
|
+
corners=[point(x,y) for x,y in local]
|
|
166
|
+
fill=color(gp_value(rich.background_gp,'fill'));stroke=color(gp_value(rich.background_gp,'col',0,'black'))
|
|
167
|
+
lwd=a.pt(float(gp_value(rich.background_gp,'lwd',0,.75)))
|
|
168
|
+
sink.write('<polygon points="'+' '.join(f'{x},{y}' for x,y in corners)+f'" fill="{fill}" stroke="{stroke}" stroke-width="{lwd}"/>')
|
|
169
|
+
for x,y,text,size,family,bold,italic,rgb in segments:
|
|
170
|
+
xx,yy=point(x-w/2,y-h/2)
|
|
171
|
+
_text(sink,xx,yy,text,size,bold=bold,italic=italic,color=rgb,family=family,rotation=node['rotation'] or None)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def subset_slice_visuals(p,rows,columns):
|
|
175
|
+
"""Keep per-group styles and sum original gaps between retained groups."""
|
|
176
|
+
from .graphics import _vector as gp_vector,gp_value
|
|
177
|
+
for axis,selected in [('row',rows),('column',columns)]:
|
|
178
|
+
gp=p._title_gp[axis];raw=p._visual_options.get(axis+'_gap_mm')
|
|
179
|
+
if not any(gp_vector(v,k) for k,v in gp.items()) and not _vector(raw):continue
|
|
180
|
+
names=p.row_names if axis=='row' else p.col_names
|
|
181
|
+
bounds=p._get_bounds(len(names),p.row_breaks if axis=='row' else p.col_breaks)
|
|
182
|
+
selected=set(map(str,selected))
|
|
183
|
+
retained=[i for i,(a,b) in enumerate(bounds) if selected.intersection(map(str,names[a:b]))]
|
|
184
|
+
style={k:[gp_value(gp,k,i) for i in retained] if gp_vector(v,k) else v for k,v in gp.items()}
|
|
185
|
+
p._title_gp={**p._title_gp,axis:style}
|
|
186
|
+
p._visual_options[axis+'_title_gp']=style
|
|
187
|
+
if _vector(raw):
|
|
188
|
+
values=np.asarray(raw,float)
|
|
189
|
+
if values.shape!=(len(bounds)-1,) or not np.isfinite(values).all() or np.any(values<0):
|
|
190
|
+
raise ValueError(axis+' gap vector must have one finite nonnegative value per slice boundary')
|
|
191
|
+
p._visual_options[axis+'_gap_mm']=[float(values[a:b].sum()) for a,b in zip(retained,retained[1:])]
|
tilesig/tree_styles.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Opt-in merge-index styling and markers for embedded native hierarchies."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
from .graphics import validate_gp,_vector,gp_value,draw_marker,color
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def validate_nodes(gp):
|
|
7
|
+
if gp is None:return None
|
|
8
|
+
gp=validate_gp(gp,{'col','fill','lwd','pch','size'})
|
|
9
|
+
sizes=np.atleast_1d(gp.get('size',1.5))
|
|
10
|
+
if not np.isfinite(sizes).all() or np.any(sizes<=0):raise ValueError('dendrogram node size must be positive finite mm')
|
|
11
|
+
symbols=gp.get('pch','circle');symbols=list(symbols) if _vector(symbols) else [symbols]
|
|
12
|
+
allowed={0,1,2,3,4,5,6,15,16,17,18,19,20,21,22,23,24,25,'circle','square','triangle','diamond','plus','cross'}
|
|
13
|
+
if not symbols or any(s not in allowed for s in symbols):raise ValueError('unsupported dendrogram node pch')
|
|
14
|
+
return gp
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def branch_options(p,axis):
|
|
18
|
+
gp=p._dend_gp[axis];nodes=p._dend_node_gp[axis]
|
|
19
|
+
# Keep the historical default geometry/string path byte-identical.
|
|
20
|
+
if nodes is None and not any(_vector(v,k) for k,v in gp.items()):return {}
|
|
21
|
+
return {'branch_gp':gp,'node_gp':nodes}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def style_branch(p,points,index,gp,node_gp):
|
|
25
|
+
"""Linkage-row index drives styles even after a hierarchy is rotated."""
|
|
26
|
+
a=p._appearance
|
|
27
|
+
attrs=f' data-merge="{index+1}" stroke="{color(gp_value(gp or {},"col",index,"black"))}" stroke-width="{a.pt(float(gp_value(gp or {},"lwd",index,.75)))}"'
|
|
28
|
+
polyline='<polyline points="'+' '.join(f'{x:.1f},{y:.1f}' for x,y in points)+'"'+attrs+'/>'
|
|
29
|
+
if node_gp is None:return polyline
|
|
30
|
+
import io
|
|
31
|
+
sink=io.StringIO();x=(points[1][0]+points[2][0])/2;y=(points[1][1]+points[2][1])/2
|
|
32
|
+
sink.write(f'<g data-dend-node="{index+1}">')
|
|
33
|
+
draw_marker(sink,x,y,a.mm(float(gp_value(node_gp,'size',index,1.5)))/2,
|
|
34
|
+
pch=gp_value(node_gp,'pch',index,'circle'),col=gp_value(node_gp,'col',index,'black'),
|
|
35
|
+
fill=gp_value(node_gp,'fill',index),linewidth=a.pt(float(gp_value(node_gp,'lwd',index,.75))))
|
|
36
|
+
sink.write('</g>')
|
|
37
|
+
return polyline+sink.getvalue()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def marker_padding(p,axis):
|
|
41
|
+
gp=p._dend_node_gp[axis]
|
|
42
|
+
if gp is None:return 0.
|
|
43
|
+
radius=p._appearance.mm(float(np.max(np.atleast_1d(gp.get('size',1.5)))))/2
|
|
44
|
+
stroke=p._appearance.pt(float(np.max(np.atleast_1d(gp.get('lwd',.75)))))/2
|
|
45
|
+
return radius+stroke
|
tilesig/unicode_pdf.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Direct PDF sink with embedded Unicode fonts, consuming drawing primitives."""
|
|
2
|
+
import io
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from PIL import Image, ImageFont
|
|
7
|
+
from reportlab.pdfbase import pdfmetrics
|
|
8
|
+
from reportlab.pdfbase.ttfonts import TTFont
|
|
9
|
+
from reportlab.lib.utils import ImageReader
|
|
10
|
+
from reportlab.pdfgen.canvas import Canvas
|
|
11
|
+
|
|
12
|
+
from .pdf_renderer import PdfSink, _IndexedImage
|
|
13
|
+
from .style import font_path
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@lru_cache(maxsize=16)
|
|
17
|
+
def register_fonts(family,include_italic=False):
|
|
18
|
+
regular='Heatmap-'+str(abs(hash(font_path(False,family))))
|
|
19
|
+
bold=regular+'-Bold'
|
|
20
|
+
pdfmetrics.registerFont(TTFont(regular,font_path(False,family)))
|
|
21
|
+
pdfmetrics.registerFont(TTFont(bold,font_path(True,family)))
|
|
22
|
+
if include_italic:
|
|
23
|
+
italic=regular+'-Oblique';bolditalic=regular+'-BoldOblique'
|
|
24
|
+
pdfmetrics.registerFont(TTFont(italic,font_path(False,family,True)))
|
|
25
|
+
pdfmetrics.registerFont(TTFont(bolditalic,font_path(True,family,True)))
|
|
26
|
+
return regular,bold,italic,bolditalic
|
|
27
|
+
return regular,bold
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@lru_cache(maxsize=256)
|
|
31
|
+
def _font_metrics(family,bold,italic,size):
|
|
32
|
+
return ImageFont.truetype(font_path(bold,family,italic),max(1,round(size))).getmetrics()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class UnicodePdfSink(PdfSink):
|
|
36
|
+
def __init__(self,page_w,page_h,dpi=300,font_family='DejaVu Sans'):
|
|
37
|
+
super().__init__(page_w,page_h)
|
|
38
|
+
self.dpi=dpi
|
|
39
|
+
self.font_family=font_family
|
|
40
|
+
|
|
41
|
+
def _canvas(self, output, full_w, full_h):
|
|
42
|
+
scale = 72 / self.dpi
|
|
43
|
+
canvas = Canvas(output, pagesize=(full_w * scale, full_h * scale),
|
|
44
|
+
pageCompression=1, invariant=1)
|
|
45
|
+
canvas.scale(scale, scale)
|
|
46
|
+
return canvas
|
|
47
|
+
|
|
48
|
+
def finalize(self,output_path,full_w,full_h):
|
|
49
|
+
canvas = self._canvas(str(output_path), full_w, full_h)
|
|
50
|
+
for op in self._ops:
|
|
51
|
+
self._draw_op(canvas, full_h, op)
|
|
52
|
+
canvas.showPage()
|
|
53
|
+
canvas.save()
|
|
54
|
+
|
|
55
|
+
def _draw_op(self, c, full_h, op):
|
|
56
|
+
kind=op[0]
|
|
57
|
+
if kind=='polygon':
|
|
58
|
+
_,points,fill,stroke,sw,alpha=op
|
|
59
|
+
c.saveState()
|
|
60
|
+
if fill is not None:c.setFillColorRGB(*fill)
|
|
61
|
+
if stroke is not None:c.setStrokeColorRGB(*stroke)
|
|
62
|
+
c.setLineWidth(sw or 0)
|
|
63
|
+
if alpha is not None:c.setFillAlpha(alpha)
|
|
64
|
+
shape=c.beginPath();shape.moveTo(points[0][0],full_h-points[0][1])
|
|
65
|
+
for xx,yy in points[1:]:shape.lineTo(xx,full_h-yy)
|
|
66
|
+
shape.close();c.drawPath(shape,stroke=int(stroke is not None),fill=int(fill is not None));c.restoreState()
|
|
67
|
+
elif kind=='image':
|
|
68
|
+
_,x,y,w,h,payload=op
|
|
69
|
+
if isinstance(payload,_IndexedImage):
|
|
70
|
+
idx=np.frombuffer(payload.indices,np.uint8).reshape(payload.height,payload.width)
|
|
71
|
+
pal=np.frombuffer(bytes.fromhex(payload.palette_hex.decode('ascii')),np.uint8).reshape(-1,3)
|
|
72
|
+
im=Image.fromarray(pal[idx])
|
|
73
|
+
else:
|
|
74
|
+
im=Image.open(io.BytesIO(payload))
|
|
75
|
+
c.drawImage(ImageReader(im),x,full_h-y-h,w,h,mask='auto')
|
|
76
|
+
elif kind=='rect':
|
|
77
|
+
_,x,y,w,h,fill,stroke,sw,alpha=op
|
|
78
|
+
c.saveState()
|
|
79
|
+
if fill is not None:c.setFillColorRGB(*fill)
|
|
80
|
+
if stroke is not None:c.setStrokeColorRGB(*stroke)
|
|
81
|
+
c.setLineWidth(sw or 0)
|
|
82
|
+
if alpha is not None:c.setFillAlpha(alpha)
|
|
83
|
+
c.rect(x,full_h-y-h,w,h,stroke=int(stroke is not None),fill=int(fill is not None))
|
|
84
|
+
c.restoreState()
|
|
85
|
+
elif kind in ('line','lines'):
|
|
86
|
+
if kind=='line':
|
|
87
|
+
_,x1,y1,x2,y2,stroke,sw=op
|
|
88
|
+
segments=[(x1,y1,x2,y2)]
|
|
89
|
+
else:_,segments,stroke,sw=op
|
|
90
|
+
if stroke is None:return
|
|
91
|
+
c.setStrokeColorRGB(*stroke);c.setLineWidth(sw)
|
|
92
|
+
c.lines([(a,full_h-b,d,full_h-e) for a,b,d,e in segments])
|
|
93
|
+
elif kind=='circle':
|
|
94
|
+
_,x,y,r,fill,stroke,sw=op
|
|
95
|
+
if fill is not None:c.setFillColorRGB(*fill)
|
|
96
|
+
if stroke is not None:c.setStrokeColorRGB(*stroke);c.setLineWidth(sw)
|
|
97
|
+
c.circle(x,full_h-y,r,stroke=int(stroke is not None),fill=int(fill is not None))
|
|
98
|
+
elif kind=='text':
|
|
99
|
+
_,x,y,content,fname,size,rgb,anchor,baseline,rot=op
|
|
100
|
+
family=getattr(fname,'family',None) or self.font_family
|
|
101
|
+
regular,bold,italic,bolditalic=register_fonts(family,include_italic=True)
|
|
102
|
+
font=(bolditalic if 'Bold' in fname else italic) if 'Oblique' in fname or 'Italic' in fname else bold if 'Bold' in fname else regular
|
|
103
|
+
c.setFont(font,size)
|
|
104
|
+
c.setFillColorRGB(*(rgb or (0,0,0)))
|
|
105
|
+
width=pdfmetrics.stringWidth(content,font,size)
|
|
106
|
+
dx=-width/2 if anchor=='middle' else -width if anchor=='end' else 0
|
|
107
|
+
# Match the raster sink's Pillow anchors in the same pixel
|
|
108
|
+
# coordinate system. PDF baselines increase upwards; middle
|
|
109
|
+
# alignment moves the baseline below the SVG anchor.
|
|
110
|
+
ascent,descent=_font_metrics(family,'Bold' in fname,'Oblique' in fname or 'Italic' in fname,size)
|
|
111
|
+
alignment=str(baseline or '').lower()
|
|
112
|
+
off=(ascent-descent)/2 if 'middle' in alignment else ascent if 'hanging' in alignment or 'before' in alignment else -descent if 'after' in alignment else 0
|
|
113
|
+
c.saveState()
|
|
114
|
+
if rot:
|
|
115
|
+
angle,rx,ry=rot
|
|
116
|
+
c.translate(rx,full_h-ry);c.rotate(-angle)
|
|
117
|
+
c.drawString(x-rx+dx,ry-y-off,content)
|
|
118
|
+
else:c.drawString(x+dx,full_h-y-off,content)
|
|
119
|
+
c.restoreState()
|