Check if cmap is one of the colorbrewer maps
12757
def check_colormap(cmap):
    
    names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
                 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
                 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
                 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning'])
    if cmap not in names:
        raise Exception("Invalid cmap '%s',  must be one of %s" % (cmap, names))
    else:
        return cmap
887359
function readCmapTable(cmap, font, isSymbolicFont) {
        var segment;
        var start = (font.start ? font.start : 0) + cmap.offset;
        font.pos = start;

        var version = font.getUint16();
        var numTables = font.getUint16();

        var potentialTable;
        var canBreak = false;
        // There's an order of preference in terms of which cmap subtable to
        // use:
        // - non-symbolic fonts the preference is a 3,1 table then a 1,0 table
        // - symbolic fonts the preference is a 3,0 table then a 1,0 table
        // The following takes advantage of the fact that the tables are sorted
        // to work.
        for (var i = 0; i < numTables; i++) {
          var platformId = font.getUint16();
          var encodingId = font.getUint16();
          var offset = font.getInt32() >>> 0;
          var useTable = false;

          if (platformId === 0 && encodingId === 0) {
            useTable = true;
            // Continue the loop since there still may be a higher priority
            // table.
          } else if (platformId === 1 && encodingId === 0) {
            useTable = true;
            // Continue the loop since there still may be a higher priority
            // table.
          } else if (platformId === 3 && encodingId === 1 &&
                     (!isSymbolicFont || !potentialTable)) {
            useTable = true;
            if (!isSymbolicFont) {
              canBreak = true;
            }
          } else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
            useTable = true;
            canBreak = true;
          }

          if (useTable) {
            potentialTable = {
              platformId: platformId,
              encodingId: encodingId,
              offset: offset
            };
          }
          if (canBreak) {
            break;
          }
        }

        if (potentialTable) {
          font.pos = start + potentialTable.offset;
        }
        if (!potentialTable || font.peekByte() === -1) {
          warn('Could not find a preferred cmap table.');
          return {
            platformId: -1,
            encodingId: -1,
            mappings: [],
            hasShortCmap: false
          };
        }

        var format = font.getUint16();
        var length = font.getUint16();
        var language = font.getUint16();

        var hasShortCmap = false;
        var mappings = [];
        var j, glyphId;

        // TODO(mack): refactor this cmap subtable reading logic out
        if (format === 0) {
          for (j = 0; j < 256; j++) {
            var index = font.getByte();
            if (!index) {
              continue;
            }
            mappings.push({
              charCode: j,
              glyphId: index
            });
          }
          hasShortCmap = true;
        } else if (format === 4) {
          // re-creating the table in format 4 since the encoding
          // might be changed
          var segCount = (font.getUint16() >> 1);
          font.getBytes(6); // skipping range fields
          var segIndex, segments = [];
          for (segIndex = 0; segIndex < segCount; segIndex++) {
            segments.push({ end: font.getUint16() });
          }
          font.getUint16();
          for (segIndex = 0; segIndex < segCount; segIndex++) {
            segments[segIndex].start = font.getUint16();
          }

          for (segIndex = 0; segIndex < segCount; segIndex++) {
            segments[segIndex].delta = font.getUint16();
          }

          var offsetsCount = 0;
          for (segIndex = 0; segIndex < segCount; segIndex++) {
            segment = segments[segIndex];
            var rangeOffset = font.getUint16();
            if (!rangeOffset) {
              segment.offsetIndex = -1;
              continue;
            }

            var offsetIndex = (rangeOffset >> 1) - (segCount - segIndex);
            segment.offsetIndex = offsetIndex;
            offsetsCount = Math.max(offsetsCount, offsetIndex +
                                    segment.end - segment.start + 1);
          }

          var offsets = [];
          for (j = 0; j < offsetsCount; j++) {
            offsets.push(font.getUint16());
          }

          for (segIndex = 0; segIndex < segCount; segIndex++) {
            segment = segments[segIndex];
            start = segment.start;
            var end = segment.end;
            var delta = segment.delta;
            offsetIndex = segment.offsetIndex;

            for (j = start; j <= end; j++) {
              if (j === 0xFFFF) {
                continue;
              }

              glyphId = (offsetIndex < 0 ?
                         j : offsets[offsetIndex + j - start]);
              glyphId = (glyphId + delta) & 0xFFFF;
              if (glyphId === 0) {
                continue;
              }
              mappings.push({
                charCode: j,
                glyphId: glyphId
              });
            }
          }
        } else if (format === 6) {
          // Format 6 is a 2-bytes dense mapping, which means the font data
          // lives glue together even if they are pretty far in the unicode
          // table. (This looks weird, so I can have missed something), this
          // works on Linux but seems to fails on Mac so let's rewrite the
          // cmap table to a 3-1-4 style
          var firstCode = font.getUint16();
          var entryCount = font.getUint16();

          for (j = 0; j < entryCount; j++) {
            glyphId = font.getUint16();
            var charCode = firstCode + j;

            mappings.push({
              charCode: charCode,
              glyphId: glyphId
            });
          }
        } else {
          error('cmap table has unsupported format: ' + format);
        }

        // removing duplicate entries
        mappings.sort(function (a, b) {
          return a.charCode - b.charCode;
        });
        for (i = 1; i < mappings.length; i++) {
          if (mappings[i - 1].charCode === mappings[i].charCode) {
            mappings.splice(i, 1);
            i--;
          }
        }

        return {
          platformId: potentialTable.platformId,
          encodingId: potentialTable.encodingId,
          mappings: mappings,
          hasShortCmap: hasShortCmap
        };
      }
