0
# Utility Functions
1
2
Comprehensive collection of helper functions for color processing, image conversion, legend scaling, and data manipulation. These utilities support visualization workflows with ColorBrewer integration, PNG generation, and data transformation capabilities.
3
4
## Capabilities
5
6
### Color Parsing and Conversion
7
8
Core color parsing functions for converting between different color formats.
9
10
```python { .api }
11
def _parse_color(x):
12
"""
13
Parse color input to RGBA float tuple.
14
15
Parameters:
16
- x: color input (tuple, list, hex string, or color name)
17
18
Returns:
19
tuple: (r, g, b, a) with float values between 0.0 and 1.0
20
21
Raises:
22
ValueError: if color format is unrecognized
23
"""
24
25
def _color_int_to_float(x: int) -> float:
26
"""
27
Convert integer color value (0-255) to float (0.0-1.0).
28
29
Parameters:
30
- x: integer color value between 0 and 255
31
32
Returns:
33
float: converted value between 0.0 and 1.0
34
"""
35
36
def _color_float_to_int(x: float) -> int:
37
"""
38
Convert float color value (0.0-1.0) to integer (0-255).
39
40
Parameters:
41
- x: float color value between 0.0 and 1.0
42
43
Returns:
44
int: converted value between 0 and 255
45
"""
46
47
def _is_hex(x: str) -> bool:
48
"""
49
Check if string is a valid hex color code.
50
51
Parameters:
52
- x: string to check
53
54
Returns:
55
bool: True if valid hex color (#RRGGBB format)
56
"""
57
58
def _parse_hex(color_code: str):
59
"""
60
Parse hex color string to RGBA float tuple.
61
62
Parameters:
63
- color_code: hex color string (#RRGGBB)
64
65
Returns:
66
tuple: (r, g, b, a) with float values between 0.0 and 1.0
67
"""
68
```
69
70
### Color Scheme Generation
71
72
Generate ColorBrewer color schemes with automatic interpolation for data visualization.
73
74
```python { .api }
75
def color_brewer(color_code: str, n: int = 6) -> list:
76
"""
77
Generate ColorBrewer color scheme with specified number of colors.
78
79
Parameters:
80
- color_code: ColorBrewer scheme name (e.g., 'YlGnBu', 'Set1', 'RdYlBu_r')
81
- n: number of colors to generate (3-253)
82
83
Returns:
84
list: hex color strings for the scheme
85
86
Raises:
87
ValueError: if color_code is invalid or n is out of range
88
TypeError: if n is not an integer
89
"""
90
91
def linear_gradient(hexList: list, nColors: int) -> list:
92
"""
93
Create linear color gradient between hex colors.
94
95
Parameters:
96
- hexList: list of hex color strings to interpolate between
97
- nColors: number of output colors
98
99
Returns:
100
list: hex color strings with smooth gradient
101
"""
102
103
def _base(x: float) -> float:
104
"""
105
Calculate base value for logarithmic scaling (used in round_method='log10').
106
107
Parameters:
108
- x: input value
109
110
Returns:
111
float: base value for logarithmic rounding
112
"""
113
```
114
115
### Legend and Scale Management
116
117
Functions for managing legend displays and scaling data values.
118
119
```python { .api }
120
def legend_scaler(legend_values: list, max_labels: int = 10) -> list:
121
"""
122
Downsample legend values to prevent text collision on colorbar.
123
124
Parameters:
125
- legend_values: sequence of float values for legend
126
- max_labels: maximum number of labels to display
127
128
Returns:
129
list: downsampled legend values with empty strings as spacers
130
"""
131
```
132
133
### Image Processing and Conversion
134
135
Convert image data to web-compatible formats with colormap support.
136
137
```python { .api }
138
def image_to_url(
139
image,
140
colormap = None,
141
origin: str = "upper"
142
) -> str:
143
"""
144
Convert image data to base64 data URL for web embedding.
145
146
Parameters:
147
- image: string URL, file object, or array-like image data
148
- colormap: ColorMap instance or callable for mono images
149
- origin: image origin placement ('upper' or 'lower')
150
151
Returns:
152
str: base64 data URL string for HTML embedding
153
"""
154
155
def write_png(
156
data,
157
origin: str = "upper",
158
colormap = None
159
) -> bytes:
160
"""
161
Convert array data to PNG byte string.
162
163
Parameters:
164
- data: numpy array (NxM mono, NxMx3 RGB, or NxMx4 RGBA)
165
- origin: image origin placement ('upper' or 'lower')
166
- colormap: ColorMap instance or callable for mono images
167
168
Returns:
169
bytes: PNG formatted byte string
170
171
Raises:
172
ImportError: if NumPy is not available
173
ValueError: if data dimensions are invalid
174
"""
175
```
176
177
### Template Management
178
179
Access to Jinja2 template environment for custom template rendering.
180
181
```python { .api }
182
def get_templates():
183
"""
184
Get Jinja2 environment with branca template loader.
185
186
Returns:
187
Environment: configured Jinja2 environment for branca templates
188
"""
189
```
190
191
### Data Structure Utilities
192
193
Helper functions for processing coordinate data and handling optional values.
194
195
```python { .api }
196
def none_min(x: float | None, y: float | None) -> float | None:
197
"""
198
Return minimum of two optional float values.
199
200
Parameters:
201
- x: optional float value
202
- y: optional float value
203
204
Returns:
205
Optional float: minimum value, or None if both are None
206
"""
207
208
def none_max(x: float | None, y: float | None) -> float | None:
209
"""
210
Return maximum of two optional float values.
211
212
Parameters:
213
- x: optional float value
214
- y: optional float value
215
216
Returns:
217
Optional float: maximum value, or None if both are None
218
"""
219
220
def iter_points(x: list | tuple) -> list:
221
"""
222
Flatten nested coordinate structures to simple point list.
223
224
Parameters:
225
- x: nested list/tuple structure of coordinates
226
227
Returns:
228
list: flattened list of coordinate points
229
230
Raises:
231
ValueError: if input is not list or tuple type
232
"""
233
```
234
235
## Usage Examples
236
237
### ColorBrewer Integration
238
239
```python
240
from branca.utilities import color_brewer
241
242
# Generate standard ColorBrewer schemes
243
blues = color_brewer('Blues', 9)
244
# Returns: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1',
245
# '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b']
246
247
# Generate reversed scheme
248
reds_reversed = color_brewer('Reds_r', 5)
249
250
# Generate diverging scheme
251
rd_yl_bu = color_brewer('RdYlBu', 11)
252
```
253
254
### Image Conversion for Web
255
256
```python
257
import numpy as np
258
from branca.utilities import image_to_url, write_png
259
from branca.colormap import LinearColormap
260
261
# Create sample data
262
data = np.random.rand(100, 100)
263
264
# Convert with custom colormap
265
colormap = LinearColormap(['blue', 'red'])
266
data_url = image_to_url(data, colormap=colormap, origin='upper')
267
268
# Generate PNG bytes for file saving
269
png_bytes = write_png(data, colormap=colormap)
270
with open('output.png', 'wb') as f:
271
f.write(png_bytes)
272
273
# Convert existing image file
274
with open('input.jpg', 'rb') as f:
275
image_url = image_to_url(f)
276
```
277
278
### Legend Scaling
279
280
```python
281
from branca.utilities import legend_scaler
282
283
# Scale down large number of legend values
284
values = list(range(0, 101, 5)) # [0, 5, 10, ..., 100]
285
scaled = legend_scaler(values, max_labels=6)
286
# Returns: [0, '', '', '', 20, '', '', '', 40, '', '', '', 60, '', '', '', 80, '', '', '', 100]
287
```
288
289
### Color Gradient Generation
290
291
```python
292
from branca.utilities import linear_gradient
293
294
# Create gradient between colors
295
colors = ['#ff0000', '#00ff00', '#0000ff'] # Red, green, blue
296
gradient = linear_gradient(colors, 20) # 20 interpolated colors
297
```
298
299
### Data Structure Processing
300
301
```python
302
from branca.utilities import iter_points, none_min, none_max
303
304
# Flatten nested coordinate structures
305
nested_coords = [[[1, 2], [3, 4]], [[5, 6]], [7, 8]]
306
flat_points = iter_points(nested_coords)
307
# Returns: [[1, 2], [3, 4], [5, 6], [7, 8]]
308
309
# Handle optional values
310
bounds = [
311
[none_min(1.0, None), none_min(2.0, 1.5)], # [1.0, 1.5]
312
[none_max(None, 3.0), none_max(4.0, 3.5)] # [3.0, 4.0]
313
]
314
```
315
316
### Custom Template Access
317
318
```python
319
from branca.utilities import get_templates
320
321
# Access branca template environment
322
env = get_templates()
323
template = env.get_template('color_scale.js')
324
rendered = template.render(colormap_data={'vmin': 0, 'vmax': 100})
325
```
326
327
## Type Definitions
328
329
```python { .api }
330
# Size parsing type for CSS dimensions
331
TypeParseSize = int | float | str | tuple[float, str]
332
```
333
334
## Internal Utility Functions
335
336
These functions are used internally by branca but may be useful for advanced customization:
337
338
```python { .api }
339
def _camelify(out: str) -> str:
340
"""Convert string to camelCase with underscores."""
341
342
def _parse_size(value) -> tuple[float, str]:
343
"""Parse size values to (number, unit) tuples."""
344
345
def _locations_mirror(x):
346
"""Mirror coordinate order in nested structures."""
347
348
def _locations_tolist(x):
349
"""Convert nested iterables to lists recursively."""
350
```
351
352
## Dependencies
353
354
The utilities module has the following optional dependencies:
355
356
- **numpy**: Required for `image_to_url()` and `write_png()` functions
357
- **jinja2**: Required for template functionality (already a branca dependency)
358
359
When numpy is not available, image processing functions will raise `ImportError` with helpful messages.