Color generator for Bokeh plots

    Parameters
    ----------
    colormap: str, sequence
        The name of the color map

    Returns
    -------
    generator
        A generator for the color palette
9407
def color_gen(colormap='viridis', key=None, n=15):
    
    if colormap in dir(bpal):
        palette = getattr(bpal, colormap)

        if isinstance(palette, dict):
            if key is None:
                key = list(palette.keys())[0]
            palette = palette[key]

        elif callable(palette):
            palette = palette(n)

        else:
            raise TypeError("pallette must be a bokeh palette name or a sequence of color hex values.")

    elif isinstance(colormap, (list, tuple)):
        palette = colormap

    else:
        raise TypeError("pallette must be a bokeh palette name or a sequence of color hex values.")

    yield from itertools.cycle(palette)
1166961
def build_colormap(palette, info):
        """"""

        from trollimage.colormap import Colormap
        if 'palette_meanings' in palette.attrs:
            palette_indices = palette.attrs['palette_meanings']
        else:
            palette_indices = range(len(palette))

        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        tups = [(val, tuple(tup))
                for (val, tup) in zip(palette_indices, sqpalette)]
        colormap = Colormap(*tups)
        if 'palette_meanings' not in palette.attrs:
            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *(np.array(info['valid_range']) * sf + info.get('add_offset', 0)))

        return colormap, sqpalette
916881
def color_map_data(self) -> typing.Optional[numpy.ndarray]:
        """"""
        if self.display_data_shape is None:  # is there display data?
            return None
        else:
            return self.__color_map_data if self.__color_map_data is not None else ColorMaps.get_color_map_data_by_id("grayscale")
1341048
def to_color(self):
        
        color_data = np.repeat(self.data[:,:,np.newaxis], 3, axis=2)
        return ColorImage(color_data, self._frame)
770840
def read_colormap(fh, byteorder, dtype, count, offsetsize):
    """"""
    cmap = fh.read_array(byteorder+dtype[-1], count)
    cmap.shape = (3, -1)
    return cmap
387202
def colorize(self, colormap):
        

        if self.mode not in ("L", "LA"):
            raise ValueError("Image should be grayscale to colorize")

        if self.mode == "LA":
            alpha = self.data.sel(bands=['A'])
        else:
            alpha = None

        l_data = self.data.sel(bands=['L'])

        def _colorize(l_data, colormap):
            # 'l_data' is (1, rows, cols)
            # 'channels' will be a list of 3 (RGB) or 4 (RGBA) arrays
            channels = colormap.colorize(l_data)
            return np.concatenate(channels, axis=0)

        new_data = l_data.data.map_blocks(_colorize, colormap,
                                          chunks=(colormap.colors.shape[1],) + l_data.data.chunks[1:],
                                          dtype=np.float64)

        if colormap.colors.shape[1] == 4:
            mode = "RGBA"
        elif alpha is not None:
            new_data = da.concatenate([new_data, alpha.data], axis=0)
            mode = "RGBA"
        else:
            mode = "RGB"

        # copy the coordinates so we don't affect the original
        coords = dict(self.data.coords)
        coords['bands'] = list(mode)
        attrs = self.data.attrs
        dims = self.data.dims
        self.data = xr.DataArray(new_data, coords=coords, attrs=attrs, dims=dims)
322108
def generateColorMap():
    '''
    
    '''
    Map = cm.jet(np.arange(256))
    stringColors = []
    for i in range(Map.shape[0]):
        rgb = (int(255*Map[i][0]), int(255*Map[i][1]), int(255*Map[i][2]))
        if (sys.version_info > (3, 0)):
            stringColors.append((struct.pack('BBB', *rgb).hex())) # python 3
        else:
            stringColors.append(
                struct.pack('BBB', *rgb).encode('hex'))  # python2

    return stringColors
