Provides different colormaps for different visualization types.
499843
def get_freesurfer_cmap(vis_type):
    """"""

    if vis_type in ('cortical_volumetric', 'cortical_contour'):
            LUT = get_freesurfer_cortical_LUT()
            cmap = ListedColormap(LUT)
    elif vis_type in ('labels_volumetric', 'labels_contour'):
        black = np.array([0, 0, 0, 1])
        cmap = plt.get_cmap('hsv')
        # TODO using more than 20 labels might be a problem?
        cmap = cmap(np.linspace(0, 1, 20))
        # prepending black to paint background as black
        colors = np.vstack((black, cmap))
        cmap = ListedColormap(colors, 'my_colormap')
    else:
        raise NotImplementedError('color map for the visualization type {} has not been implemented!'.format(vis_type))

    return cmap
812810
def _map_val2color(val, vmin, vmax, colorscale=None):
    
    colorscale = colorscale or colorscale_default

    if vmin >= vmax:
        raise ValueError("vmin should be < vmax")

    scale = list(map(float, np.array(colorscale)[:, 0]))
    colors = np.array(colorscale)[:, 1]

    colors_01 = (
        np.array(list(map(literal_eval, [color[3:] for color in colors]))) / 255.0
    )

    v = (val - vmin) / float((vmax - vmin))  # val is mapped to v in[0,1]

    idx = 0
    # sequential search for the two   consecutive indices idx, idx+1 such that
    # v belongs to the interval  [scale[idx], scale[idx+1]
    while v > scale[idx + 1]:
        idx += 1
    left_scale_val = scale[idx]
    right_scale_val = scale[idx + 1]
    vv = (v - left_scale_val) / (right_scale_val - left_scale_val)

    # get the triplet of three values in [0,1] that represent the rgb color
    # corresponding to val
    val_color01 = colors_01[idx] + vv * (colors_01[idx + 1] - colors_01[idx])
    val_color_0255 = list(map(np.uint8, 255 * val_color01))

    return "rgb" + str(tuple(val_color_0255))
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)
943642
def color_map(lookup, color_stops, default_color='rgb(122,122,122)'):
    
    # if no color_stops, use default color
    if len(color_stops) == 0:
        return default_color
    
    # dictionary to lookup color from match-type color_stops
    match_map = dict((x, y) for (x, y) in color_stops)

    # if lookup matches stop exactly, return corresponding color (first priority)
    # (includes non-numeric color_stop "keys" for finding color by match)
    if lookup in match_map.keys():
        return match_map.get(lookup)

    # if lookup value numeric, map color by interpolating from color scale
    if isinstance(lookup, (int, float, complex)):

        # try ordering stops 
        try:
            stops, colors = zip(*sorted(color_stops))
        
        # if not all stops are numeric, attempt looking up as if categorical stops
        except TypeError:
            return match_map.get(lookup, default_color)

        # for interpolation, all stops must be numeric
        if not all(isinstance(x, (int, float, complex)) for x in stops):
            return default_color

        # check if lookup value in stops bounds
        if float(lookup) <= stops[0]:
            return colors[0]
        
        elif float(lookup) >= stops[-1]:
            return colors[-1]
        
        # check if lookup value matches any stop value
        elif float(lookup) in stops:
            return colors[stops.index(lookup)]
        
        # interpolation required
        else:

            rgb_tuples = [Color(rgb_tuple_from_str(x)) for x in colors]

            # identify bounding color stop values
            lower = max([stops[0]] + [x for x in stops if x < lookup])
            upper = min([stops[-1]] + [x for x in stops if x > lookup])
            
            # colors from bounding stops
            lower_color = rgb_tuples[stops.index(lower)]
            upper_color = rgb_tuples[stops.index(upper)]
            
            # generate color scale for mapping lookup value to interpolated color
            scale = Scale(Color(lower_color), Color(upper_color))

            # compute linear "relative distance" from lower bound color to upper bound color
            distance = (lookup - lower) / (upper - lower)

            # return string representing rgb color value
            return scale(distance).to_string().replace(', ', ',')

    # default color value catch-all
    return default_color
280935
def _setColors(self, colors, doc, xref):
        """"""
        return _fitz.Link__setColors(self, colors, doc, xref)