1305843
def plot_colormap_components(cmap):
    """"""
    from ._helpers import set_ax_labels  # recursive import protection

    plt.figure(figsize=[8, 4])
    gs = grd.GridSpec(3, 1, height_ratios=[1, 10, 1], hspace=0.05)
    # colorbar
    ax = plt.subplot(gs[0])
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.)
    ax.set_title(cmap.name, fontsize=20)
    ax.set_axis_off()
    # components
    ax = plt.subplot(gs[1])
    x = np.arange(cmap.N)
    colors = cmap(x)
    r = colors[:, 0]
    g = colors[:, 1]
    b = colors[:, 2]
    RGB_weight = [0.299, 0.587, 0.114]
    k = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
    r.clip(0, 1, out=r)
    g.clip(0, 1, out=g)
    b.clip(0, 1, out=b)
    xi = np.linspace(0, 1, x.size)
    plt.plot(xi, r, "r", linewidth=5, alpha=0.6)
    plt.plot(xi, g, "g", linewidth=5, alpha=0.6)
    plt.plot(xi, b, "b", linewidth=5, alpha=0.6)
    plt.plot(xi, k, "k", linewidth=5, alpha=0.6)
    ax.set_xlim(0, 1)
    ax.set_ylim(-0.1, 1.1)
    set_ax_labels(ax=ax, xlabel=None, xticks=False, ylabel="intensity")
    # grayified colorbar
    cmap = grayify_cmap(cmap)
    ax = plt.subplot(gs[2])
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.)
    ax.set_axis_off()
477580
def _list_cmaps(provider=None, records=False):
    
    if provider is None:
        provider = providers
    elif isinstance(provider, basestring):
        if provider not in providers:
            raise ValueError('Colormap provider %r not recognized, must '
                             'be one of %r' % (provider, providers))
        provider = [provider]

    cmaps = []

    def info(provider,names):
        return [CMapInfo(name=n,provider=provider,category=None,source=None,bg=None) for n in names] \
               if records else list(names)

    if 'matplotlib' in provider:
        try:
            import matplotlib.cm as cm
            cmaps += info('matplotlib',
                          [cmap for cmap in cm.cmap_d if not
                           (cmap.startswith('cet_') or      # duplicates list below
                            cmap.startswith('Vega') or      # deprecated in matplotlib=2.1
                            cmap.startswith('spectral') )]) # deprecated in matplotlib=2.1
        except:
            pass
    if 'bokeh' in provider:
        try:
            from bokeh import palettes
            cmaps += info('bokeh', palettes.all_palettes)
            cmaps += info('bokeh', [p+'_r' for p in palettes.all_palettes])
        except:
            pass
    if 'colorcet' in provider:
        try:
            from colorcet import palette_n, glasbey_hv
            cet_maps = palette_n.copy()
            cet_maps['glasbey_hv'] = glasbey_hv # Add special hv-specific map
            cmaps += info('colorcet', cet_maps) 
            cmaps += info('colorcet', [p+'_r' for p in cet_maps])
        except:
            pass
    return sorted(unique_iterator(cmaps))
