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,172 @@
1
+ """Identity and explicit geometry helpers for native specialized scenes."""
2
+ from collections import Counter
3
+ import copy
4
+ import numpy as np
5
+ from .slice_geometry import slice_gaps
6
+ import pandas as pd
7
+ from matplotlib.colors import to_hex
8
+
9
+
10
+ def no_mean_compression(options):
11
+ config=options.get('config')
12
+ for axis in ('row','col'):
13
+ value=options.get(axis+'_compression',getattr(config,axis+'_compression',1))
14
+ if value is not None and value!=1:raise ValueError('mean compression is unsupported for categorical event/membership displays')
15
+
16
+
17
+ def _event_ids(values, supplied, parameter):
18
+ def names(ids):
19
+ if isinstance(ids, (str, bytes)):
20
+ raise TypeError(f'{parameter} must be a sequence of identifiers')
21
+ index = pd.Index(ids, tupleize_cols=False)
22
+ labels = index.map(str)
23
+ if index.isna().any() or any(not label.strip() for label in labels):
24
+ raise ValueError(f'{parameter} must contain nonmissing, nonblank identifiers')
25
+ if not labels.is_unique:
26
+ raise ValueError(f'{parameter} identifiers must be unique after string conversion')
27
+ return labels
28
+
29
+ codes, observed = pd.factorize(values)
30
+ if (codes < 0).any():
31
+ raise ValueError(f'event records must have a nonmissing ID for {parameter}')
32
+ observed = names(observed)
33
+ if supplied is None:
34
+ return observed, codes
35
+ axis = names(supplied)
36
+ lookup = axis.get_indexer(observed)
37
+ if (lookup < 0).any():
38
+ raise ValueError(f'{parameter} must include all identifiers present in the event table')
39
+ return axis, lookup[codes]
40
+
41
+
42
+ def onco_table_events(data, *, sample, gene, event, sample_ids, gene_ids):
43
+ """Build one native event tuple per cell from a table of present events."""
44
+ if not isinstance(data, pd.DataFrame):
45
+ raise TypeError('long-form oncoPrint input must be a pandas DataFrame')
46
+ fields = {sample, gene, event}
47
+ if not data.columns.is_unique or len(fields) != 3:
48
+ raise ValueError('long-form oncoPrint requires unique table columns and distinct sample, gene and event fields')
49
+ if not fields <= set(data.columns):
50
+ raise ValueError('sample, gene and event must name columns in the event table')
51
+ rows, row_codes = _event_ids(data[gene], gene_ids, 'gene_ids')
52
+ columns, column_codes = _event_ids(data[sample], sample_ids, 'sample_ids')
53
+ types_by_cell = {}
54
+ for row, column, kind in zip(row_codes, column_codes, data[event]):
55
+ if not isinstance(kind, str) or not kind.strip():
56
+ raise ValueError('event types must be nonempty strings, with one type per record')
57
+ types_by_cell.setdefault((row, column), {})[kind.strip()] = None
58
+ events = np.empty((len(rows), len(columns)), dtype=object)
59
+ events.fill(())
60
+ for cell, types in types_by_cell.items():
61
+ events[cell] = tuple(types)
62
+ return events, rows, columns
63
+
64
+
65
+ def onco_r_orders(events,row_order=None):
66
+ from .api import _order
67
+ counts=np.asarray([[len(cell) for cell in row] for row in events])
68
+ affected=(counts>0).sum(axis=1);totals=counts.sum(axis=1)
69
+ rows=np.asarray(sorted(range(len(counts)),key=lambda i:(-totals[i],-affected[i])),int) if row_order is None else np.asarray(row_order)
70
+ c=counts[rows];rank=np.arange(1,len(c)+1)[:,None]
71
+ # Remove the common 2**n factor to avoid overflow for large gene panels.
72
+ scores=np.sum(np.where(c>0,np.exp2(-rank/np.maximum(c,1)),0),axis=0)
73
+ return rows,np.argsort(-scores,kind='stable')
74
+
75
+
76
+ def onco_layer(plotter,sink,layout,fun,vectorized,with_indices):
77
+ from .appearance import _coord
78
+ p=plotter;nr,nc=p._matrix_sorted.shape;ii,jj=np.indices((nr,nc));i=ii.ravel();j=jj.ravel()
79
+ frame=p.alterations.reindex(index=p.row_names,columns=p.col_names)
80
+ if frame.isna().any().any():raise ValueError('oncoPrint event IDs do not match the displayed source axis')
81
+ cells=frame.to_numpy().ravel();types=list(p.alteration_colors)
82
+ x=layout['heatmap_x']+np.array([_coord(k,layout['cell_w'],p.col_breaks,slice_gaps(p,'column')) for k in j])+layout['cell_w']/2
83
+ y=layout['heatmap_y']+np.array([_coord(k,layout['cell_h'],p.row_breaks,slice_gaps(p,'row')) for k in i])+layout['cell_h']/2
84
+ w=np.full(len(j),layout['cell_w']);h=np.full(len(i),layout['cell_h'])
85
+ active={t:np.asarray([t in cell for cell in cells],bool) for t in types}
86
+ def call(callback,mask,args=()):
87
+ callback(sink,x[mask],y[mask],w[mask],h[mask],*args,*((j[mask],i[mask]) if with_indices else ()))
88
+ if callable(fun):call(fun,np.ones(len(i),bool),(active,))
89
+ else:
90
+ if fun and 'background' in fun:call(fun['background'],np.ones(len(i),bool))
91
+ from .specialized import alter_graphic
92
+ for t in dict.fromkeys([t for t in (fun or {}) if t in types]+types):
93
+ mask=active[t]
94
+ if not mask.any():continue
95
+ if fun and t in fun:call(fun[t],mask)
96
+ else:
97
+ # Retain the original per-cell stacked default geometry.
98
+ for k in np.flatnonzero(mask):
99
+ cell=cells[k];position=cell.index(t);hh=h[k]*.8/max(1,len(cell));yy=y[k]-h[k]*.4+position*hh
100
+ sink.write(f'<rect x="{x[k]-w[k]*.4}" y="{yy}" width="{w[k]*.8}" height="{hh}" fill="{p.alteration_colors[t]}"/>')
101
+
102
+
103
+ def transform_metadata(out,*,row_map=None,column_map=None,subset=False):
104
+ """Maintain specialized source metadata across the copying object API."""
105
+ from .algorithm_binding import transform_bindings
106
+ transform_bindings(out,row_map=row_map,column_map=column_map,subset=subset)
107
+ if getattr(out,'_dot_heatmap',False):
108
+ for attribute in ('size_values', '_dot_category_ids'):
109
+ frame = getattr(out, attribute)
110
+ if frame is None:
111
+ continue
112
+ if subset:
113
+ frame = frame.reindex(index=out.df.index.map(str), columns=out.df.columns.map(str)).copy()
114
+ else:
115
+ frame = frame.rename(index=row_map, columns=column_map)
116
+ setattr(out, attribute, frame)
117
+ if not subset:
118
+ for h in getattr(out,'all_annotations',[]):
119
+ if getattr(h,'item_colors',None) is not None:h.item_colors=h.item_colors.rename(index=row_map if h.side in ('left','right') else column_map)
120
+ kind=getattr(out,'_specialized_kind',None)
121
+ if kind=='oncoPrint':
122
+ source_rows=set(out.alterations.index);source_columns=set(out.alterations.columns)
123
+ if subset:
124
+ out.alterations=out.alterations.reindex(index=out.df.index.map(str),columns=out.df.columns.map(str)).copy()
125
+ out.alteration_percentages=out.alteration_percentages.reindex(out.df.index.map(str)).copy()
126
+ else:
127
+ out.alterations=out.alterations.rename(index=row_map,columns=column_map)
128
+ out.alteration_percentages=out.alteration_percentages.rename(index=row_map)
129
+ out.alteration_counts=Counter(t for row in out.alterations.to_numpy() for cell in row for t in cell)
130
+ for track in out.all_annotations:
131
+ bound=getattr(track,'_item_colors_by_id',None)
132
+ if bound is not None:
133
+ row=track.side in ('left','right')
134
+ active=set(out.alterations.index if row else out.alterations.columns) if subset else source_rows if row else source_columns
135
+ mapping=(row_map if row else column_map) or {}
136
+ track._item_colors_by_id={mapping.get(key,key):value for key,value in bound.items() if key in active}
137
+ axis=getattr(track,'_onco_default_count_axis',None)
138
+ if subset and axis is not None:
139
+ values={t:out.alterations.map(lambda cell:t in cell).sum(axis=1 if axis=='row' else 0)
140
+ for t in track.df.columns}
141
+ track.df=pd.DataFrame(values,index=track.df.index)
142
+ elif kind=='UpSet':
143
+ mapping=column_map if out._upset_set_on_rows else row_map
144
+ if mapping is not None:
145
+ out.upset_colors={mapping.get(k,k):v for k,v in out.upset_colors.items()}
146
+ out._upset_size_by_id={mapping.get(k,k):v for k,v in out._upset_size_by_id.items()}
147
+ for query in out.upset_queries:query['combinations']=tuple(mapping.get(k,k) for k in query['combinations'])
148
+ set_map=row_map if out._upset_set_on_rows else column_map
149
+ if set_map is not None and out._upset_backgrounds is not None:out._upset_backgrounds={set_map.get(k,k):v for k,v in out._upset_backgrounds.items()}
150
+ ids=out.df.columns.map(str) if out._upset_set_on_rows else out.df.index.map(str)
151
+ from .sets import _count_array
152
+ out.combination_sizes=_count_array([out._upset_size_by_id[k] for k in ids],True)
153
+ elif kind=='distribution':
154
+ mapping=column_map or {}
155
+ columns=set(out.df.columns.map(str))
156
+ for field in ('distribution_quantiles','distribution_means'):
157
+ values=getattr(out,field,None)
158
+ if values is not None:
159
+ setattr(out,field,{mapping.get(k,k):v for k,v in values.items() if not subset or k in columns})
160
+ if hasattr(out,'distribution_value_by_id') and row_map is not None:
161
+ out.distribution_value_by_id={row_map.get(k,k):v for k,v in out.distribution_value_by_id.items()}
162
+
163
+
164
+ def color_by_ids(value,ids):
165
+ ids=list(map(str,ids))
166
+ if isinstance(value,(dict,pd.Series)):
167
+ if set(map(str,value.keys()))!=set(ids):raise ValueError('colors must cover every source combination ID')
168
+ return {str(k):to_hex(v) for k,v in value.items()}
169
+ from .graphics import _vector
170
+ values=list(value) if _vector(value,'col') else [value]
171
+ if not values:raise ValueError('colors must not be empty')
172
+ return {k:to_hex(values[i%len(values)]) for i,k in enumerate(ids)}
@@ -0,0 +1,118 @@
1
+ """Stream large vector pages while ReportLab manages fonts and other resources."""
2
+
3
+ from pathlib import Path
4
+ from shutil import copyfileobj
5
+ from tempfile import TemporaryFile
6
+ import zlib
7
+
8
+ from reportlab.pdfbase import pdfdoc
9
+
10
+ from .unicode_pdf import UnicodePdfSink
11
+ from .vector_grid import colour_index_rows
12
+
13
+
14
+ _INDEXED_FILLS = tuple(f'{index} sc\n'.encode('ascii') for index in range(256))
15
+
16
+
17
+ class _StreamingPdfSink(UnicodePdfSink):
18
+ def __init__(self, scratch, width, height, dpi, font_family):
19
+ super().__init__(width, height, dpi, font_family)
20
+ self._scratch = scratch
21
+ self._compressor = zlib.compressobj()
22
+ self._canvas_writer = self._canvas(None, width, height)
23
+ self._palettes = {}
24
+ self._write_commands(self._canvas_writer._preamble.encode('ascii') + b'\n')
25
+
26
+ def _write_commands(self, commands):
27
+ self._scratch.write(self._compressor.compress(commands))
28
+
29
+ def _flush_canvas(self):
30
+ code = self._canvas_writer._code
31
+ if code:
32
+ self._write_commands(('\n'.join(code) + '\n').encode('latin1'))
33
+ code.clear()
34
+
35
+ def _append_op(self, op):
36
+ self._draw_op(self._canvas_writer, self._page_h, op)
37
+ if len(self._canvas_writer._code) >= 4096:
38
+ self._flush_canvas()
39
+
40
+ def write_vector_grid(self, x, y, cw, ch, values, lo, hi, palette_rgb):
41
+ """Write opaque cells row by row with local coordinates and indexed fills."""
42
+ self._flush_canvas()
43
+ palette = palette_rgb.tobytes()
44
+ name = self._palettes.setdefault(palette, f'SMGrid{len(self._palettes)}')
45
+ x += self._tx
46
+ y = self._page_h - (y + self._ty)
47
+ # Decimal notation keeps PDF operands valid even for subpixel cell sizes.
48
+ transform = f'q\n/{name} cs\n{cw:.15f} 0 0 {-ch:.15f} {x:.12f} {y:.12f} cm\n'
49
+ self._write_commands(transform.encode('ascii'))
50
+ rectangles = tuple(f'{column} 0 1 1 re f*\n'.encode('ascii')
51
+ for column in range(values.shape[1]))
52
+ # Keep the original paint order. PDF viewers can map adjacent subpixel
53
+ # rectangles to the same display pixel, making their order observable.
54
+ for row, indices in enumerate(colour_index_rows(values, lo, hi)):
55
+ cells = b''.join(_INDEXED_FILLS[index] + rectangle
56
+ for index, rectangle in zip(indices, rectangles))
57
+ self._write_commands(f'q\n1 0 0 1 0 {row} cm\n'.encode('ascii') + cells + b'Q\n')
58
+ self._write_commands(b'Q\n')
59
+
60
+ def finish(self, output_path):
61
+ self._flush_canvas()
62
+ self._scratch.write(self._compressor.flush())
63
+
64
+ canvas = self._canvas_writer
65
+ canvas.showPage()
66
+ document = canvas._doc
67
+ page = document.Pages.pages[0]
68
+ # Let ReportLab build the page resources and cross-references around an
69
+ # empty stream. The full page content remains in the scratch file.
70
+ page.Contents = pdfdoc.PDFStream(content=b'')
71
+ page.check_format(document)
72
+ for palette, name in self._palettes.items():
73
+ page.Resources.ColorSpace[name] = b'[ /Indexed /DeviceRGB 255 <' + palette.hex().encode('ascii') + b'> ]'
74
+ content_id = document.Reference(page.Contents).name
75
+ skeleton = canvas.getpdfdata()
76
+ _replace_page_stream(output_path, document, content_id, skeleton, self._scratch)
77
+
78
+
79
+ def _replace_page_stream(path, document, content_id, skeleton, scratch):
80
+ """Copy the resource objects and the spooled page, then write the adjusted xref."""
81
+ offset = document.idToOffset[content_id]
82
+ stream_ref = pdfdoc.PDFIndirectObject(content_id, document.idToObject[content_id])
83
+ old_end = offset + len(stream_ref.format(document))
84
+ startxref = skeleton.rindex(b'\nstartxref\n')
85
+ old_xref = int(skeleton[startxref:].splitlines()[2])
86
+ stream_length = scratch.tell()
87
+ scratch.seek(0)
88
+ number, generation = document.idToObjectNumberAndVersion[content_id]
89
+
90
+ with Path(path).open('wb') as output:
91
+ data = memoryview(skeleton)
92
+ output.write(data[:offset])
93
+ output.write(f'{number} {generation} obj\n<< /Filter /FlateDecode /Length {stream_length} >>\nstream\n'.encode('ascii'))
94
+ copyfileobj(scratch, output, length=1024 * 1024)
95
+ output.write(b'\nendstream\nendobj\n')
96
+ shift = output.tell() - old_end
97
+ output.write(data[old_end:old_xref])
98
+
99
+ for object_id, original_offset in document.idToOffset.items():
100
+ if original_offset > offset:
101
+ document.idToOffset[object_id] = original_offset + shift
102
+ ids = [document.numberToId[i] for i in range(1, document.objectcounter + 1)]
103
+ xref = pdfdoc.PDFCrossReferenceTable()
104
+ xref.addsection(0, ids)
105
+ trailer = pdfdoc.PDFTrailer(startxref=output.tell(), Size=len(ids) + 1,
106
+ Root=document.Reference(document.Catalog),
107
+ Info=document.Reference(document.info), ID=document.ID())
108
+ output.write(xref.format(document))
109
+ output.write(trailer.format(document))
110
+
111
+
112
+ def save_vector_pdf(path, width, height, dpi, font_family, draw):
113
+ path = Path(path)
114
+ path.parent.mkdir(parents=True, exist_ok=True)
115
+ with TemporaryFile() as scratch:
116
+ sink = _StreamingPdfSink(scratch, width, height, dpi, font_family)
117
+ draw(sink)
118
+ sink.finish(path)
@@ -0,0 +1,72 @@
1
+ """Write SVG fragments directly and share rectangle definitions across cells."""
2
+
3
+ from base64 import b64encode
4
+ from pathlib import Path
5
+ from stat import S_IMODE, S_ISREG
6
+ from tempfile import TemporaryDirectory
7
+ from xml.sax.saxutils import quoteattr
8
+
9
+ from .vector_grid import colour_index_rows
10
+
11
+
12
+ _COMPACT_GRID_MIN_CELLS = 4096
13
+
14
+
15
+ class _SvgSink:
16
+ def __init__(self, stream):
17
+ self.write = stream.write
18
+ self._palettes = {}
19
+
20
+ def write_image(self, x, y, width, height, png):
21
+ payload = b64encode(png).decode('ascii')
22
+ self.write(f'<image x="{x}" y="{y}" width="{width}" height="{height}" '
23
+ f'preserveAspectRatio="none" xlink:href="data:image/png;base64,{payload}"/>')
24
+
25
+ def write_vector_grid(self, x, y, cw, ch, values, lo, hi, palette_rgb):
26
+ if values.size < _COMPACT_GRID_MIN_CELLS:
27
+ return False
28
+ palette = palette_rgb.tobytes()
29
+ links = self._palettes.get(palette)
30
+ if links is None:
31
+ ids = [f'sm{len(self._palettes)}-{index:x}' for index in range(len(palette_rgb))]
32
+ definition = ''.join(f'<rect id="{id_}" width="1" height="1" fill="#{rgb.tobytes().hex()}"/>'
33
+ for id_, rgb in zip(ids, palette_rgb))
34
+ self.write(f'<defs>{definition}</defs>\n')
35
+ links = tuple(f' xlink:href="#{id_}"/>' for id_ in ids)
36
+ self._palettes[palette] = links
37
+
38
+ self.write(f'<g transform="translate({x} {y}) scale({cw} {ch})">\n')
39
+ columns = tuple(f'<use x="{column}"' for column in range(values.shape[1]))
40
+ for row, indices in enumerate(colour_index_rows(values, lo, hi)):
41
+ cells = ''.join(column + links[index] for column, index in zip(columns, indices))
42
+ self.write(f'<g transform="translate(0 {row})">{cells}</g>\n')
43
+ self.write('</g>\n')
44
+
45
+
46
+ def save_vector_svg(path, width, height, dpi, font_family, draw):
47
+ path = Path(path)
48
+ path.parent.mkdir(parents=True, exist_ok=True)
49
+
50
+ def write_file(destination):
51
+ with destination.open('w', encoding='utf-8', newline='\n') as stream:
52
+ sink = _SvgSink(stream)
53
+ sink.write('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
54
+ f'width="{width / dpi * 25.4}mm" height="{height / dpi * 25.4}mm" '
55
+ f'viewBox="0 0 {width} {height}" font-family={quoteattr(font_family)}>')
56
+ draw(sink)
57
+ sink.write('</svg>')
58
+
59
+ try:
60
+ existing = path.lstat()
61
+ except FileNotFoundError:
62
+ existing = None
63
+ # Preserve link and device semantics, including writes to an open file descriptor.
64
+ if existing is not None and (not S_ISREG(existing.st_mode) or existing.st_nlink > 1):
65
+ write_file(path)
66
+ return
67
+ with TemporaryDirectory(prefix='.tilesig-svg-', dir=path.parent) as directory:
68
+ temporary = Path(directory) / path.name
69
+ write_file(temporary)
70
+ if existing is not None:
71
+ temporary.chmod(S_IMODE(existing.st_mode))
72
+ temporary.replace(path)
tilesig/style.py ADDED
@@ -0,0 +1,148 @@
1
+ """Physical appearance and vectorized color mapping; no plotting backend."""
2
+ from dataclasses import dataclass
3
+ from functools import lru_cache
4
+ from pathlib import Path
5
+
6
+ import cv2
7
+ import numpy as np
8
+ from PIL import ImageFont
9
+ from matplotlib.colors import to_rgb
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Appearance:
14
+ dpi: float = 300
15
+ body_width_mm: float = 180
16
+ font_family: str = 'DejaVu Sans'
17
+
18
+ def mm(self, value):
19
+ return float(value) * self.dpi / 25.4
20
+
21
+ def pt(self, value):
22
+ return float(value) * self.dpi / 72
23
+
24
+
25
+ @lru_cache(maxsize=32)
26
+ def font_path(bold=False,family='DejaVu Sans',italic=False):
27
+ """Resolve installed TTF files consistently for raster, PDF and SVG."""
28
+ import subprocess
29
+ style='Bold Oblique' if bold and italic else 'Oblique' if italic else 'Bold' if bold else 'Book'
30
+ query=family+':style='+style
31
+ try:
32
+ p = subprocess.run(['fc-match', '-f', '%{file}', query], capture_output=True, text=True, check=True).stdout.strip()
33
+ if p and Path(p).is_file():
34
+ # Serif families often call the face Italic rather than Oblique.
35
+ # Fontconfig's exact style query may silently return the regular
36
+ # face; request slant/weight when that happens.
37
+ if italic and not any(k in ImageFont.truetype(p,12).getname()[1].lower() for k in ('italic','oblique')):
38
+ fallback_query=family+':slant=italic:weight='+('bold' if bold else 'regular')
39
+ alternate=subprocess.run(['fc-match','-f','%{file}',fallback_query],capture_output=True,text=True,check=True).stdout.strip()
40
+ if alternate and Path(alternate).is_file():p=alternate
41
+ return p
42
+ except (OSError, subprocess.SubprocessError):
43
+ pass
44
+ name='DejaVuSans-BoldOblique.ttf' if bold and italic else 'DejaVuSans-Oblique.ttf' if italic else 'DejaVuSans-Bold.ttf' if bold else 'DejaVuSans.ttf'
45
+ for base in (Path('/usr/share/fonts/truetype/dejavu'), Path('C:/Windows/Fonts')):
46
+ if (base/name).is_file():
47
+ return str(base/name)
48
+ # Named-palette compatibility already depends on Matplotlib. Its bundled
49
+ # font resources also give consistent native text when fontconfig/system
50
+ # DejaVu are unavailable; no Matplotlib plotting backend is used.
51
+ from matplotlib import get_data_path
52
+ bundled=Path(get_data_path())/'fonts'/'ttf'/name
53
+ if bundled.is_file():return str(bundled)
54
+ # Pillow resolves its platform font search; use the path it actually chose.
55
+ return ImageFont.truetype(name, 12).path
56
+
57
+
58
+ def text_width(text,size,bold=False,family='DejaVu Sans',italic=False):
59
+ return ImageFont.truetype(font_path(bold,family,italic), max(1, round(size))).getlength(str(text))
60
+
61
+
62
+ @lru_cache(maxsize=32)
63
+ def resolved_font_family(family):
64
+ """Actual family name for SVG, matching the file used by PNG/PDF metrics."""
65
+ return ImageFont.truetype(font_path(False,str(family)),12).getname()[0]
66
+
67
+
68
+ class ColorMapping:
69
+ """Piecewise colorRamp2-like mapping with LAB or RGB interpolation.
70
+
71
+ Values outside breaks saturate. Missing values receive na_col. Breaks are
72
+ explicit; this object never normalizes data or infers quantile limits.
73
+ """
74
+ def __init__(self, breaks=None, colors=None, space='LAB', na_col=None,*,levels=None,name='',col_fun=None,full_col=None):
75
+ from collections.abc import Mapping
76
+ self.name=str(name);self.is_categorical=levels is not None or isinstance(colors,Mapping)
77
+ if col_fun is not None:
78
+ if full_col is not None:raise ValueError('full_col conflicts with col_fun')
79
+ if breaks is not None or colors is not None or levels is not None:raise ValueError('col_fun conflicts with explicit breaks/colors/levels')
80
+ if not isinstance(col_fun,ColorMapping):raise TypeError('col_fun must be a ColorMapping/colorRamp2 object')
81
+ import copy
82
+ self.__dict__.update(copy.deepcopy(col_fun.__dict__));self.name=str(name or getattr(col_fun,'name',''))
83
+ self.na_color=np.asarray(to_rgb('#FFFFFF' if na_col is None else na_col))*255
84
+ return
85
+ na_col=('#FFFFFF' if self.is_categorical else 'grey') if na_col is None else na_col
86
+ if self.is_categorical:
87
+ levels=list(colors) if levels is None else list(levels)
88
+ if not levels or len(set(levels))!=len(levels):raise ValueError('categorical levels must be nonempty and unique')
89
+ colors=[colors[k] for k in levels] if isinstance(colors,Mapping) else list(colors)
90
+ if len(colors)!=len(levels):raise ValueError('levels and colors must have equal length')
91
+ self.levels=np.asarray(levels,dtype=object);self.breaks=self.levels.copy()
92
+ self.colors=np.asarray([to_rgb(c) for c in colors],np.float32);self.na_color=np.asarray(to_rgb(na_col))*255
93
+ if full_col is not None:
94
+ if not isinstance(full_col,Mapping):raise TypeError('full_col must be a categorical color mapping')
95
+ if any(k not in full_col for k in levels):raise ValueError('full_col must include every visible categorical level')
96
+ self._full_colors={k:np.asarray(to_rgb(c),np.float32) for k,c in full_col.items()}
97
+ return
98
+ if full_col is not None:raise ValueError('full_col is only supported for categorical mappings')
99
+ self.breaks = np.asarray(breaks, dtype=float)
100
+ if self.breaks.ndim != 1 or len(self.breaks) < 2 or not np.all(np.isfinite(self.breaks)) or np.any(np.diff(self.breaks) <= 0):
101
+ raise ValueError('breaks must be at least two finite, strictly increasing values')
102
+ if len(colors) != len(self.breaks):
103
+ raise ValueError('colors and breaks must have equal length')
104
+ self.colors = np.array([to_rgb(c) for c in colors], dtype=np.float32)
105
+ self.space = str(space).upper()
106
+ if self.space not in ('LAB', 'RGB','SRGB'):
107
+ raise ValueError('space must be LAB, RGB or sRGB')
108
+ self.na_color = np.asarray(to_rgb(na_col))*255
109
+
110
+ def __call__(self, values, *, bytes=False):
111
+ if self.is_categorical:
112
+ import pandas as pd
113
+ v=np.asarray(values,dtype=object);flat=v.ravel();lookup=getattr(self,'_full_colors',None)
114
+ if lookup is None:lookup=dict(zip(self.levels,self.colors))
115
+ rows=[]
116
+ for value in flat:
117
+ if pd.isna(value):rows.append(self.na_color)
118
+ elif value in lookup:rows.append(np.rint(lookup[value]*255))
119
+ else:raise ValueError(f'unknown categorical level {value!r}')
120
+ result=np.asarray(rows,np.uint8).reshape(v.shape+(3,))
121
+ return result if bytes else result.astype(float)/255
122
+ v=np.asarray(values,dtype=float)
123
+ flat=v.ravel()
124
+ source=self.colors
125
+ if self.space=='LAB':
126
+ source=cv2.cvtColor(source[None,:,:],cv2.COLOR_RGB2LAB)[0]
127
+ elif self.space=='RGB':
128
+ source=np.where(source<=.04045,source/12.92,((source+.055)/1.055)**2.4)
129
+ mixed=np.stack([np.interp(flat,self.breaks,source[:,c]) for c in range(3)],axis=-1).astype(np.float32)
130
+ if self.space=='LAB':
131
+ mixed=cv2.cvtColor(mixed[None,:,:],cv2.COLOR_LAB2RGB)[0]
132
+ elif self.space=='RGB':
133
+ mixed=np.where(mixed<=.0031308,mixed*12.92,1.055*np.maximum(mixed,0)**(1/2.4)-.055)
134
+ result=np.clip(np.rint(mixed*255),0,255).astype(np.uint8)
135
+ result[~np.isfinite(flat)]=self.na_color.astype(np.uint8)
136
+ result=result.reshape(v.shape+(3,))
137
+ return result if bytes else result.astype(float)/255
138
+
139
+ def lut(self, n=256, bgr=True):
140
+ if self.is_categorical:
141
+ rgb=self(self.levels,bytes=True)
142
+ return rgb[:,::-1].copy() if bgr else rgb
143
+ rgb=self(np.linspace(self.breaks[0],self.breaks[-1],n),bytes=True)
144
+ return rgb[:,::-1].copy() if bgr else rgb
145
+
146
+
147
+ def colorRamp2(breaks, colors, space='LAB', na_col='grey'):
148
+ return ColorMapping(breaks,colors,space,na_col)