-
Notifications
You must be signed in to change notification settings - Fork 63
/
colormap.py
483 lines (407 loc) · 17.4 KB
/
colormap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
"""
Colormap
--------
Utility module for dealing with colormaps.
"""
import json
import math
import os
from jinja2 import Template
from branca.element import ENV, Figure, JavascriptLink, MacroElement
from branca.utilities import legend_scaler
rootpath = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(rootpath, '_cnames.json')) as f:
_cnames = json.loads(f.read())
with open(os.path.join(rootpath, '_schemes.json')) as f:
_schemes = json.loads(f.read())
def _is_hex(x):
return x.startswith('#') and len(x) == 7
def _parse_hex(color_code):
return (int(color_code[1:3], 16),
int(color_code[3:5], 16),
int(color_code[5:7], 16))
def _parse_color(x):
if isinstance(x, (tuple, list)):
color_tuple = tuple(x)[:4]
elif isinstance(x, (str, bytes)) and _is_hex(x):
color_tuple = _parse_hex(x)
elif isinstance(x, (str, bytes)):
cname = _cnames.get(x.lower(), None)
if cname is None:
raise ValueError('Unknown color {!r}.'.format(cname))
color_tuple = _parse_hex(cname)
else:
raise ValueError('Unrecognized color code {!r}'.format(x))
if max(color_tuple) > 1.:
color_tuple = tuple(u/255. for u in color_tuple)
return tuple(map(float, (color_tuple+(1.,))[:4]))
def _base(x):
if x > 0:
base = pow(10, math.floor(math.log10(x)))
return round(x/base)*base
else:
return 0
class ColorMap(MacroElement):
"""A generic class for creating colormaps.
Parameters
----------
vmin: float
The left bound of the color scale.
vmax: float
The right bound of the color scale.
caption: str
A caption to draw with the colormap.
max_labels : int, default 10
Maximum number of legend tick labels
"""
_template = ENV.get_template('color_scale.js')
def __init__(self, vmin=0., vmax=1., caption='', max_labels=10):
super(ColorMap, self).__init__()
self._name = 'ColorMap'
self.vmin = vmin
self.vmax = vmax
self.caption = caption
self.index = [vmin, vmax]
self.max_labels = max_labels
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
self.color_domain = [self.vmin + (self.vmax-self.vmin) * k/499. for
k in range(500)]
self.color_range = [self.__call__(x) for x in self.color_domain]
self.tick_labels = legend_scaler(self.index, self.max_labels)
super(ColorMap, self).render(**kwargs)
figure = self.get_root()
assert isinstance(figure, Figure), ('You cannot render this Element '
'if it is not in a Figure.')
figure.header.add_child(JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"), name='d3') # noqa
def rgba_floats_tuple(self, x):
"""
This class has to be implemented for each class inheriting from
Colormap. This has to be a function of the form float ->
(float, float, float, float) describing for each input float x,
the output color in RGBA format;
Each output value being between 0 and 1.
"""
raise NotImplementedError
def rgba_bytes_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with int values between 0 and 255.
"""
return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))
def rgb_bytes_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B) with int values between 0 and 255.
"""
return self.rgba_bytes_tuple(x)[:3]
def rgb_hex_str(self, x):
"""Provides the color corresponding to value `x` in the
form of a string of hexadecimal values "#RRGGBB".
"""
return '#%02x%02x%02x' % self.rgb_bytes_tuple(x)
def rgba_hex_str(self, x):
"""Provides the color corresponding to value `x` in the
form of a string of hexadecimal values "#RRGGBBAA".
"""
return '#%02x%02x%02x%02x' % self.rgba_bytes_tuple(x)
def __call__(self, x):
"""Provides the color corresponding to value `x` in the
form of a string of hexadecimal values "#RRGGBBAA".
"""
return self.rgba_hex_str(x)
def _repr_html_(self):
return (
'<svg height="50" width="500">' +
''.join(
[('<line x1="{i}" y1="0" x2="{i}" '
'y2="20" style="stroke:{color};stroke-width:3;" />').format(
i=i*1,
color=self.rgba_hex_str(
self.vmin +
(self.vmax-self.vmin)*i/499.)
)
for i in range(500)]) +
'<text x="0" y="35">{}</text>'.format(self.vmin) +
'<text x="500" y="35" style="text-anchor:end;">{}</text>'.format(
self.vmax) +
'</svg>')
class LinearColormap(ColorMap):
"""Creates a ColorMap based on linear interpolation of a set of colors
over a given index.
Parameters
----------
colors : list-like object with at least two colors.
The set of colors to be used for interpolation.
Colors can be provided in the form:
* tuples of RGBA ints between 0 and 255 (e.g: `(255, 255, 0)` or
`(255, 255, 0, 255)`)
* tuples of RGBA floats between 0. and 1. (e.g: `(1.,1.,0.)` or
`(1., 1., 0., 1.)`)
* HTML-like string (e.g: `"#ffff00`)
* a color name or shortcut (e.g: `"y"` or `"yellow"`)
index : list of floats, default None
The values corresponding to each color.
It has to be sorted, and have the same length as `colors`.
If None, a regular grid between `vmin` and `vmax` is created.
vmin : float, default 0.
The minimal value for the colormap.
Values lower than `vmin` will be bound directly to `colors[0]`.
vmax : float, default 1.
The maximal value for the colormap.
Values higher than `vmax` will be bound directly to `colors[-1]`.
max_labels : int, default 10
Maximum number of legend tick labels"""
def __init__(self, colors, index=None, vmin=0., vmax=1., caption='', max_labels=10):
super(LinearColormap, self).__init__(vmin=vmin, vmax=vmax,
caption=caption, max_labels=max_labels)
n = len(colors)
if n < 2:
raise ValueError('You must provide at least 2 colors.')
if index is None:
self.index = [vmin + (vmax-vmin)*i*1./(n-1) for i in range(n)]
else:
self.index = list(index)
self.colors = [_parse_color(x) for x in colors]
def rgba_floats_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1.
"""
if x <= self.index[0]:
return self.colors[0]
if x >= self.index[-1]:
return self.colors[-1]
i = len([u for u in self.index if u < x]) # 0 < i < n.
if self.index[i-1] < self.index[i]:
p = (x - self.index[i-1])*1./(self.index[i]-self.index[i-1])
elif self.index[i-1] == self.index[i]:
p = 1.
else:
raise ValueError('Thresholds are not sorted.')
return tuple((1.-p) * self.colors[i-1][j] + p*self.colors[i][j] for j
in range(4))
def to_step(self, n=None, index=None, data=None, method=None,
quantiles=None, round_method=None, max_labels=10):
"""Splits the LinearColormap into a StepColormap.
Parameters
----------
n : int, default None
The number of expected colors in the ouput StepColormap.
This will be ignored if `index` is provided.
index : list of floats, default None
The values corresponding to each color bounds.
It has to be sorted.
If None, a regular grid between `vmin` and `vmax` is created.
data : list of floats, default None
A sample of data to adapt the color map to.
method : str, default 'linear'
The method used to create data-based colormap.
It can be 'linear' for linear scale, 'log' for logarithmic,
or 'quant' for data's quantile-based scale.
quantiles : list of floats, default None
Alternatively, you can provide explicitely the quantiles you
want to use in the scale.
round_method : str, default None
The method used to round thresholds.
* If 'int', all values will be rounded to the nearest integer.
* If 'log10', all values will be rounded to the nearest
order-of-magnitude integer. For example, 2100 is rounded to
2000, 2790 to 3000.
max_labels : int, default 10
Maximum number of legend tick labels
Returns
-------
A StepColormap with `n=len(index)-1` colors.
Examples:
>> lc.to_step(n=12)
>> lc.to_step(index=[0, 2, 4, 6, 8, 10])
>> lc.to_step(data=some_list, n=12)
>> lc.to_step(data=some_list, n=12, method='linear')
>> lc.to_step(data=some_list, n=12, method='log')
>> lc.to_step(data=some_list, n=12, method='quantiles')
>> lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1])
>> lc.to_step(data=some_list, quantiles=[0, 0.3, 0.7, 1],
... round_method='log10')
"""
msg = 'You must specify either `index` or `n`'
if index is None:
if data is None:
if n is None:
raise ValueError(msg)
else:
index = [self.vmin + (self.vmax-self.vmin)*i*1./n for
i in range(1+n)]
scaled_cm = self
else:
max_ = max(data)
min_ = min(data)
scaled_cm = self.scale(vmin=min_, vmax=max_)
method = ('quantiles' if quantiles is not None
else method if method is not None
else 'linear'
)
if method.lower().startswith('lin'):
if n is None:
raise ValueError(msg)
index = [min_ + i*(max_-min_)*1./n for i in range(1+n)]
elif method.lower().startswith('log'):
if n is None:
raise ValueError(msg)
if min_ <= 0:
msg = ('Log-scale works only with strictly '
'positive values.')
raise ValueError(msg)
index = [math.exp(
math.log(min_) + i * (math.log(max_) -
math.log(min_)) * 1./n
) for i in range(1+n)]
elif method.lower().startswith('quant'):
if quantiles is None:
if n is None:
msg = ('You must specify either `index`, `n` or'
'`quantiles`.')
raise ValueError(msg)
else:
quantiles = [i*1./n for i in range(1+n)]
p = len(data)-1
s = sorted(data)
index = [s[int(q*p)] * (1.-(q*p) % 1) +
s[min(int(q*p) + 1, p)] * ((q*p) % 1) for
q in quantiles]
else:
raise ValueError('Unknown method {}'.format(method))
else:
scaled_cm = self.scale(vmin=min(index), vmax=max(index))
n = len(index)-1
if round_method == 'int':
index = [round(x) for x in index]
if round_method == 'log10':
index = [_base(x) for x in index]
colors = [scaled_cm.rgba_floats_tuple(index[i] * (1.-i/(n-1.)) +
index[i+1] * i/(n-1.)) for
i in range(n)]
caption = self.caption
return StepColormap(colors, index=index, vmin=index[0], vmax=index[-1], caption=caption,
max_labels=max_labels)
def scale(self, vmin=0., vmax=1., max_labels=10):
"""Transforms the colorscale so that the minimal and maximal values
fit the given parameters.
"""
return LinearColormap(
self.colors,
index=[vmin + (vmax-vmin)*(x-self.vmin)*1./(self.vmax-self.vmin) for x in self.index], # noqa
vmin=vmin,
vmax=vmax,
caption=self.caption,
max_labels=max_labels
)
class StepColormap(ColorMap):
"""Creates a ColorMap based on linear interpolation of a set of colors
over a given index.
Parameters
----------
colors : list-like object
The set of colors to be used for interpolation.
Colors can be provided in the form:
* tuples of int between 0 and 255 (e.g: `(255,255,0)` or
`(255, 255, 0, 255)`)
* tuples of floats between 0. and 1. (e.g: `(1.,1.,0.)` or
`(1., 1., 0., 1.)`)
* HTML-like string (e.g: `"#ffff00`)
* a color name or shortcut (e.g: `"y"` or `"yellow"`)
index : list of floats, default None
The values corresponding to each color.
It has to be sorted, and have the same length as `colors`.
If None, a regular grid between `vmin` and `vmax` is created.
vmin : float, default 0.
The minimal value for the colormap.
Values lower than `vmin` will be bound directly to `colors[0]`.
vmax : float, default 1.
The maximal value for the colormap.
Values higher than `vmax` will be bound directly to `colors[-1]`.
max_labels : int, default 10
Maximum number of legend tick labels
"""
def __init__(self, colors, index=None, vmin=0., vmax=1., caption='', max_labels=10):
super(StepColormap, self).__init__(vmin=vmin, vmax=vmax,
caption=caption, max_labels=max_labels)
n = len(colors)
if n < 1:
raise ValueError('You must provide at least 1 colors.')
if index is None:
self.index = [vmin + (vmax-vmin)*i*1./n for i in range(n+1)]
else:
self.index = list(index)
self.colors = [_parse_color(x) for x in colors]
def rgba_floats_tuple(self, x):
"""
Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1.
"""
if x <= self.index[0]:
return self.colors[0]
if x >= self.index[-1]:
return self.colors[-1]
i = len([u for u in self.index if u < x]) # 0 < i < n.
return tuple(self.colors[i-1])
def to_linear(self, index=None, max_labels=10):
"""
Transforms the StepColormap into a LinearColormap.
Parameters
----------
index : list of floats, default None
The values corresponding to each color in the output colormap.
It has to be sorted.
If None, a regular grid between `vmin` and `vmax` is created.
max_labels : int, default 10
Maximum number of legend tick labels
"""
if index is None:
n = len(self.index)-1
index = [self.index[i]*(1.-i/(n-1.))+self.index[i+1]*i/(n-1.) for
i in range(n)]
colors = [self.rgba_floats_tuple(x) for x in index]
return LinearColormap(colors, index=index,
vmin=self.vmin, vmax=self.vmax, max_labels=max_labels)
def scale(self, vmin=0., vmax=1., max_labels=10):
"""Transforms the colorscale so that the minimal and maximal values
fit the given parameters.
"""
return StepColormap(
self.colors,
index=[vmin + (vmax-vmin)*(x-self.vmin)*1./(self.vmax-self.vmin) for x in self.index], # noqa
vmin=vmin,
vmax=vmax,
caption=self.caption,
max_labels=max_labels
)
class _LinearColormaps(object):
"""A class for hosting the list of built-in linear colormaps."""
def __init__(self):
self._schemes = _schemes.copy()
self._colormaps = {key: LinearColormap(val) for
key, val in _schemes.items()}
for key, val in _schemes.items():
setattr(self, key, LinearColormap(val))
def _repr_html_(self):
return Template("""
<table>
{% for key,val in this._colormaps.items() %}
<tr><td>{{key}}</td><td>{{val._repr_html_()}}</td></tr>
{% endfor %}</table>
""").render(this=self)
linear = _LinearColormaps()
class _StepColormaps(object):
"""A class for hosting the list of built-in step colormaps."""
def __init__(self):
self._schemes = _schemes.copy()
self._colormaps = {key: StepColormap(val) for
key, val in _schemes.items()}
for key, val in _schemes.items():
setattr(self, key, StepColormap(val))
def _repr_html_(self):
return Template("""
<table>
{% for key,val in this._colormaps.items() %}
<tr><td>{{key}}</td><td>{{val._repr_html_()}}</td></tr>
{% endfor %}</table>
""").render(this=self)
step = _StepColormaps()