1177252
public static boolean isOpaqueTransparentExclusive(int colorA, int colorB)
    {
        return colorA == ColorRgba.TRANSPARENT.getRgba() && colorB == ColorRgba.OPAQUE.getRgba()
               || colorA == ColorRgba.OPAQUE.getRgba() && colorB == ColorRgba.TRANSPARENT.getRgba();
    }
80474
def map_colors(arr, crange, cmap, hex=True):
    
    if isinstance(crange, np.ndarray):
        xsorted = np.argsort(crange)
        ypos = np.searchsorted(crange, arr)
        arr = xsorted[ypos]
    else:
        if isinstance(crange, tuple):
            cmin, cmax = crange
        else:
            cmin, cmax = np.nanmin(arr), np.nanmax(arr)
        arr = (arr - cmin) / (cmax-cmin)
        arr = np.ma.array(arr, mask=np.logical_not(np.isfinite(arr)))
    arr = cmap(arr)
    if hex:
        return rgb2hex(arr)
    else:
        return arr
1050198
private void CheckPalleteImage(IfdTags metadata, int nifd) {
    // Color Map
    if (!metadata.containsTagId(TiffTags.getTagId("ColorMap"))) {
      validation.addErrorLoc("Missing Color Map", "IFD" + nifd);
    } else {
      int n = metadata.get(TiffTags.getTagId("ColorMap")).getCardinality();
      if (n != 3 * (int) Math.pow(2, metadata.get(TiffTags.getTagId("BitsPerSample"))
          .getFirstNumericValue()))
        validation.addError("Incorrect Color Map Cardinality", "IFD" + nifd, metadata.get(320)
            .getCardinality());
    }

    // Bits per Sample
    long bps = metadata.get(TiffTags.getTagId("BitsPerSample")).getFirstNumericValue();
    if (bps != 4 && bps != 8)
      validation.addError("Invalid Bits per Sample", "IFD" + nifd, bps);

    // Compression
    long comp = metadata.get(TiffTags.getTagId("Compression")).getFirstNumericValue();
    // if (comp != 1 && comp != 32773)
    if (comp < 1)
      validation.addError("Invalid Compression", "IFD" + nifd, comp);
  }
356362
def com_google_fonts_check_production_encoded_glyphs(ttFont, api_gfonts_ttFont):
  """"""
  cmap = ttFont['cmap'].getcmap(3, 1).cmap
  gf_cmap = api_gfonts_ttFont['cmap'].getcmap(3, 1).cmap
  missing_codepoints = set(gf_cmap.keys()) - set(cmap.keys())

  if missing_codepoints:
    hex_codepoints = ['0x' + hex(c).upper()[2:].zfill(4) for c
                      in missing_codepoints]
    yield FAIL, ("Font is missing the following glyphs"
                 " from the previous release"
                 " [{}]").format(', '.join(hex_codepoints))
  else:
    yield PASS, ('Font has all the glyphs from the previous release')
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)
796748
def save_colormap(self, name=None):
        
        if name == None: name = self.get_name()
        if name == "" or not type(name)==str: return "Error: invalid name."

        # get the colormaps directory
        colormaps = _os.path.join(_settings.path_home, 'colormaps')

        # make sure we have the colormaps directory
        _settings.MakeDir(colormaps)

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

        # open the file and overwrite
        f = open(path, 'w')
        f.write(str(self._colorpoint_list))
        f.close()

        return self
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
586578
private static function hasColorSupport()
    {
        if (!\defined('STDOUT')) {
            return false;
        }

        if ('Hyper' === getenv('TERM_PROGRAM')) {
            return true;
        }

        if (\DIRECTORY_SEPARATOR === '\\') {
            return (\function_exists('sapi_windows_vt100_support')
                && sapi_windows_vt100_support(STDOUT))
                || false !== getenv('ANSICON')
                || 'ON' === getenv('ConEmuANSI')
                || 'xterm' === getenv('TERM');
        }

        if (\function_exists('stream_isatty')) {
            return stream_isatty(STDOUT);
        }

        if (\function_exists('posix_isatty')) {
            return posix_isatty(STDOUT);
        }

        $stat = fstat(STDOUT);

        // Check if formatted mode is S_IFCHR
        return $stat ? 0020000 === ($stat['mode'] & 0170000) : false;
    }