315701
def rgb(self, color_tuple):
        """"""
        # Check bounds
        self.color = tuple(map(self._apply_float_bounds, color_tuple[:3]))

        # Include alpha if necessary
        if len(color_tuple) > 3:
            self.alpha = self._apply_float_bounds(color_tuple[3])
1354385
def editColormap(self):
        """"""
        self.editor = pg.ImageView()
        # remove the ROI and Norm buttons
        self.editor.ui.roiBtn.setVisible(False)
        self.editor.ui.menuBtn.setVisible(False)
        self.editor.setImage(self.imageArray)
        if self.imgArgs['state'] is not None:
            self.editor.getHistogramWidget().item.gradient.restoreState(self.imgArgs['state'])
            self.editor.getHistogramWidget().item.setLevels(*self.imgArgs['levels'])
        
        self.editor.closeEvent = self._editor_close
        self.editor.setWindowModality(QtCore.Qt.ApplicationModal)
        self.editor.show()
273997
def palettebar(height, length, colormap):
    
    cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
    cbar = (cbar * (colormap.values.max() + 1 - colormap.values.min())
            + colormap.values.min())

    return colormap.palettize(cbar)
482363
function convertToFalseColorImage (element, colormap) {
  const enabledElement = getEnabledElement(element);


  return convertImageToFalseColorImage(enabledElement.image, colormap);
}
136329
def make_colormap(seq):
    
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)
859208
def generateDefaultColorRamp(cls, colorRampEnum):
        
        hue = [(255, 0, 255), (231, 0, 255), (208, 0, 255), (185, 0, 255), (162, 0, 255), (139, 0, 255), (115, 0, 255), (92, 0, 255), (69, 0, 255), (46, 0, 255), (23, 0, 255),        # magenta to blue
                   (0, 0, 255), (0, 23, 255), (0, 46, 255), (0, 69, 255), (0, 92, 255), (0, 115, 255), (0, 139, 255), (0, 162, 255), (0, 185, 255), (0, 208, 255), (0, 231, 255),          # blue to cyan
                   (0, 255, 255), (0, 255, 231), (0, 255, 208), (0, 255, 185), (0, 255, 162), (0, 255, 139), (0, 255, 115), (0, 255, 92), (0, 255, 69), (0, 255, 46), (0, 255, 23),        # cyan to green
                   (0, 255, 0), (23, 255, 0), (46, 255, 0), (69, 255, 0), (92, 255, 0), (115, 255, 0), (139, 255, 0), (162, 255, 0), (185, 255, 0), (208, 255, 0), (231, 255, 0),          # green to yellow
                   (255, 255, 0), (255, 243, 0), (255, 231, 0), (255, 220, 0), (255, 208, 0), (255, 197, 0), (255, 185, 0), (255, 174, 0), (255, 162, 0), (255, 151, 0), (255, 139, 0),    # yellow to orange
                   (255, 128, 0), (255, 116, 0), (255, 104, 0), (255, 93, 0), (255, 81, 0), (255, 69, 0), (255, 58, 0), (255, 46, 0), (255, 34, 0), (255, 23, 0), (255, 11, 0),            # orange to red
                   (255, 0, 0)]                                                                                                                                                            # red

        terrain = [(0, 100, 0), (19, 107, 0), (38, 114, 0), (57, 121, 0), (76, 129, 0), (95, 136, 0), (114, 143, 0), (133, 150, 0), (152, 158, 0), (171, 165, 0), (190, 172, 0),                   # dark green to golden rod yellow
                   (210, 180, 0), (210, 167, 5), (210, 155, 10), (210, 142, 15), (210, 130, 20), (210, 117, 25),                                                                                   # golden rod yellow to orange brown
                   (210, 105, 30), (188, 94, 25), (166, 83, 21), (145, 72, 17), (123, 61, 13), (101, 50, 9),                                                                                       # orange brown to dark brown
                   (80, 40, 5), (95, 59, 27), (111, 79, 50), (127, 98, 73), (143, 118, 95), (159, 137, 118),(175, 157, 141), (191, 176, 164), (207, 196, 186), (223, 215, 209), (239, 235, 232),   # dark brown to white
                   (255, 255, 255)]                                                                                                                                                                # white

        aqua = [(150, 255, 255), (136, 240, 250), (122, 226, 245), (109, 212, 240), (95, 198, 235), (81, 184, 230), (68, 170, 225), (54, 156, 220), (40, 142, 215), (27, 128, 210), (13, 114, 205), # aqua to blue
                (0, 100, 200), (0, 94, 195), (0, 89, 191), (0, 83, 187), (0, 78, 182), (0, 72, 178), (0, 67, 174), (0, 61, 170), (0, 56, 165), (0, 50, 161), (0, 45, 157), (0, 40, 153),            # blue to navy blue
                (0, 36, 143), (0, 32, 134), (0, 29, 125), (0, 25, 115), (0, 21, 106), (0, 18, 97), (0, 14, 88), (0, 10, 78), (0, 7, 69), (0, 3, 60), (0, 0, 51)]                                    # navy blue to dark navy blue


        if (colorRampEnum == ColorRampEnum.COLOR_RAMP_HUE):
            return hue

        elif (colorRampEnum == ColorRampEnum.COLOR_RAMP_TERRAIN):
            return terrain

        elif (colorRampEnum == ColorRampEnum.COLOR_RAMP_AQUA):
            return aqua
