Returns a new colormap based on the one given
    but adjusted so that the old center point higher
    (>0.5) or lower (<0.5)

    :param cmap: colormap instance (e.g., cm.jet)
    :param center_ratio:
176510
def cmap_center_adjust(cmap, center_ratio):
    
    if not (0. < center_ratio) & (center_ratio < 1.):
        return cmap
    a = math.log(center_ratio) / math.log(0.5)
    return cmap_powerlaw_adjust(cmap, a)
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
567595
def rebuild_cmaps(self):
        
        self.logger.info("building color maps image")
        ht, wd, sep = self._cmht, self._cmwd, self._cmsep
        viewer = self.p_view

        # put the canvas into pick mode
        canvas = viewer.get_canvas()
        canvas.delete_all_objects()

        # get the list of color maps
        cm_names = self.cm_names
        num_cmaps = len(cm_names)
        viewer.configure_surface(500, (ht + sep) * num_cmaps)

        # create a bunch of color bars and make one large compound object
        # with callbacks for clicking on individual color bars
        l2 = []
        ColorBar = canvas.get_draw_class('drawablecolorbar')
        Text = canvas.get_draw_class('text')
        #ch_rgbmap = chviewer.get_rgbmap()
        #dist = ch_rgbmap.get_dist()
        dist = None
        #imap = ch_rgbmap.get_imap()
        logger = viewer.get_logger()

        for i, name in enumerate(cm_names):
            rgbmap = RGBMap.RGBMapper(logger, dist=dist)
            rgbmap.set_cmap(cmap.get_cmap(name))
            #rgbmap.set_imap(imap)
            x1, y1 = self._cmxoff, i * (ht + sep)
            x2, y2 = x1 + wd, y1 + ht
            cbar = ColorBar(x1, y1, x2, y2, cm_name=name, showrange=False,
                            rgbmap=rgbmap, coord='window')
            l2.append(cbar)
            l2.append(Text(x2 + sep, y2, name, color='white', fontsize=16,
                           coord='window'))

        Compound = canvas.get_draw_class('compoundobject')
        obj = Compound(*l2)
        canvas.add(obj)

        self._max_y = y2

        rgb_img = self.p_view.get_image_as_array()
        self.r_image.set_data(rgb_img)
753696
def center(self, reference=None):
        
        return self.from_center(x=0.0, y=0.0, z=0.0, reference=reference)
729439
def cmd_center(self, args):
        ''''''
        if len(args) < 3:
            print("map center LAT LON")
            return
        lat = float(args[1])
        lon = float(args[2])
        self.map.set_center(lat, lon)
641067
def _compute_ratio(top, bot):
        
        data = np.where(bot.data > 0, top.data / bot.data, 0.)
        return HpxMap(data, top.hpx)
105992
def create_colormap(palette):
    """"""
    from trollimage.colormap import Colormap
    fname = palette.get('filename', None)
    if fname:
        data = np.load(fname)
        cmap = []
        num = 1.0 * data.shape[0]
        for i in range(int(num)):
            cmap.append((i / num, (data[i, 0] / 255., data[i, 1] / 255.,
                                   data[i, 2] / 255.)))
        return Colormap(*cmap)

    colors = palette.get('colors', None)
    if isinstance(colors, list):
        cmap = []
        values = palette.get('values', None)
        for idx, color in enumerate(colors):
            if values:
                value = values[idx]
            else:
                value = idx / float(len(colors) - 1)
            cmap.append((value, tuple(color)))
        return Colormap(*cmap)

    if isinstance(colors, str):
        from trollimage import colormap
        import copy
        return copy.copy(getattr(colormap, colors))

    return None
620041
def register_custom_colormaps():
    
    if not HAS_MPL:
        return ()
    makemap = LinearSegmentedColormap.from_list
    for name, val in custom_colormap_data.items():
        cm1 = np.array(val).transpose().astype('f8')/256.0
        cm2 = cm1[::-1]
        nam1 = name
        nam2 = '%s_r' % name
        register_cmap(name=nam1, cmap=makemap(nam1, cm1, 256), lut=256)
        register_cmap(name=nam2, cmap=makemap(nam2, cm2, 256), lut=256)

    return ('stdgamma', 'red', 'green', 'blue', 'red_heat', 'green_heat',
            'blue_heat', 'magenta', 'yellow', 'cyan')
205342
def hue_sat_to_cmap(hue, sat):
    
    import colorsys

    # normalize to floats
    hue = float(hue) / 360.0
    sat = float(sat) / 100.0

    res = []
    for val in range(256):
        hsv_val = float(val) / 255.0
        r, g, b = colorsys.hsv_to_rgb(hue, sat, hsv_val)
        res.append((r, g, b))

    return res
130502
def get_canvas_xy(self, data_x, data_y, center=None):
        
        if center is not None:
            self.logger.warning("`center` keyword is ignored and will be deprecated")

        arr_pts = np.asarray((data_x, data_y)).T
        return self.tform['data_to_native'].to_(arr_pts).T[:2]
1033086
def center_image(self, no_reset=True):
        
        try:
            xy_mn, xy_mx = self.get_limits()
            data_x = float(xy_mn[0] + xy_mx[0]) / 2.0
            data_y = float(xy_mn[1] + xy_mx[1]) / 2.0

        except ImageViewNoDataError:
            # No data, so try to get center of any plotted objects
            canvas = self.get_canvas()
            try:
                data_x, data_y = canvas.get_center_pt()[:2]

            except Exception as e:
                self.logger.error("Can't compute center point: %s" % (str(e)))
                return

        self.panset_xy(data_x, data_y, no_reset=no_reset)

        if self.t_['autocenter'] == 'once':
            self.t_.set(autocenter='off')
405577
def setCustomColorRamp(self, colors=[], interpolatedPoints=10):
        
        self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, interpolatedPoints)
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)
255020
def add_cmap(name, clst):
    """"""
    global cmaps
    assert len(clst) == min_cmap_len, \
        ValueError("color map '%s' length mismatch %d != %d (needed)" % (
            name, len(clst), min_cmap_len))
    cmaps[name] = ColorMap(name, clst)
1188815
def heatmap(self, partition=None, cmap=CM.Blues):
        

        if isinstance(self.dm, DistanceMatrix):
            length = self.dm.values.shape[0]
        else:
            length = self.dm.shape[0]
        datamax = float(np.abs(self.dm).max())
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ticks_at = [0, 0.5 * datamax, datamax]
        if partition:
            sorting = flatten_list(partition.get_membership())
            self.dm = self.dm.reorder(sorting)
        cax = ax.imshow(
            self.dm.values,
            interpolation='nearest',
            origin='lower',
            extent=[0., length, 0., length],
            vmin=0,
            vmax=datamax,
            cmap=cmap,
        )
        cbar = fig.colorbar(cax, ticks=ticks_at, format='%1.2g')
        cbar.set_label('Distance')
        return fig
1219742
def centerOn(self, point):
        
        rect = self.rect()
        x = point.x() - rect.width() / 2.0
        y = point.y() - rect.height() / 2.0
        
        self.setPos(x, y)
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"