• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#    Copyright 2015-2017 ARM Limited
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
15
16"""Defines a generic indexable ColorMap Class"""
17import matplotlib.colors as clrs
18import matplotlib.cm as cmx
19from matplotlib.colors import ListedColormap, Normalize
20
21
22def to_dygraph_colors(color_map):
23    """Convert a color_map specified as a list of rgb tuples to the
24    syntax that dygraphs expect: ["rgb(1, 2, 3)", "rgb(4, 5, 6)",...]
25
26    :param color_map: a list of rgb tuples
27    :type color_map: list of tuples
28    """
29
30    rgb_list = ["rgb(" + ", ".join(str(i) for i in e) + ")" for e in color_map]
31
32    return '["' + '", "'.join(rgb_list) + '"]'
33
34class ColorMap(object):
35
36    """The Color Map Class to return a gradient method
37
38    :param num_colors: Number or colors for which a gradient
39        is needed
40    :type num_colors: int
41    """
42
43    def __init__(self, num_colors, cmap='hsv'):
44        self.color_norm = clrs.Normalize(vmin=0, vmax=num_colors)
45        self.scalar_map = cmx.ScalarMappable(norm=self.color_norm, cmap=cmap)
46        self.num_colors = num_colors
47
48    def cmap(self, index):
49        """
50        :param index: Index for the gradient array
51        :type index: int
52
53        :return: The color at specified index
54        """
55        return self.scalar_map.to_rgba(index)
56
57    def cmap_inv(self, index):
58        """
59        :param index: Index for the gradient array
60        :type index: int
61
62        :return: The color at :math:`N_{colors} - i`
63        """
64        return self.cmap(self.num_colors - index)
65
66    @classmethod
67    def rgb_cmap(cls, rgb_list):
68        """Constructor for a ColorMap from an rgb_list
69
70        :param rgb_list: A list of rgb tuples for red, green and blue.
71            The rgb values should be in the range 0-255.
72        :type rgb_list: list of tuples
73        """
74
75        rgb_list = [[x / 255.0 for x in rgb[:3]] for rgb in rgb_list]
76
77        rgb_map = ListedColormap(rgb_list, name='default_color_map', N=None)
78        num_colors = len(rgb_list)
79
80        return cls(num_colors, cmap=rgb_map)
81