/
colortools.py
2407 lines (2237 loc) · 105 KB
/
colortools.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Registers colormaps, color cycles, and color string names with
`register_cmaps`, `register_cycles`, and `register_colors`.
Defines tools for creating new colormaps and color cycles, i.e. `colormap`
and `colors`. Defines helpful new `~matplotlib.colors.Normalize` and
`~matplotlib.colors.Colormap` classes.
For a visual reference, see the :ref:`Table of colormaps`,
:ref:`Table of color cycles`, and the :ref:`Table of colors`.
Perceptually uniform colormaps
------------------------------
ProPlot's custom colormaps are instances of the new
`PerceptuallyUniformColormap` class. These classes employ *linear transitions*
between channel values in any of three possible "perceptually uniform",
HSV-like colorspaces. These colorspaces can be described as follows (see also
`these visualizations <http://www.hsluv.org/comparison/>`_):
* **HCL**: A purely perceptually uniform colorspace, where colors are
broken down into “hue” (color, range 0-360), “chroma”
(colorfulness, range 0-100), and “luminance” (brightness, range 0-100).
* **HPLuv**: As with HCL, but 100 chroma is scaled to be the *minimum maximum
chroma* across all hues for a given luminance, and is hence more
appropriate for multi-hue colormaps.
* **HSLuv**: As with HCL, but 100 chroma is scaled to be the *maximum
possible chroma* for a given hue and luminance. This is more appropriate for
single-hue colormaps, because crossing hues in
this space make it more likely that bands of higher absolute chroma are
crossed.
The HCL space is the only "purely" perceptually uniform colorspace. But
during a linear transition between two values, we may cross over "impossible"
colors (i.e. colors with RGB channels >1).
The HSLuv and HPLuv colorspaces
were developed to resolve this issue by (respectively) scaling and clipping
high-chroma colors across different hues and luminances.
From other projects
-------------------
I’ve removed some outdated “miscellaneous” colormaps that are packaged
by default (see `this reference
<https://matplotlib.org/examples/color/colormaps_reference.html>`_)
and added new "perceptually uniform" colormaps from the following projects:
* The `cmOcean project <https://matplotlib.org/cmocean/>`_
* The `SciVisColor project <https://sciviscolor.org/home/colormaps/>`_
* `Kenneth Moreland's colormaps <http://soliton.vm.bytemark.co.uk/pub/cpt-city/km/index.html>`_
* `Fabio Crameri's colormaps <http://www.fabiocrameri.ch/colourmaps.php>`_
* Colormaps commissioned by `Statistik Stadt Zürich
<http://soliton.vm.bytemark.co.uk/pub/cpt-city/ssz/index.html>`_
* Peter Koveski's `CET colormaps <https://peterkovesi.com/projects/colourmaps/>`_
Several of these were found thanks to `Riley X. Bradey
<https://github.com/bradyrx>`_. Others were found using the `cpt-city
<http://soliton.vm.bytemark.co.uk/pub/cpt-city/>`_ archive of color
gradients.
Note that matplotlib comes packaged with every `ColorBrewer2.0
<http://colorbrewer2.org/>`__ colormap, which are also certainly
"perceptually uniform".
Flexible colormap arguments
---------------------------
All of the `~matplotlib.axes.Axes` methods listed in
`~proplot.axes.cmap_methods` and
`~proplot.axes.cycle_methods` have been wrapped by ProPlot. For the
latter methods, ProPlot adds a brand new keyword arg called ``cycle``, used for
changing the axes property cycler on-the-fly.
The ``cmap`` and ``cycle`` arguments
are all passed through the magical `Colormap` function.
`Colormap` is incredibly powerful -- it can make colormaps
on-the-fly, look up existing maps, and merge them. As such, any of the following
are now valid ``cmap`` and ``cycle`` arguments:
1. Registered colormap names. For example, ``'Blues'`` or ``'Sunset'``.
See :ref:`Table of colormaps` for a visalization of the registered maps.
Cycles are constructed automatically by sampling colors from these colormaps;
use e.g. ``('Blues', 5)`` to specify the number of colors in the cycle.
2. Gradations of a single hue. For example, ``'maroon'`` creates colormap spanning
white to maroon, and ``'maroon90'`` spans from a 90% luminance pale red
color to maroon (see `~proplot.colors.Colormap`).
Cycles are again constructed automatically; use e.g. ``('maroon', 10)``
to specify the number of colors in the cycle.
3. Registered color cycle names. For example, ``'Cycle1'``. See
:ref:`Table of color cycles`
for a visualization of the registered cycles.
4. Lists of colors. For example, ``['red', 'blue', 'green']``.
This makes a `~matplotlib.colors.ListedColormap` map which can be trivially
used as a "color cycle".
5. Dictionary containing the keys ``'h'``, ``'s'``, and ``'l'``. This builds
a `PerceptuallyUniformColormap` using the
`~PerceptuallyUniformColormap.from_hsl` constructor.
6. **List of any of the above five arguments, to merge the resulting
colormaps.** For
example, use ``['viridis', 'navy']`` to merge the virids map with a colormap
spanning white to navy.
Note when assigning to the ``proplot.rc.cycle`` global setting (see
`~proplot.rcmod`), the argument is also interpreted as above. For example,
``proplot.rc.cycle = ('blue', 10)`` will construct a color cycle with 10 colors
ranging from white to blue.
"""
#------------------------------------------------------------------------------#
# Interesting cpt-city colormaps that did not use:
# * Considered Jim Mossman maps, but not very uniform.
# * Erik Jeschke grayscale ones are also neat, but probably not much
# scientific use.
# * Rafi 'sky' themes were pretty, but ultimately not useful.
# * Crumblingwalls also interesting, but too many/some are weird.
# * NCL gradients mostly ugly, forget them.
# * Piecrust design has interesting 'nature' colormaps, but they are
# not practical. Just added a couple astro ones (aurora, space, star).
# * Elvensword is cool, but most are pretty banded.
# Geographic ones not used:
# * Christian Heine geologic time maps are interesting, but again not
# uniform and not useful.
# * IBCA could have been good, but bathymetry has ugly jumps.
# * GMT maps also interesting, but non uniform.
# * Victor Huérfano Caribbean map almost useful, but has banding.
# * Christopher Wesson martian topo map sort of cool, but too pale.
# * Thomas Deweez has more topo colors, but kind of ugly.
# Geographic ones to be adapted:
# * ESRI seems to have best geographic maps.
# * Wiki schemes are also pretty good, but not great.
#------------------------------------------------------------------------------#
# Notes on 'channel-wise alpha':
# * Colormaps generated from HCL space (and cmOcean ones) are indeed perfectly
# perceptually uniform, but this still looks bad sometimes -- usually we
# *want* to focus on the *extremes*, so want to weight colors more heavily
# on the brighters/whiter part of the map! That's what the ColdHot map does,
# it's what most of the ColorBrewer maps do, and it's what ColorWizard does.
# * By default extremes are stored at end of *lookup table*, not as
# separate RGBA values (so look under cmap._lut, indexes cmap._i_over and
# cmap._i_under). You can verify that your cmap is using most extreme values
# by comparing high-resolution one to low-resolution one.
#------------------------------------------------------------------------------#
# Potential bottleneck, loading all this stuff?
# NO. Try using @timer on register functions, turns out worst is colormap
# one at 0.1 seconds. Just happens to be a big package, takes a bit to compile
# to bytecode (done every time module changed) then import.
#------------------------------------------------------------------------------#
# Here's some useful info on colorspaces
# https://en.wikipedia.org/wiki/HSL_and_HSV
# http://www.hclwizard.org/color-scheme/
# http://www.hsluv.org/comparison/ compares lch, hsluv (scaled lch), and hpluv (truncated lch)
# Info on the CIE conventions
# https://en.wikipedia.org/wiki/CIE_1931_color_space
# https://en.wikipedia.org/wiki/CIELUV
# https://en.wikipedia.org/wiki/CIELAB_color_space
# And some useful tools for creating colormaps and cycles
# https://nrlmry.navy.mil/TC.html
# http://help.mail.colostate.edu/tt_o365_imap.aspx
# http://schumacher.atmos.colostate.edu/resources/archivewx.php
# https://coolors.co/
# http://tristen.ca/hcl-picker/#/hlc/12/0.99/C6F67D/0B2026
# http://gka.github.io/palettes/#diverging|c0=darkred,deeppink,lightyellow|c1=lightyellow,lightgreen,teal|steps=13|bez0=1|bez1=1|coL0=1|coL1=1
# https://flowingdata.com/tag/color/
# http://tools.medialab.sciences-po.fr/iwanthue/index.php
# https://learntocodewith.me/posts/color-palette-tools/
#------------------------------------------------------------------------------
import os
import re
import json
import glob
from lxml import etree
from numbers import Number
import cycler
import warnings
import numpy as np
import numpy.ma as ma
import matplotlib.colors as mcolors
import matplotlib.cm as mcm
from matplotlib import rcParams # cannot import rcmod because rcmod import this!
from . import utils, colormath
from .utils import _default, _counter, ic
_data_user = os.path.join(os.path.expanduser('~'), '.proplot')
_data_cmaps = os.path.join(os.path.dirname(__file__), 'cmaps') # or parent, but that makes pip install distribution hard
_data_colors = os.path.join(os.path.dirname(__file__), 'colors') # or parent, but that makes pip install distribution hard
# Define some new palettes
# Note the default listed colormaps
_cycles_loaded = {}
_cycles_preset = {
# Default matplotlib v2
'default': ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'],
# Copied from stylesheets; stylesheets just add color themese from every possible tool, not already present as a colormap
'538': ['#008fd5', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#810f7c'],
'ggplot': ['#E24A33', '#348ABD', '#988ED5', '#777777', '#FBC15E', '#8EBA42', '#FFB5B8'],
# The default seaborn ones (excluded deep/muted/bright because thought they were unappealing)
'ColorBlind': ['#0072B2', '#D55E00', '#009E73', '#CC79A7', '#F0E442', '#56B4E9'],
'ColorBlind10': ["#0173B2", "#DE8F05", "#029E73", "#D55E00", "#CC78BC", "#CA9161", "#FBAFE4", "#949494", "#ECE133", "#56B4E9"], # versions with more colors
# From the website
'FlatUI': ["#3498db", "#e74c3c", "#95a5a6", "#34495e", "#2ecc71", "#9b59b6"],
# Created with online tools; add to this
# See: http://tools.medialab.sciences-po.fr/iwanthue/index.php
'Cinematic': [(51,92,103), (158,42,43), (255,243,176), (224,159,62), (84,11,14)],
'Cool': ["#6C464F", "#9E768F", "#9FA4C4", "#B3CDD1", "#C7F0BD"],
'Sugar': ["#007EA7", "#B4654A", "#80CED7", "#B3CDD1", "#003249"],
'Vibrant': ["#007EA7", "#D81159", "#B3CDD1", "#FFBC42", "#0496FF"],
'Office': ["#252323", "#70798C", "#DAD2BC", "#F5F1ED", "#A99985"],
'Industrial': ["#38302E", "#6F6866", "#788585", "#BABF95", "#CCDAD1"],
'Tropical': ["#0D3B66", "#F95738", "#F4D35E", "#FAF0CA", "#EE964B"],
'Intersection': ["#2B4162", "#FA9F42", "#E0E0E2", "#A21817", "#0B6E4F"],
'Field': ["#23395B", "#D81E5B", "#FFFD98", "#B9E3C6", "#59C9A5"],
}
# Color stuff
# Keep major color names, and combinations of those names
_distinct_colors_threshold = 0.09 # bigger number equals fewer colors
_distinct_colors_space = 'hcl' # register colors distinct in this space?
_exceptions_names = (
'sky blue', 'eggshell', 'sea blue', 'coral', 'tomato red', 'brick red', 'crimson',
'red orange', 'yellow orange', 'yellow green', 'blue green',
'blue violet', 'red violet',
)
_bad_names = '(' + '|'.join(( # filter these out; let's try to be professional here...
'shit', 'poo', 'pee', 'piss', 'puke', 'vomit', 'snot', 'booger',
)) + ')'
_sanitize_names = ( # replace regex (first entry) with second entry
('/', ' '), ("'s", ''), ('grey', 'gray'),
('pinky', 'pink'), ('greeny', 'green'),
('bluey', 'blue'),
('robin egg', 'robins egg'),
('egg blue', 'egg'),
(r'reddish', 'red'),
(r'purplish', 'purple'),
(r'bluish', 'blue'),
(r'ish\b', ''),
('bluegray', 'blue gray'),
('grayblue', 'gray blue'),
('lightblue', 'light blue')
)
_space_aliases = {
'rgb': 'rgb',
'hsv': 'hsv',
'hpl': 'hpl',
'hpluv': 'hpl',
'hsl': 'hsl',
'hsluv': 'hsl',
'hcl': 'hcl',
'lch': 'hcl',
}
_channel_idxs = {
'h': 0, 'hue': 0,
's': 1, 'saturation': 1,
'c': 1, 'chroma': 1,
'l': 2, 'luminance': 2,
'a': 3, 'alpha': 3,
}
# Names of builtin colormaps
# NOTE: Has support for 'x' coordinates in first column.
# NOTE: For 'alpha' column, must use a .rgba filename
# TODO: Better way to save colormap files.
_cmap_categories = {
# Your custom registered maps; this is a placeholder, meant to put these
# maps at the top of the colormap table
'User': [
],
# We keep these ones
'Matplotlib Originals': [
'viridis', 'plasma', 'inferno', 'magma', 'twilight',
],
# Assorted origin, but these belong together
'Grayscale': [
'Grays',
'Mono',
'GrayCycle',
],
# CET isoluminant maps
# See: https://peterkovesi.com/projects/colourmaps/
# All the others have better options
'Isoluminant': [
'Iso1', 'Iso2', 'Iso3',
'Phase', # these actually from cmocean
],
# Included ColorBrewer
'ColorBrewer2.0 Sequential': [
'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
'PuBu', 'PuBuGn', 'BuGn', 'GnBu', 'YlGnBu', 'YlGn'
],
# Added diverging versions
# See: http://soliton.vm.bytemark.co.uk/pub/cpt-city/jjg/polarity/index.html
# Other JJ Green maps weren't that great
# TODO: Add 'serated' maps? See: http://soliton.vm.bytemark.co.uk/pub/cpt-city/jjg/serrate/index.html
# TODO: Add tool for cutting center out of ***any*** colormap by ending
# with the _cut suffix or something?
'ColorBrewer2.0 Diverging': [
'Spectral', 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGY',
'RdBu', 'RdYlBu', 'RdYlGn',
],
# Custom maps
'ProPlot Sequential': [
'Glacial',
'Dusk',
'Bog', 'Verdant',
'Turquoise',
'Sunrise', 'Sunset', 'Fire',
'Golden'
],
# 'Vibrant'], # empty at first, fill automatically
'ProPlot Diverging': [
'IceFire', 'NegPos', 'BlueRed', 'PurplePink', 'DryWet', 'AltDryWet', 'LandSea'
],
# Other
# BlackBody2 is actually from Los Alamos, and a couple are from Kenneth's
# website, but organization is better this way.
'Misc Diverging': [
'bwr',
'CoolWarm',
'SoftCoolWarm',
'MutedCoolWarm',
'ColdHot',
# 'Temp', # too un-uniform
# 'BlackBody1', 'BlackBody2', 'BlackBody3', # 3rd one is actually sky theme from rafi
# 'Star',
# 'JMN', # James map; ugly, so deleted
# 'CubeHelix', 'SatCubeHelix',
# 'cividis',
# 'Aurora', 'Space', # from PIEcrust; not uniform, so deleted
# 'TemperatureJJG', # from JJG; ugly, so deleted
# 'Kindlmann', 'ExtendedKindlmann',
# 'Seismic', # note this one originally had hard boundaries/no interpolation
# 'MutedBio', 'DarkBio', # from: ???, maybe SciVisColor
],
# Statistik
# 'Statistik Stadt Zürich': [
'Zürich Muted': [
'MutedBlue', 'MutedRed', 'MutedDry', 'MutedWet',
'MutedBuRd', 'MutedBuRd_cut', 'MutedDryWet', 'MutedDryWet_cut',
],
# cmOcean
'cmOcean Sequential': [
'Oxy', 'Thermal', 'Dense', 'Ice', 'Haline',
'Deep', 'Algae', 'Tempo', 'Speed', 'Turbid', 'Solar', 'Matter',
'Amp',
],
'cmOcean Diverging': [
'Balance', 'Curl', 'Delta'
],
# SciVisColor
# Culled these because some were ugly
# Actually nevermind... point of these is to *combine* them, make
# stacked colormaps that highlight different things.
'SciVisColor Blues': [
'Blue0', 'Blue1', 'Blue2', 'Blue3', 'Blue4', 'Blue5', 'Blue6', 'Blue7', 'Blue8', 'Blue9', 'Blue10', 'Blue11',
],
'SciVisColor Greens': [
'Green1', 'Green2', 'Green3', 'Green4', 'Green5', 'Green6', 'Green7', 'Green8',
],
'SciVisColor Oranges': [
'Orange1', 'Orange2', 'Orange3', 'Orange4', 'Orange5', 'Orange6', 'Orange7', 'Orange8',
],
'SciVisColor Browns': [
'Brown1', 'Brown2', 'Brown3', 'Brown4', 'Brown5', 'Brown6', 'Brown7', 'Brown8', 'Brown9',
],
'SciVisColor Reds/Purples': [
'RedPurple1', 'RedPurple2', 'RedPurple3', 'RedPurple4', 'RedPurple5', 'RedPurple6', 'RedPurple7', 'RedPurple8',
],
# FabioCrameri
# See: http://www.fabiocrameri.ch/colourmaps.php
'Fabio Crameri Sequential': [
'Acton', 'Buda', 'Lajolla',
'Imola', 'Bamako', 'Nuuk', 'Davos', 'Oslo', 'Devon', 'Tokyo', 'Hawaii', 'Batlow',
'Turku', 'Bilbao', 'Lapaz',
],
'Fabio Crameri Diverging': [
'Roma', 'Broc', 'Cork', 'Vik', 'Oleron', 'Lisbon', 'Tofino', 'Berlin',
],
# Gross. These ones will be deleted.
'Alt Sequential': [
'binary', 'gist_yarg', 'gist_gray', 'gray', 'bone', 'pink',
'spring', 'summer', 'autumn', 'winter', 'cool', 'Wistia',
'multi', 'cividis',
'afmhot', 'gist_heat', 'copper'
],
'Alt Rainbow': [
'multi', 'cividis'
],
'Alt Diverging': [
'coolwarm', 'bwr', 'seismic'
],
'Miscellaneous Orig': [
'flag', 'prism', 'ocean', 'gist_earth', 'terrain', 'gist_stern',
'gnuplot', 'gnuplot2', 'CMRmap', 'brg', 'hsv', 'hot', 'rainbow',
'gist_rainbow', 'jet', 'nipy_spectral', 'gist_ncar', 'cubehelix',
],
# Kenneth Moreland
# See: http://soliton.vm.bytemark.co.uk/pub/cpt-city/km/index.html
# Soft coolwarm from: https://www.kennethmoreland.com/color-advice/
# 'Kenneth Moreland': [
# 'CoolWarm', 'MutedCoolWarm', 'SoftCoolWarm',
# 'BlueTan', 'PurpleOrange', 'CyanMauve', 'BlueYellow', 'GreenRed',
# ],
# 'Kenneth Moreland Sequential': [
# 'BlackBody', 'Kindlmann', 'ExtendedKindlmann',
# ],
# Los Alamos
# See: https://datascience.lanl.gov/colormaps.html
# Most of these have analogues in SciVisColor, previously added the few
# unique ones to Miscellaneous category
# 'Los Alamos Sequential': [
# 'MutedRainbow', 'DarkRainbow', 'MutedBlue', 'DeepBlue', 'BrightBlue', 'BrightGreen', 'WarmGray',
# ],
# 'Los Alamos Diverging': [
# 'MutedBlueGreen', 'DeepBlueGreen', 'DeepBlueGreenAsym', 'DeepColdHot', 'DeepColdHotAsym', 'ExtendedCoolWarm'
# ],
# Removed the "combo" maps (and ugly diverging ones) because these can
# be built in proplot with the Colormap tool!
# 'SciVisColor Diverging': [
# 'Div1', 'Div2', 'Div3', 'Div4', 'Div5'
# ],
# 'SciVisColor 3 Waves': [
# '3Wave1', '3Wave2', '3Wave3', '3Wave4', '3Wave5', '3Wave6', '3Wave7'
# ],
# 'SciVisColor 4 Waves': [
# '4Wave1', '4Wave2', '4Wave3', '4Wave4', '4Wave5', '4Wave6', '4Wave7'
# ],
# 'SciVisColor 5 Waves': [
# '5Wave1', '5Wave2', '5Wave3', '5Wave4', '5Wave5', '5Wave6'
# ],
# 'SciVisColor Waves': [
# '3Wave1', '3Wave2', '3Wave3',
# '4Wave1', '4Wave2', '4Wave3',
# '5Wave1', '5Wave2', '5Wave3',
# ],
# 'SciVisColor Inserts': [
# 'Insert1', 'Insert2', 'Insert3', 'Insert4', 'Insert5', 'Insert6', 'Insert7', 'Insert8', 'Insert9', 'Insert10'
# ],
# 'SciVisColor Thick Inserts': [
# 'ThickInsert1', 'ThickInsert2', 'ThickInsert3', 'ThickInsert4', 'ThickInsert5'
# ],
# 'SciVisColor Highlight': [
# 'Highlight1', 'Highlight2', 'Highlight3', 'Highlight4', 'Highlight5',
# ],
# Most of these were ugly, deleted them
# 'SciVisColor Outlier': [
# 'DivOutlier1', 'DivOutlier2', 'DivOutlier3', 'DivOutlier4',
# 'Outlier1', 'Outlier2', 'Outlier3', 'Outlier4'
# ],
# Duncan Agnew
# See: http://soliton.vm.bytemark.co.uk/pub/cpt-city/dca/index.html
# These are 1.0.5 through 1.4.0
# 'Duncan Agnew': [
# 'Alarm1', 'Alarm2', 'Alarm3', 'Alarm4', 'Alarm5', 'Alarm6', 'Alarm7'
# ],
# Elevation and bathymetry
# 'Geographic': [
# 'Bath1', # from XKCD; see: http://soliton.vm.bytemark.co.uk/pub/cpt-city/xkcd/tn/xkcd-bath.png.index.html
# 'Bath2', # from Tom Patterson; see: http://soliton.vm.bytemark.co.uk/pub/cpt-city/tp/index.html
# 'Bath3', # from: http://soliton.vm.bytemark.co.uk/pub/cpt-city/ibcso/tn/ibcso-bath.png.index.html
# 'Bath4', # ^^ same
# 'Geography4-1', # mostly ocean
# 'Geography5-4', # range must be -4000 to 5000
# 'Geography1', # from ???
# 'Geography2', # from: http://soliton.vm.bytemark.co.uk/pub/cpt-city/ngdc/tn/ETOPO1.png.index.html
# 'Geography3', # from: http://soliton.vm.bytemark.co.uk/pub/cpt-city/mby/tn/mby.png.index.html
# ],
}
# Categories to ignore/*delete* from dictionary because they suck donkey balls
_cmap_categories_delete = ['Alt Diverging', 'Alt Sequential', 'Alt Rainbow', 'Miscellaneous Orig']
# Slice indices that split up segments of names
# WARNING: Must add to this list manually! Not worth trying to generalize.
# List of string cmap names, and the indices where they can be broken into parts
_cmap_parts = {
# Diverging colorbrewer
'piyg': (None, 2, None),
'prgn': (None, 1, 2, None), # purple red green
'brbg': (None, 2, 3, None), # brown blue green
'puor': (None, 2, None),
'rdgy': (None, 2, None),
'rdbu': (None, 2, None),
'rdylbu': (None, 2, 4, None),
'rdylgn': (None, 2, 4, None),
# Other diverging
'coldhot': (None, 4, None),
'bwr': (None, 1, 2, None),
'icefire': (None, 3, None),
'negpos': (None, 3, None),
'bluered': (None, 4, None),
'purplepink': (None, 4, None),
'drywet': (None, 3, None),
'drierwetter': (None, 5, None),
'landsea': (None, 4, None),
}
# Tuple pairs of mirror image cmap names
_cmap_mirrors = [
(name, ''.join(reversed([name[slice(*idxs[i:i+2])] for i in range(len(idxs)-1)])),)
for name,idxs in _cmap_parts.items()
]
#------------------------------------------------------------------------------#
# Special classes
#------------------------------------------------------------------------------#
# Class for flexible color names
# WARNING: Matplotlib 'color' arguments are passed to to_rgba, which tries
# to read directly from cache and if that fails, tries to sanitize input.
# The sanitization raises error when encounters (colormap, idx) tuple. So
# we need to override the *cache* instead of color dictionary itself!
# WARNING: Builtin to_rgb tries to get cached colors as dict[name, alpha],
# resulting in key as (colorname, alpha) or ((R,G,B), alpha) tuple. Impossible
# to differentiate this from (cmapname, index) usage! Must do try except lookup
# into colormap dictionary every time. Don't want to do this for actual
# color dict for sake of speed, so we only wrap *cache* lookup. Also we try
# to avoid cmap lookup attempt whenever possible.
class ColorDictSpecial(dict):
"""Special dictionary that lets user draw single color tuples from
arbitrary colormaps or color cycles."""
def __getitem__(self, key):
"""
Either samples the color from a colormap or color cycle,
or calls the parent getitem to look up the color name.
For a **smooth colormap**, usage is e.g.
``color=('Blues', 0.8)`` -- the number should be between 0 and 1, and
indicates where to draw the color from the smooth colormap. For a
"listed" colormap, i.e. a **color cycle**, usage is e.g.
``color=('colorblind', 2)``. The number indicates the index in the
list of discrete colors.
These examples work with any matplotlib command that accepts
a ``color`` keyword arg.
"""
# Pull out alpha
# WARNING: Possibly fragile? Does this hidden behavior ever change?
# NOTE: This override doubles startup time 0.0001s to 0.0002s, probably ok.
if np.iterable(key) and len(key)==2:
key, alpha = key
if np.iterable(key) and len(key)==2 and \
isinstance(key[1], Number) and isinstance(key[0], str): # i.e. is not None; this is *very common*, so avoids lots of unnecessary lookups!
try:
cmap = mcm.cmap_d[key[0]]
except (TypeError, KeyError):
pass
else:
if isinstance(cmap, mcolors.ListedColormap):
return tuple(cmap.colors[key[1]]) # draw color from the list of colors, using index
else:
return tuple(cmap(key[1])) # interpolate color from colormap, using key in range 0-1
return super().__getitem__((key, alpha))
# Wraps the cache
class _ColorMappingOverride(mcolors._ColorMapping):
def __init__(self, mapping):
"""Wraps the cache."""
super().__init__(mapping)
self.cache = ColorDictSpecial({})
# Override default color name dictionary
if not isinstance(mcolors._colors_full_map, _ColorMappingOverride):
mcolors._colors_full_map = _ColorMappingOverride(mcolors._colors_full_map)
# List of colors with 'name' attribute
class CycleList(list):
"""Simply stores a list of colors, and adds a `name` attribute corresponding
to the registered name."""
def __repr__(self):
"""Wraps the string representation."""
return 'CycleList(' + super().__repr__() + ')'
def __init__(self, list_, name):
self.name = name
super().__init__(list_)
# Flexible colormap identification
class CmapDict(dict):
"""
Flexible, case-insensitive colormap identification. Replaces the
`matplotlib.cm.cmap_d` dictionary that stores registered colormaps.
Behaves like a dictionary, with three new features:
1. Names are case insensitive: ``'Blues'``, ``'blues'``, and ``'bLuEs'``
are all valid names for the "Blues" colormap.
2. "Reversed" colormaps are not stored directly: Requesting e.g.
``'Blues_r'`` will just look up ``'Blues'``, then return the result
of the `~matplotlib.colors.Colormap.reversed` method.
3. Diverging colormap names can be referenced by their "inverse" name.
For example, ``'BuRd'`` is equivalent to ``'RdBu_r'``, as are
``'BuYlRd'`` and ``'RdYlBu_r'``.
"""
def __init__(self, kwargs):
kwargs_filtered = {}
for key,value in kwargs.items():
if not isinstance(key, str):
raise KeyError(f'Invalid key {key}. Must be string.')
if key[-2:] != '_r': # don't need to store these!
kwargs_filtered[key.lower()] = value
super().__init__(kwargs_filtered)
# Helper functions
def _sanitize_key(self, key):
"""Sanitizes key name."""
# Try retrieving
if not isinstance(key, str):
raise ValueError(f'Invalid key {key}. Must be string.')
key = key.lower()
reverse = False
if key[-2:] == '_r':
key = key[:-2]
reverse = True
if not super().__contains__(key):
# Attempt to get 'mirror' key, maybe that's the one
# stored in colormap dict
key_mirror = key
for mirror in _cmap_mirrors:
try:
idx = mirror.index(key)
key_mirror = mirror[1 - idx]
except ValueError:
continue
if super().__contains__(key_mirror):
reverse = (not reverse)
key = key_mirror
# Return 'sanitized' key. Not necessarily in dictionary! Error
# will be raised further down the line if so.
if reverse:
key = key + '_r'
return key
def _getitem(self, key):
"""Get value, but skip key sanitization."""
reverse = False
if key[-2:] == '_r':
key = key[:-2]
reverse = True
value = super().__getitem__(key) # may raise keyerror
if reverse:
try:
value = value.reversed()
except AttributeError:
raise KeyError(f'Dictionary value in {key} must have reversed() method.')
return value
# Indexing and 'in' behavior
def __getitem__(self, key):
"""Sanitizes key, then queries dictionary."""
# Assume lowercase
key = self._sanitize_key(key)
return self._getitem(key)
def __setitem__(self, key, item):
"""Assigns lowercase."""
if not isinstance(key, str):
raise KeyError(f'Invalid key {key}. Must be string.')
return super().__setitem__(key.lower(), item)
def __contains__(self, item):
"""The 'in' behavior."""
try:
self.__getitem__(item)
return True
except KeyError:
return False
# Other methods
def get(self, key, *args):
"""Case-insensitive version of `dict.get`."""
# Get item
if len(args)>1:
raise ValueError(f'Accepts only 1-2 arguments (got {len(args)+1}).')
try:
if not isinstance(key, str):
raise KeyError(f'Invalid key {key}. Must be string.')
return self.__getitem__(key.lower())
except KeyError as key_error:
if args:
return args[0]
else:
raise key_error
def pop(self, key, *args):
"""Case-insensitive version of `dict.pop`."""
# Pop item
if len(args)>1:
raise ValueError(f'Accepts only 1-2 arguments (got {len(args)+1}).')
try:
key = self._sanitize_key(key)
value = self._getitem(key) # could raise error
del self[key]
except KeyError as key_error:
if args:
return args[0]
else:
raise key_error
return value
# Override default colormap dictionary
if not isinstance(mcm.cmap_d, CmapDict):
mcm.cmap_d = CmapDict(mcm.cmap_d)
#------------------------------------------------------------------------------#
# Color manipulation functions
#------------------------------------------------------------------------------#
def _get_space(space):
"""Verify requested colorspace is valid."""
space = _space_aliases.get(space, None)
if space is None:
raise ValueError(f'Unknown colorspace "{space}".')
return space
def _get_channel(color, channel, space='hsl'):
"""Gets hue, saturation, or luminance channel value from registered
string color name. The color name `color` can optionally be a string
with the format ``'color+x'`` or ``'color-x'``, where `x` specifies
the offset from the channel value."""
# Interpret channel
channel = _channel_idxs.get(channel, channel)
if callable(color) or isinstance(color, Number):
return color
if channel not in (0,1,2):
raise ValueError('Channel must be in [0,1,2].')
# Interpret string or RGB tuple
offset = 0
if isinstance(color, str):
regex = '([-+]\S*)$' # user can optionally offset from color; don't filter to just numbers, want to raise our own error if user messes up
match = re.search(regex, color)
if match:
try:
offset = float(match.group(0))
except ValueError:
raise ValueError(f'Invalid channel identifier "{color}".')
color = color[:match.start()]
return offset + to_xyz(to_rgb(color, 'rgb'), space)[channel]
def shade(color, shade=0.5):
"""Changes the "shade" of a color by scaling its luminance channel by `shade`."""
try:
color = mcolors.to_rgb(color) # ensure is valid color
except Exception:
raise ValueError(f'Invalid RGBA argument {color}. Registered colors are: {", ".join(mcolors._colors_full_map.keys())}.')
color = [*colormath.rgb_to_hsl(*color)]
color[2] = max([0, min([color[2]*shade, 100])]) # multiply luminance by this value
color = [*colormath.hsl_to_rgb(*color)]
return tuple(color)
def to_rgb(color, space='rgb'):
"""Generalization of matplotlib's `~matplotlib.colors.to_rgb`. Translates
colors from *any* colorspace to rgb. Also will convert color
strings to tuple. Inverse of `to_xyz`."""
# First the RGB input
# NOTE: Need isinstance here because strings stored in numpy arrays
# are actually subclasses thereof!
if isinstance(color, str):
try:
color = mcolors.to_rgb(color) # ensure is valid color
except Exception:
raise ValueError(f'Invalid RGBA argument {color}. Registered colors are: {", ".join(mcolors._colors_full_map.keys())}.')
elif space=='rgb':
color = color[:3] # trim alpha
if any(c>1 for c in color):
color = [c/255 for c in color] # scale to within 0-1
# Next the perceptually uniform versions
elif space=='hsv':
color = colormath.hsl_to_rgb(*color)
elif space=='hpl':
color = colormath.hpluv_to_rgb(*color)
elif space=='hsl':
color = colormath.hsluv_to_rgb(*color)
elif space=='hcl':
color = colormath.hcl_to_rgb(*color)
else:
raise ValueError('Invalid RGB value.')
return color
def to_xyz(color, space):
"""Translates from RGB space to colorspace `space`. Inverse of `to_rgb`."""
# Run tuple conversions
# NOTE: Don't pass color tuple, because we may want to permit out-of-bounds RGB values to invert conversion
if isinstance(color, str):
color = mcolors.to_rgb(color) # convert string
else:
color = color[:3]
if space=='hsv':
color = colormath.rgb_to_hsl(*color) # rgb_to_hsv would also work
elif space=='hpl':
color = colormath.rgb_to_hpluv(*color)
elif space=='hsl':
color = colormath.rgb_to_hsluv(*color)
elif space=='hcl':
color = colormath.rgb_to_hcl(*color)
elif space=='rgb':
pass
else:
raise ValueError(f'Invalid colorspace {space}.')
return color
#------------------------------------------------------------------------------#
# Helper functions
#------------------------------------------------------------------------------#
def _transform_cycle(color):
"""Transforms colors C0, C1, etc. into their corresponding color strings.
May be necessary trying to change the color cycler."""
# Optional exit
if not isinstance(color, str):
return color
elif not re.match('^C[0-9]$', color):
return color
# Transform color to actual cycle color
else:
cycler = rcParams['axes.prop_cycle'].by_key()
if 'color' not in cycler:
cycle = ['k']
else:
cycle = cycler['color']
return cycle[int(color[-1])]
def _clip_colors(colors, mask=True, gray=0.2, verbose=False):
"""
Clips impossible colors rendered in an HSl-to-RGB colorspace conversion.
Used by `PerceptuallyUniformColormap`. If `mask` is ``True``, impossible
colors are masked out
Parameters
----------
colors : list of length-3 tuples
The RGB colors.
mask : bool, optional
Whether to mask out (set to `gray` color) or clip (limit
range of each channel to 0-1) the out-of-range RGB channels.
gray : float, optional
The identical RGB channel values (gray color) to be used if `mask`
is ``True``.
verbose : bool, optional
Whether to print message if colors are clipped.
"""
# Notes:
# I could use `numpy.clip` (`matplotlib.colors` uses this under the hood),
# but we want to display messages. And anyway, premature efficiency is
# the root of all evil, we're manipulating like 1000 colors max here, so
# it's no big deal.
message = 'Invalid' if mask else 'Clipped'
colors = np.array(colors) # easier
under = (colors<0)
over = (colors>1)
if mask:
colors[(under | over)] = gray
else:
colors[under] = 0
colors[over] = 1
if verbose:
for i,name in enumerate('rgb'):
if under[:,i].any():
warnings.warn(f'{message} "{name}" channel (<0).')
if over[:,i].any():
warnings.warn(f'{message} "{name}" channel (>1).')
return colors
def _clip_cmap(cmap, left=None, right=None, name=None, N=None):
"""Helper function that cleanly divides linear segmented colormaps and
subsamples listed colormaps. Full documentation is in `Colormap`."""
# Bail out
if left is None and right is None:
return cmap
# Simple process for listed colormap, just truncate the colors
name = name or 'no_name'
if isinstance(cmap, mcolors.ListedColormap):
try:
return mcolors.ListedColormap(cmap.colors[left:right])
except Exception:
raise ValueError(f'Invalid slice {slice(left,right)} for listed colormap.')
# Trickier for segment data maps
# Initial stuff
left = left or 0
right = right or 1
# Resample the segmentdata arrays
data = {}
dict_ = {key:value for key,value in cmap._segmentdata.items() if 'gamma' not in key}
gammas = {'saturation':'gamma1', 'luminance':'gamma2'}
for key,xyy in dict_.items():
# Get coordinates
xyy = np.array(xyy)
x = xyy[:,0]
xleft, = np.where(x>left)
xright, = np.where(x<right)
if len(xleft)==0:
raise ValueError(f'Invalid x minimum {left}.')
if len(xright)==0:
raise ValueError(f'Invalid x maximum {right}.')
# Slice
# l is the first point where x>0 or x>left, should be at least 1
# r is the last point where r<1 or r<right
l, r = xleft[0], xright[-1]
ixyy = xyy[l:r+1,:].copy()
xl = xyy[l-1,1:] + (left - x[l-1])*(xyy[l,1:] - xyy[l-1,1:])/(x[l] - x[l-1])
ixyy = np.concatenate(([[left, *xl]], ixyy), axis=0)
xr = xyy[r,1:] + (right - x[r])*(xyy[r+1,1:] - xyy[r,1:])/(x[r+1] - x[r])
ixyy = np.concatenate((ixyy, [[right, *xr]]), axis=0)
ixyy[:,0] = (ixyy[:,0] - left)/(right - left)
data[key] = ixyy
# Retain the corresponding 'gamma' *segments*
# Need more testing but so far so good
if key in gammas:
gamma = cmap._segmentdata[gammas[key]]
if np.iterable(gamma):
gamma = gamma[l-1:r+1]
data[gammas[key]] = gamma
# And finally rebuild map
kwargs = {}
if hasattr(cmap, '_space'):
kwargs['space'] = cmap._space
return type(cmap)(name, data, N=cmap.N, **kwargs)
def _shift_cmap(cmap, shift=None, name=None):
"""Shift a cyclic colormap by `shift` degrees out of 360 degrees."""
# Bail out
if not shift:
return cmap
# Simple process for listed colormap, just rotate the colors
name = name or 'no_name'
if isinstance(cmap, mcolors.ListedColormap):
shift = shift % len(cmap.colors)
colors = [*cmap.colors] # ensure list
colors = colors[shift:] + colors[:shift]
return mcolors.ListedColormap(colors, name=name, N=len(colors))
# Trickier for smooth colormaps, must shift coordinates
# TODO: This won't work for lo-res colormaps or percpetually
# uniform maps with only a couple coordiante transitions, right?
data = cmap._segmentdata.copy()
for key,orig in cmap._segmentdata.items():
# Drop an end color
orig = np.array(orig)
orig = orig[1:,:]
array = orig.copy()
array[:,0] -= shift/360
array[:,0] %= 1
# Add end color back in
array = array[array[:,0].argsort(),:]
array = np.concatenate((array[-1:,:], array), axis=0)
array[:1,0] = array[1:2,0] - np.diff(array[1:3,0])
# Normalize x-range
array[:,0] -= array[:,0].min()
array[:,0] /= array[:,0].max()
data[key] = array
# Generate shifted colormap
cmap = mcolors.LinearSegmentedColormap(name, data, N=cmap.N)
cmap._cyclic = True
return cmap
def _merge_cmaps(*imaps, ratios=1, name=None, N=512, **kwargs):
"""Merges arbitrary colormaps. This is used when you pass multiple `imaps`
to the `Colormap` function. Full documentation is in `Colormap`."""
# Bail out
if len(imaps)==1:
return imaps[0]
types = {type(cmap) for cmap in imaps}
if len(types)!=1:
raise ValueError(f'Mixed colormap types {types}. Maps must all be LinearSegmentedColormap or PerceptuallyUniformColormap.')
type_ = types.pop()
# Simple process for listed colormap, just combine the colors
name = name or 'no_name'
if all(isinstance(cmap, mcolors.ListedColormap) for cmap in imaps):
colors = [color for cmap in imaps for color in cmap.colors]
return mcolors.ListedColormap(colors, name=name, N=len(colors))
# Tricker for smooth maps
# Initial stuff
kwargs = {}
segmentdata = {}
ratios = ratios or 1
if isinstance(ratios, Number):
ratios = [1]*len(imaps)
ratios = np.array(ratios)/np.sum(ratios) # so if 4 cmaps, will be 1/4
x0 = np.concatenate([[0], np.cumsum(ratios)])
xw = x0[1:] - x0[:-1] # weights for averages
# PerceptuallyUniformColormaps checks
if type_ is PerceptuallyUniformColormap:
spaces = {cmap._space for cmap in imaps}
if len(spaces)>1:
raise ValueError(f'Cannot merge colormaps in the different HSL spaces {repr(spaces)}.')
kwargs['space'] = spaces.pop()
gammas = {0:'saturation', 1:'luminance'}
for i,key in enumerate(('gamma1', 'gamma2')):
if key not in segmentdata:
segmentdata[key] = []