1266211
def plot_phens(phen_grid, **kwargs):
    
    denom, palette = get_kwargs(phen_grid, kwargs, True)

    grid = color_grid(phen_grid, palette, denom)

    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if grid[i][j] != -1 and tuple(grid[i][j]) != -1:
                plt.gca().add_patch(plt.Circle((j, i),
                                    radius=.3, lw=1, ec="black",
                                    facecolor=grid[i][j], zorder=2))
1042100
def palettize(self, colormap):
        

        if self.mode not in ("L", "LA"):
            raise ValueError("Image should be grayscale to colorize")

        l_data = self.data.sel(bands=['L'])

        def _palettize(data):
            # returns data and palette, only need data
            return colormap.palettize(data)[0]

        new_data = l_data.data.map_blocks(_palettize, dtype=l_data.dtype)
        self.palette = tuple(colormap.colors)

        if self.mode == "L":
            mode = "P"
        else:
            mode = "PA"
            new_data = da.concatenate([new_data, self.data.sel(bands=['A'])], axis=0)

        self.data.data = new_data
        self.data.coords['bands'] = list(mode)
447365
def heatmap(w, vmin=None, vmax=None, diverge_color=False,
            ncol=1,
            plot_name=None, vocab=["A", "C", "G", "T"], figsize=(6, 2)):
    
    # Generate y and x values from the dimension lengths
    assert len(vocab) == w.shape[0]
    plt_y = np.arange(w.shape[0] + 1) + 0.5
    plt_x = np.arange(w.shape[1] + 1) - 0.5
    z_min = w.min()
    z_max = w.max()

    if vmin is None:
        vmin = z_min
    if vmax is None:
        vmax = z_max

    if diverge_color:
        color_map = plt.cm.RdBu
    else:
        color_map = plt.cm.Blues

    fig = plt.figure(figsize=figsize)
    # multiple axis
    if len(w.shape) == 3:
        #
        n_plots = w.shape[2]
        nrow = math.ceil(n_plots / ncol)
    else:
        n_plots = 1
        nrow = 1
        ncol = 1

    for i in range(n_plots):
        if len(w.shape) == 3:
            w_cur = w[:, :, i]
        else:
            w_cur = w
        ax = plt.subplot(nrow, ncol, i + 1)
        plt.tight_layout()
        im = ax.pcolormesh(plt_x, plt_y, w_cur, cmap=color_map,
                           vmin=vmin, vmax=vmax, edgecolors="white")
        ax.grid(False)
        ax.set_yticklabels([""] + vocab, minor=False)
        ax.yaxis.set_major_locator(MaxNLocator(integer=True))
        ax.set_xticks(np.arange(w_cur.shape[1] + 1))
        ax.set_xlim(plt_x.min(), plt_x.max())
        ax.set_ylim(plt_y.min(), plt_y.max())

        # nice scale location:
        # http://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        fig.colorbar(im, cax=cax)

        if plot_name is not None:
            if n_plots > 0:
                pln = plot_name + " {0}".format(i)
            else:
                pln = plot_name
            ax.set_title(pln)
        ax.set_aspect('equal')
    return fig
1263000
def build_colormap(palette, dtype, info):
        """"""
        from trollimage.colormap import Colormap
        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        if hasattr(palette, 'attrs') and 'palette_meanings' in palette.attrs:
            meanings = palette.attrs['palette_meanings']
            iterator = zip(meanings, sqpalette)
        else:
            iterator = enumerate(sqpalette[:-1])

        if dtype == np.dtype('uint8'):
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

        elif 'valid_range' in info:
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *info['valid_range'] * sf + info.get('add_offset', 0))

        return colormap, sqpalette
86842
def palettize(self, colormap):
        

        if self.mode not in ("L", "LA"):
            raise ValueError("Image should be grayscale to colorize")
        self.channels[0], self.palette = colormap.palettize(self.channels[0])
        if self.mode == "L":
            self.mode = "P"
        else:
            self.mode = "PA"