1339911
def sc_cmap(self, viewer, event, msg=True):
        
        direction = self.get_direction(event.direction)
        self._cycle_cmap(viewer, msg, direction=direction)
        return True
1183542
def grayify_cmap(cmap):
    
    cmap = plt.cm.get_cmap(cmap)
    colors = cmap(np.arange(cmap.N))
    # convert RGBA to perceived greyscale luminance
    # cf. http://alienryderflex.com/hsp.html
    RGB_weight = [0.299, 0.587, 0.114]
    luminance = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight))
    colors[:, :3] = luminance[:, np.newaxis]
    return mplcolors.LinearSegmentedColormap.from_list(cmap.name + "_grayscale", colors, cmap.N)
775348
def _read_cmap(self):
        

        try:
            i = 0
            colormap = {0: (0, 0, 0)}
            with open(settings.COLORMAP) as cmap:
                lines = cmap.readlines()
                for line in lines:
                    if i == 0 and 'mode = ' in line:
                        i = 1
                        maxval = float(line.replace('mode = ', ''))
                    elif i > 0:
                        str = line.split()
                        if str == []:  # when there are empty lines at the end of the file
                            break
                        colormap.update(
                            {
                                i: (int(round(float(str[0]) * 255 / maxval)),
                                    int(round(float(str[1]) * 255 / maxval)),
                                    int(round(float(str[2]) * 255 / maxval)))
                            }
                        )
                        i += 1
        except IOError:
            pass

        self.cmap = {k: v[:4] for k, v in colormap.items()}
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"
923292
def process_cmap(cmap, ncolors=None, provider=None, categorical=False):
    
    providers_checked="matplotlib, bokeh, or colorcet" if provider is None else provider

    if isinstance(cmap, Cycle):
        palette = [rgb2hex(c) if isinstance(c, tuple) else c for c in cmap.values]
    elif isinstance(cmap, list):
        palette = cmap
    elif isinstance(cmap, basestring):
        mpl_cmaps = _list_cmaps('matplotlib')
        bk_cmaps = _list_cmaps('bokeh')
        cet_cmaps = _list_cmaps('colorcet')
        if provider=='matplotlib' or (provider is None and (cmap in mpl_cmaps or cmap.lower() in mpl_cmaps)):
            palette = mplcmap_to_palette(cmap, ncolors, categorical)
        elif provider=='bokeh' or (provider is None and (cmap in bk_cmaps or cmap.capitalize() in bk_cmaps)):
            palette = bokeh_palette_to_palette(cmap, ncolors, categorical)
        elif provider=='colorcet' or (provider is None and cmap in cet_cmaps):
            from colorcet import palette
            if cmap.endswith('_r'):
                palette = list(reversed(palette[cmap[:-2]]))
            else:
                palette = palette[cmap]
        else:
            raise ValueError("Supplied cmap %s not found among %s colormaps." %
                             (cmap,providers_checked))
    else:
        try:
            # Try processing as matplotlib colormap
            palette = mplcmap_to_palette(cmap, ncolors)
        except:
            palette = None
    if not isinstance(palette, list):
        raise TypeError("cmap argument %s expects a list, Cycle or valid %s colormap or palette."
                        % (cmap,providers_checked))
    if ncolors and len(palette) != ncolors:
        return [palette[i%len(palette)] for i in range(ncolors)]
    return palette