943799
def color_worker(srcs, window, ij, args):
    """"""
    src = srcs[0]
    arr = src.read(window=window)
    arr = to_math_type(arr)

    for func in parse_operations(args["ops_string"]):
        arr = func(arr)

    # scaled 0 to 1, now scale to outtype
    return scale_dtype(arr, args["out_dtype"])
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
1222654
def custom_line_color_map(self, values):
        
        if not isinstance(values, list):
            raise TypeError("custom_line_color_map must be a list")

        self.options["custom_line_color_map"] = values
214029
function (ui, context) {
					var active = color.active;
					if (context != colorMap && active.val() == null) return;
					var xy = ui.val('all');
					switch (settings.color.mode) {
					case 'h':
						active.val('sv', {
							s: xy.x,
							v: 100 - xy.y
						}, context);
						break;
					case 's':
					case 'a':
						active.val('hv', {
							h: xy.x,
							v: 100 - xy.y
						}, context);
						break;
					case 'v':
						active.val('hs', {
							h: xy.x,
							s: 100 - xy.y
						}, context);
						break;
					case 'r':
						active.val('gb', {
							g: 255 - xy.y,
							b: xy.x
						}, context);
						break;
					case 'g':
						active.val('rb', {
							r: 255 - xy.y,
							b: xy.x
						}, context);
						break;
					case 'b':
						active.val('rg', {
							r: xy.x,
							g: 255 - xy.y
						}, context);
						break;
					}
				}
980883
def _create_ansi_color_dict(color_cls):
    "  "
    return {
        'ansidefault':   color_cls.BLACK,
        'ansiblack':     color_cls.BLACK,
        'ansidarkgray':  color_cls.BLACK | color_cls.INTENSITY,
        'ansilightgray': color_cls.GRAY,
        'ansiwhite':     color_cls.GRAY | color_cls.INTENSITY,
        
        # Low intensity.
        'ansidarkred':     color_cls.RED,
        'ansidarkgreen':   color_cls.GREEN,
        'ansibrown':       color_cls.YELLOW,
        'ansidarkblue':    color_cls.BLUE,
        'ansipurple':      color_cls.MAGENTA,
        'ansiteal':        color_cls.CYAN,

        # High intensity.
        'ansired':        color_cls.RED | color_cls.INTENSITY,
        'ansigreen':      color_cls.GREEN | color_cls.INTENSITY,
        'ansiyellow':     color_cls.YELLOW | color_cls.INTENSITY,
        'ansiblue':       color_cls.BLUE | color_cls.INTENSITY,
        'ansifuchsia':    color_cls.MAGENTA | color_cls.INTENSITY,
        'ansiturquoise':  color_cls.CYAN | color_cls.INTENSITY,
    }
446450
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.channels[1]
        else:
            alpha = None
        self.channels = colormap.colorize(self.channels[0])
        if alpha is not None:
            self.channels.append(alpha)
            self.mode = "RGBA"
        else:
            self.mode = "RGB"