958509
def MWColorMapping(maptype='jet', reverse=True):
     
    d = {'A':89,'R':174,'N':132,'D':133,'C':121,'Q':146,'E':147,\
         'G':75,'H':155,'I':131,'L':131,'K':146,'M':149,'F':165,\
         'P':115,'S':105,'T':119,'W':204,'Y':181,'V':117}
    
    aas = sorted(AA_TO_INDEX.keys())
    mws  = [d[aa] for aa in aas]
    if reverse:
        mws = [-1 * x for x in mws]
    mapper = pylab.cm.ScalarMappable(cmap=maptype)
    mapper.set_clim(min(mws), max(mws))
    mapping_d = {'*':'#000000'}
    for (aa, h) in zip(aas, mws):
        tup = mapper.to_rgba(h, bytes=True)
        (red, green, blue, alpha) = tup
        mapping_d[aa] = '#%02x%02x%02x' % (red, green, blue)
        assert len(mapping_d[aa]) == 7
    cmap = mapper.get_cmap()
    return (cmap, mapping_d, mapper)
1143630
def _get_global_color_table(colors):
    
    global_color_table = b''.join(c[0] for c in colors.most_common())
    full_table_size = 2**(1+int(get_color_table_size(len(colors)), 2))
    repeats = 3 * (full_table_size - len(colors))
    zeros = struct.pack('<{}x'.format(repeats))
    return global_color_table + zeros
1136758
def load_colormap(self, name=None):
        

        if name == None: name = self.get_name()
        if name == "" or not type(name)==str: return "Error: Bad name."

        # assemble the path to the colormap
        path = _os.path.join(_settings.path_home, "colormaps", name+".cmap")

        # make sure the file exists
        if not _os.path.exists(path):
            print("load_colormap(): Colormap '"+name+"' does not exist. Creating.")
            self.save_colormap(name)
            return

        # open the file and get the lines
        f = open(path, 'r')
        x = f.read()
        f.close()

        try:
            self._colorpoint_list = eval(x)
        except:
            print("Invalid colormap. Overwriting.")
            self.save_colormap()

        # update the image
        self.update_image()

        return self
267982
def generateCustomColorRamp(cls, colors=[], interpolatedPoints=10):
        
        if not (isinstance(colors, list)):
            print('COLOR RAMP GENERATOR WARNING: colors must be passed in as a list of RGB tuples.')
            raise

        numColors = len(colors)

        colorRamp = []

        # Iterate over colors
        for index in range (0, numColors - 1):
            bottomColor = colors[index]
            topColor = colors[index + 1]

            colorRamp.append(bottomColor)

            # Calculate slopes
            rSlope = (topColor[0] - bottomColor[0]) / float(interpolatedPoints)
            gSlope = (topColor[1] - bottomColor[1]) / float(interpolatedPoints)
            bSlope = (topColor[2] - bottomColor[2]) / float(interpolatedPoints)

            # Interpolate colors
            for point in range(1, interpolatedPoints):
                red = int(rSlope * point + bottomColor[0])
                green = int(gSlope * point + bottomColor[1])
                blue = int(bSlope * point + bottomColor[2])
                color = (red, green, blue)

                # Make sure the color ramp contains unique colors
                if not (color in colorRamp):
                    colorRamp.append(color)

        # Append the last color
        colorRamp.append(colors[-1])

        return colorRamp
30811
def _get_cmap(kwargs: dict) -> colors.Colormap:
    
    from matplotlib.colors import ListedColormap

    cmap = kwargs.pop("cmap", default_cmap)
    if isinstance(cmap, list):
        return ListedColormap(cmap)
    if isinstance(cmap, str):
        try:
            cmap = plt.get_cmap(cmap)
        except BaseException as exc:
            try:
                # Try to use seaborn palette
                import seaborn as sns
                sns_palette = sns.color_palette(cmap, n_colors=256)
                cmap = ListedColormap(sns_palette, name=cmap)
            except ImportError:
                raise exc
    return cmap