Esempio n. 1
0
def ratios_to_colors(values, colormap):
    """
    Map values in the range [0, 1] onto colors

    Parameters
    ----------
    values : array_like | float
        Numeric(s) in the range [0, 1]
    colormap : cmap
        Matplotlib colormap to use for the mapping

    Returns
    -------
    out : list | float
        Color(s) corresponding to the values
    """
    iterable = True
    try:
        iter(values)
    except TypeError:
        iterable = False
        values = [values]

    color_tuples = colormap(values)
    try:
        hex_colors = [mcolors.rgb2hex(t) for t in color_tuples]
    except IndexError:
        hex_colors = mcolors.rgb2hex(color_tuples)
    return hex_colors if iterable else hex_colors[0]
 def _on_color_pick(self):
     # store old value and type
     try:
         old_value = self.get_value()
         old_color_dev = colors.get_color_dev(old_value)
         color = colors.get_color_as_rgba_f(old_value)
     except ValueError:
         color = None
     if color is None:
         color = [1., 0., 0.]
     color = np.array(color) * 255
     qcolor = QtGui.QColor(*color.astype(int))
     # create dialog
     dialog = QtGui.QColorDialog(self)
     dialog.setOption(QtGui.QColorDialog.ShowAlphaChannel, True)
     color = dialog.getColor(initial=qcolor)
     # convert the color to previous type if possible
     if old_color_dev == 'name':
         color_name = mpl_colors.rgb2hex(color.getRgbF())
         new_value = colors.COLORS_INV.get(color_name, color_name)
     elif old_color_dev in ['rgbf', 'rgbaf']:
         new_value = color.getRgbF()
         new_value = [round(i, 2) for i in new_value]
     elif old_color_dev in ['rgb', 'rgba']:
         new_value = color.getRgb()
     elif old_color_dev == 'hex':
         new_value = mpl_colors.rgb2hex(color.getRgbF())
     else:
         new_value = color.name()
     self.set_value(new_value)
Esempio n. 3
0
File: table.py Progetto: vanife/tia
    def heat_map(self, cmap="RdYlGn", vmin=None, vmax=None, font_cmap=None):
        if cmap is None:
            carr = ["#d7191c", "#fdae61", "#ffffff", "#a6d96a", "#1a9641"]
            cmap = LinearSegmentedColormap.from_list("default-heatmap", carr)

        if isinstance(cmap, str):
            cmap = get_cmap(cmap)
        if isinstance(font_cmap, str):
            font_cmap = get_cmap(font_cmap)

        vals = self.actual_values.astype(float)
        if vmin is None:
            vmin = vals.min().min()
        if vmax is None:
            vmax = vals.max().max()
        norm = (vals - vmin) / (vmax - vmin)
        for ridx in range(self.nrows):
            for cidx in range(self.ncols):
                v = norm.iloc[ridx, cidx]
                if np.isnan(v):
                    continue
                color = cmap(v)
                hex = rgb2hex(color)
                styles = {"BACKGROUND": HexColor(hex)}
                if font_cmap is not None:
                    styles["TEXTCOLOR"] = HexColor(rgb2hex(font_cmap(v)))
                self.iloc[ridx, cidx].apply_styles(styles)
        return self
Esempio n. 4
0
    def _get_style_dict(self, gc, rgbFace):
        """
        return the style string.  style is generated from the
        GraphicsContext and rgbFace
        """
        attrib = {}

        if gc.get_hatch() is not None:
            attrib[u'fill'] = u"url(#%s)" % self._get_hatch(gc, rgbFace)
        else:
            if rgbFace is None:
                attrib[u'fill'] = u'none'
            elif tuple(rgbFace[:3]) != (0, 0, 0):
                attrib[u'fill'] = rgb2hex(rgbFace)

        if gc.get_alpha() != 1.0:
            attrib[u'opacity'] = str(gc.get_alpha())

        offset, seq = gc.get_dashes()
        if seq is not None:
            attrib[u'stroke-dasharray'] = u','.join([u'%f' % val for val in seq])
            attrib[u'stroke-dashoffset'] = unicode(float(offset))

        linewidth = gc.get_linewidth()
        if linewidth:
            attrib[u'stroke'] = rgb2hex(gc.get_rgb())
            if linewidth != 1.0:
                attrib[u'stroke-width'] = str(linewidth)
            if gc.get_joinstyle() != 'round':
                attrib[u'stroke-linejoin'] = gc.get_joinstyle()
            if gc.get_capstyle() != 'projecting':
                attrib[u'stroke-linecap'] = _capstyle_d[gc.get_capstyle()]

        return attrib
Esempio n. 5
0
def test_xkcd():
    x11_blue = mcolors.rgb2hex(
        mcolors.colorConverter.to_rgb('blue'))
    assert x11_blue == '#0000ff'
    XKCD_blue = mcolors.rgb2hex(
        mcolors.colorConverter.to_rgb('XKCDblue'))
    assert XKCD_blue == '#0343df'
Esempio n. 6
0
    def heat_map(self, cmap='RdYlGn', vmin=None, vmax=None, font_cmap=None):
        if cmap is None:
            carr = ['#d7191c', '#fdae61', '#ffffff', '#a6d96a', '#1a9641']
            cmap = LinearSegmentedColormap.from_list('default-heatmap', carr)

        if isinstance(cmap, basestring):
            cmap = get_cmap(cmap)
        if isinstance(font_cmap, basestring):
            font_cmap = get_cmap(font_cmap)

        vals = self.actual_values.astype(float)
        if vmin is None:
            vmin = vals.min().min()
        if vmax is None:
            vmax = vals.max().max()
        norm = (vals - vmin) / (vmax - vmin)
        for ridx in range(self.nrows):
            for cidx in range(self.ncols):
                v = norm.iloc[ridx, cidx]
                if np.isnan(v):
                    continue
                color = cmap(v)
                hex = rgb2hex(color)
                styles = {'BACKGROUND': HexColor(hex)}
                if font_cmap is not None:
                    styles['TEXTCOLOR'] = HexColor(rgb2hex(font_cmap(v)))
                self.iloc[ridx, cidx].apply_styles(styles)
        return self
Esempio n. 7
0
    def _get_style_dict(self, gc, rgbFace):
        """
        return the style string.  style is generated from the
        GraphicsContext and rgbFace
        """
        attrib = {}

        if gc.get_hatch() is not None:
            attrib[u"fill"] = u"url(#%s)" % self._get_hatch(gc, rgbFace)
        else:
            if rgbFace is None:
                attrib[u"fill"] = u"none"
            elif tuple(rgbFace[:3]) != (0, 0, 0):
                attrib[u"fill"] = rgb2hex(rgbFace)

        if gc.get_alpha() != 1.0:
            attrib[u"opacity"] = str(gc.get_alpha())

        offset, seq = gc.get_dashes()
        if seq is not None:
            attrib[u"stroke-dasharray"] = u",".join([u"%f" % val for val in seq])
            attrib[u"stroke-dashoffset"] = unicode(float(offset))

        linewidth = gc.get_linewidth()
        if linewidth:
            attrib[u"stroke"] = rgb2hex(gc.get_rgb())
            if linewidth != 1.0:
                attrib[u"stroke-width"] = str(linewidth)
            if gc.get_joinstyle() != "round":
                attrib[u"stroke-linejoin"] = gc.get_joinstyle()
            if gc.get_capstyle() != "projecting":
                attrib[u"stroke-linecap"] = _capstyle_d[gc.get_capstyle()]

        return attrib
Esempio n. 8
0
 def _get_hatch(self, gc, rgbFace):
     """
     Create a new hatch pattern
     """
     HATCH_SIZE = 72
     dictkey = (gc.get_hatch(), rgbFace, gc.get_rgb())
     id = self._hatchd.get(dictkey)
     if id is None:
         id = 'h%s' % md5(str(dictkey)).hexdigest()
         self._svgwriter.write('<defs>\n  <pattern id="%s" ' % id)
         self._svgwriter.write('patternUnits="userSpaceOnUse" x="0" y="0" ')
         self._svgwriter.write(' width="%d" height="%d" >\n' % (HATCH_SIZE, HATCH_SIZE))
         path_data = self._convert_path(
             gc.get_hatch_path(),
             Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE))
         if rgbFace is None:
             fill = 'none'
         else:
             fill = rgb2hex(rgbFace)
         self._svgwriter.write(
             '<rect x="0" y="0" width="%d" height="%d" fill="%s"/>' %
             (HATCH_SIZE+1, HATCH_SIZE+1, fill))
         path = '<path d="%s" fill="%s" stroke="%s" stroke-width="1.0"/>' % (
             path_data, rgb2hex(gc.get_rgb()[:3]), rgb2hex(gc.get_rgb()[:3]))
         self._svgwriter.write(path)
         self._svgwriter.write('\n  </pattern>\n</defs>')
         self._hatchd[dictkey] = id
     return id
Esempio n. 9
0
    def _get_style(self, gc, rgbFace):
        """
        return the style string.
        style is generated from the GraphicsContext, rgbFace and clippath
        """
        if rgbFace is None:
            fill = 'none'
        else:
            fill = rgb2hex(rgbFace)

        offset, seq = gc.get_dashes()
        if seq is None:
            dashes = ''
        else:
            dashes = 'stroke-dasharray: %s; stroke-dashoffset: %s;' % (
                ','.join(['%s'%val for val in seq]), offset)

        linewidth = gc.get_linewidth()
        if linewidth:
            return 'fill: %s; stroke: %s; stroke-width: %s; ' \
                'stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %s' % (
                         fill,
                         rgb2hex(gc.get_rgb()),
                         linewidth,
                         gc.get_joinstyle(),
                         _capstyle_d[gc.get_capstyle()],
                         dashes,
                         gc.get_alpha(),
                )
        else:
            return 'fill: %s; opacity: %s' % (\
                         fill,
                         gc.get_alpha(),
                )
Esempio n. 10
0
    def _get_style(self, gc, rgbFace):
        """
        return the style string.
        style is generated from the GraphicsContext, rgbFace and clippath
        """
        if rgbFace is None:
            fill = "none"
        else:
            fill = rgb2hex(rgbFace[:3])

        offset, seq = gc.get_dashes()
        if seq is None:
            dashes = ""
        else:
            dashes = "stroke-dasharray: %s; stroke-dashoffset: %f;" % (",".join(["%f" % val for val in seq]), offset)

        linewidth = gc.get_linewidth()
        if linewidth:
            return (
                "fill: %s; stroke: %s; stroke-width: %f; "
                "stroke-linejoin: %s; stroke-linecap: %s; %s opacity: %f"
                % (
                    fill,
                    rgb2hex(gc.get_rgb()[:3]),
                    linewidth,
                    gc.get_joinstyle(),
                    _capstyle_d[gc.get_capstyle()],
                    dashes,
                    gc.get_alpha(),
                )
            )
        else:
            return "fill: %s; opacity: %f" % (fill, gc.get_alpha())
Esempio n. 11
0
def assign_continuous_colors(data, gg, color_col):
    """
    Logic to assign colors in the continuous case.

    Handle continuous colors here. We're going to use whatever colormap
    is defined to evaluate for each value. We're then going to convert
    each color to HEX so that it can fit in 1 column. This will make it
    much easier when creating layers. We're also going to evaluate the
    quantiles for that particular column to generate legend scales. This
    isn't what ggplot does, but it's good enough for now.

    Parameters
    ----------
    data : DataFrame
        dataframe which should have shapes assigned to
    gg : ggplot object, which holds information and gets a legend assigned
    color_col : The column we are using to color.

    Returns
    -------
    data : DataFrame
        the changed dataframe
    """
    values = data[color_col].tolist()
    values = [(i - min(values)) / (max(values) - min(values)) for i in values]
    color_mapping = gg.colormap(values)[::, :3]
    data["color_mapping"] = [rgb2hex(value) for value in color_mapping]
    quantiles = np.percentile(gg.data[color_col], [0, 25, 50, 75, 100])
    key_colors = gg.colormap([0, 25, 50, 75, 100])[::, :3]
    key_colors = [rgb2hex(value) for value in key_colors]
    gg.add_to_legend("color", dict(zip(key_colors, quantiles)),
                     scale_type="continuous")
    return data
Esempio n. 12
0
    def draw_gouraud_triangle(self, gc, points, colors, trans):
        # This uses a method described here:
        #
        #   http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html
        #
        # that uses three overlapping linear gradients to simulate a
        # Gouraud triangle.  Each gradient goes from fully opaque in
        # one corner to fully transparent along the opposite edge.
        # The line between the stop points is perpendicular to the
        # opposite edge.  Underlying these three gradients is a solid
        # triangle whose color is the average of all three points.

        trans_and_flip = self._make_flip_transform(trans)
        tpoints = trans_and_flip.transform(points)
        write = self._svgwriter.write

        write("<defs>")
        for i in range(3):
            x1, y1 = points[i]
            x2, y2 = points[(i + 1) % 3]
            x3, y3 = points[(i + 2) % 3]
            c = colors[i][:3]

            if x2 == x3:
                xb = x2
                yb = y1
            elif y2 == y3:
                xb = x1
                yb = y2
            else:
                m1 = (y2 - y3) / (x2 - x3)
                b1 = y2 - (m1 * x2)
                m2 = -(1.0 / m1)
                b2 = y1 - (m2 * x1)
                xb = (-b1 + b2) / (m1 - m2)
                yb = m2 * xb + b2

            write(
                '<linearGradient id="GR%x_%d" x1="%f" y1="%f" x2="%f" y2="%f" gradientUnits="userSpaceOnUse">'
                % (self._n_gradients, i, x1, y1, xb, yb)
            )
            write('<stop offset="0" stop-color="%s" stop-opacity="1.0"/>' % rgb2hex(c))
            write('<stop offset="1" stop-color="%s" stop-opacity="0.0"/>' % rgb2hex(c))
            write("</linearGradient>")

        # Define the triangle itself as a "def" since we use it 4 times
        write('<polygon id="GT%x" points="%f %f %f %f %f %f"/>' % (self._n_gradients, x1, y1, x2, y2, x3, y3))
        write("</defs>\n")

        avg_color = np.sum(colors[:, :3], axis=0) / 3.0
        write('<use xlink:href="#GT%x" fill="%s"/>\n' % (self._n_gradients, rgb2hex(avg_color)))
        for i in range(3):
            write(
                '<use xlink:href="#GT%x" fill="url(#GR%x_%d)" filter="url(#colorAdd)"/>\n'
                % (self._n_gradients, self._n_gradients, i)
            )

        self._n_gradients += 1
Esempio n. 13
0
    def getLevels(self):
        levels = []
        colHEX_RGB = []
        colHEX_BGR = []
        colRGB = []
        colBGR = []
        level_ok = True
        col_ok = True
        
        rows = self.ui.tableWidget.rowCount()
        
        if rows > 0:
            for row in range(rows):
                try:
                    levels.append(float(self.ui.tableWidget.item(row, 0).text()))
                    float(self.ui.tableWidget.item(row, 1).text())
                except:
                    return [], False, [], [], True
                try:
                    col = str(self.ui.tableWidget.item(row, 2).text()).split(",")

                    colFloat_RGB = (float(col[0])/255.0, float(col[1])/255.0, float(col[2])/255.0)
                    colFloat_BGR = (float(col[2])/255.0, float(col[1])/255.0, float(col[0])/255.0)
                    colRGB.append([float(col[0]), float(col[1]), float(col[2])])
                    colBGR.append([float(col[2]), float(col[1]), float(col[0])])
#                    colHex = colors.rgb2hex(colFloat_RGB)
                    colHEX_RGB.append(colors.rgb2hex(colFloat_RGB))
                    colHEX_BGR.append(colors.rgb2hex(colFloat_BGR))
                except:
                    return [], True, [], [], False
         
            # check if level ranges are in ascending order
            for row in range(rows-1):
                
                level_ai = round(float(self.ui.tableWidget.item(row, 0).text()), 6)
                level_aj = round(float(self.ui.tableWidget.item(row, 1).text()), 6)
                level_bi = round(float(self.ui.tableWidget.item(row+1, 0).text()), 6)
                
                if level_aj != level_bi:
                    level_ok = False
                if level_aj <= level_ai:
                    level_ok = False
                    
            level_1i = float(self.ui.tableWidget.item(0, 0).text())
            level_1j = float(self.ui.tableWidget.item(0, 1).text())
            
            if level_1j <= level_1i:
                level_ok = False

            level_Ni = float(self.ui.tableWidget.item(rows-1, 0).text())
            level_Nj = float(self.ui.tableWidget.item(rows-1, 1).text())
            
            if level_Nj <= level_Ni:
                level_ok = False
            
            levels.append(float(self.ui.tableWidget.item(rows-1, 1).text()))
            
        return levels, level_ok, colHEX_RGB, colRGB, colHEX_BGR, colBGR, col_ok
Esempio n. 14
0
def assign_colors(data, aes, gg):
    """
    Assigns colors to the given data based on the aes and adds the right legend

    We need to take a value an convert it into colors that we can actually
    plot. This means checking to see if we're colorizing a discrete or
    continuous value, checking if their is a colormap, etc.

    Parameters
    ----------
    data : DataFrame
        dataframe which should have shapes assigned to
    aes : aesthetic
        mapping, including a mapping from color to variable
    gg : ggplot object, which holds information and gets a legend assigned

    Returns
    -------
    data : DataFrame
        the changed dataframe
    """
    if 'color' in aes:
        color_col = aes['color']
        # Handle continuous colors here. We're going to use whatever colormap
        # is defined to evaluate for each value. We're then going to convert
        # each color to HEX so that it can fit in 1 column. This will make it
        # much easier when creating layers. We're also going to evaluate the 
        # quantiles for that particular column to generate legend scales. This
        # isn't what ggplot does, but it's good enough for now.
        if color_col in data._get_numeric_data().columns:
            values = data[color_col].tolist()
            # Normalize the values for the colormap
            values = [(i - min(values)) / (max(values) - min(values)) for i in values]
            color_mapping = gg.colormap(values)[::, :3]
            data["color_mapping"] = [rgb2hex(value) for value in color_mapping]
            quantiles = np.percentile(gg.data[color_col], [0, 25, 50, 75, 100])
            key_colors = gg.colormap([0, 25, 50, 75, 100])[::, :3]
            key_colors = [rgb2hex(value) for value in key_colors]
            gg.add_to_legend("color", dict(zip(key_colors, quantiles)), scale_type="continuous")

        # Handle discrete colors here. We're going to check and see if the user
        # has defined their own color palette. If they have then we'll use those
        # colors for mapping. If not, then we'll generate some default colors.
        # We also have to be careful here because for some odd reason the next()
        # function is different in Python 2.7 and Python 3.0. Once we've done that
        # we generate the legends based off the the (color -> value) mapping.
        else:
            possible_colors = np.unique(data[color_col])
            if gg.manual_color_list:
                color = color_gen(len(possible_colors), gg.manual_color_list)
            else:
                color = color_gen(len(possible_colors))
            color_mapping = dict((value, six.next(color)) for value in possible_colors)
            data["color_mapping"] = data[color_col].apply(lambda x: color_mapping[x])
            gg.add_to_legend("color", dict((v, k) for k, v in color_mapping.items()))

    return data
Esempio n. 15
0
    def __init__(self, pdb_object, structure_name, residues_of_interest = [], label_all_residues_of_interest = False, **kwargs):
        '''The chain_seed_color kwarg can be either:
               - a triple of R,G,B values e.g. [0.5, 1.0, 0.75] where each value is between 0.0 and 1.0;
               - a hex string #RRGGBB e.g. #77ffaa;
               - a name defined in the predefined dict above e.g. "aquamarine".
        '''
        self.pdb_object = pdb_object
        self.structure_name = structure_name
        self.add_residues_of_interest(residues_of_interest)
        self.label_all_residues_of_interest = label_all_residues_of_interest
        self.chain_colors = kwargs.get('chain_colors') or {}

        # Set up per-chain colors
        try:
            if not self.chain_colors and kwargs.get('chain_seed_color'):
                chain_seed_color = kwargs.get('chain_seed_color')
                if isinstance(chain_seed_color, str) or isinstance(chain_seed_color, unicode):
                    chain_seed_color = str(chain_seed_color)
                    if chain_seed_color.startswith('#'):
                        if len(chain_seed_color) != 7:
                            chain_seed_color = None
                    else:
                        trpl = predefined.get(chain_seed_color)
                        chain_seed_color = None
                        if trpl:
                            chain_seed_color = mpl_colors.rgb2hex(trpl)
                elif isinstance(chain_seed_color, list) and len(chain_seed_color) == 3:
                    chain_seed_color = mpl_colors.rgb2hex(chain_seed_color)

                if chain_seed_color.startswith('#') and len(chain_seed_color) == 7:

                    # todo: We are moving between color spaces multiple times so are probably introducing artifacts due to rounding. Rewrite this to minimize this movement.
                    chain_seed_color = chain_seed_color[1:]

                    hsl_color = colorsys.rgb_to_hls(int(chain_seed_color[0:2], 16)/255.0, int(chain_seed_color[2:4], 16)/255.0, int(chain_seed_color[4:6], 16)/255.0)
                    chain_seed_hue = int(360.0 * hsl_color[0])
                    chain_seed_saturation = max(0.15, hsl_color[1]) # otherwise some colors e.g. near-black will not yield any alternate colors
                    chain_seed_lightness = max(0.15, hsl_color[2]) # otherwise some colors e.g. near-black will not yield any alternate colors

                    min_colors_in_wheel = 4 # choose at least 4 colors - this usually results in a wider variety of colors and prevents clashes e.g. given 2 chains in both mut and wt, wt seeded with blue, and mut seeded with yellow, we will get a clash
                    chain_ids = sorted(pdb_object.atom_sequences.keys())

                    # Choose complementary colors, respecting the original saturation and lightness values
                    chain_colors = ggplot_color_wheel(max(len(chain_ids), min_colors_in_wheel), start = chain_seed_hue, saturation_adjustment = None, saturation = chain_seed_saturation, lightness = chain_seed_lightness)
                    assert(len(chain_colors) >= len(chain_ids))
                    self.chain_colors = {}
                    for i in xrange(len(chain_ids)):
                        self.chain_colors[chain_ids[i]] = str(list(mpl_colors.hex2color('#' + chain_colors[i])))

                    # Force use of the original seed as this may have been altered above in the "= max(" statements
                    self.chain_colors[chain_ids[0]] = str(list(mpl_colors.hex2color('#' + chain_seed_color)))

        except Exception, e:
            print('An exception occurred setting the chain colors. Ignoring exception and resuming with default colors.')
            print(str(e))
            print(traceback.format_exc())
Esempio n. 16
0
    def _cmap_d_pal(n):
        if n > ncolors:
            raise ValueError(
                "cmap `{}` has {} colors you requested {} "
                "colors.".format(name, ncolors, n))

        if ncolors < 256:
            return [mcolors.rgb2hex(c) for c in colormap.colors[:n]]
        else:
            # Assume these are continuous and get colors equally spaced
            # intervals  e.g. viridis is defined with 256 colors
            idx = np.linspace(0, ncolors-1, n).round().astype(int)
            return [mcolors.rgb2hex(colormap.colors[i]) for i in idx]
Esempio n. 17
0
def test_cn():
    matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
                                                    ['blue', 'r'])
    x11_blue = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C0'))
    assert x11_blue == '#0000ff'
    red = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C1'))
    assert red == '#ff0000'

    matplotlib.rcParams['axes.prop_cycle'] = cycler('color',
                                                    ['XKCDblue', 'r'])
    XKCD_blue = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C0'))
    assert XKCD_blue == '#0343df'
    red = mcolors.rgb2hex(mcolors.colorConverter.to_rgb('C1'))
    assert red == '#ff0000'
Esempio n. 18
0
def assign_colors(gg):
    """
    We need to take a value an convert it into colors that we can actually
    plot. This means checking to see if we're colorizing a discrete or 
    continuous value, checking if their is a colormap, etc.

    params:
        gg - a ggplot instance
    """
    if 'color' in gg.aesthetics:
        color_col = gg.aesthetics['color']
        # Handle continuous colors here. We're going to use whatever colormap
        # is defined to evaluate for each value. We're then going to convert
        # each color to HEX so that it can fit in 1 column. This will make it
        # much easier when creating layers. We're also going to evaluate the 
        # quantiles for that particular column to generate legend scales. This
        # isn't what ggplot does, but it's good enough for now.
        if color_col in gg.data._get_numeric_data().columns:
            values = gg.data[color_col].tolist()
            # Normalize the values for the colormap
            values = [(i - min(values)) / (max(values) - min(values)) for i in values]
            color_mapping = gg.colormap(values)[::,:3]
            gg.data["color_mapping"] = [rgb2hex(value) for value in color_mapping]
            quantiles = np.percentile(gg.data[color_col], [0, 25, 50, 75, 100])
            key_colors = gg.colormap([0, 25, 50, 75, 100])[::,:3]
            key_colors = [rgb2hex(value) for value in key_colors]
            gg.legend["color"] = dict(zip(key_colors, quantiles))

        # Handle discrete colors here. We're goign to check and see if the user
        # has defined their own color palatte. If they have then we'll use those
        # colors for mapping. If not, then we'll generate some default colors.
        # We also have to be careful here becasue for some odd reason the next()
        # function is different in Python 2.7 and Python 3.0. Once we've done that
        # we generate the legends based off the the (color -> value) mapping.
        else:
            if gg.manual_color_list:
                color = color_gen(gg.manual_color_list)
            else:
                color = color_gen()
            possible_colors = np.unique(gg.data[color_col])
            if sys.hexversion > 0x03000000:
                color_mapping = {value: color.__next__() for value in possible_colors}
            else:
                color_mapping = {value: color.next() for value in possible_colors}
            gg.data["color_mapping"] = gg.data[color_col].apply(lambda x: color_mapping[x])
            gg.legend["color"] = { v: k for k, v in color_mapping.items() }

    return gg
Esempio n. 19
0
    def draw_text(self, gc, x, y, s, prop, angle, ismath):
        """
        draw text
        """
        if ismath:
             return self.draw_mathtext(gc, x, y, s, prop, angle)
        
        font = self._get_font(prop)

        fontsize = prop.get_size_in_points()
        
        thetext = '%s' % s
        fontname = font.get_sfnt()[(1,0,0,6)]
        fontsize = prop.get_size_in_points()
        color = rgb2hex(gc.get_rgb())
        style = 'font-size: %f; font-family: %s; stroke-width: 0.5; stroke: %s; fill: %s;'%(fontsize, fontname, color, color)
        #style = 'font-size: %f; font-family: %s; stroke: %s;'%(fontsize, fontname, color)
        if angle!=0:
            transform = 'transform="translate(%f,%f) rotate(%1.1f) translate(%f,%f)"' % (x,y,-angle,-x,-y) # Inkscape doesn't support rotate(angle x y)
        else: transform = ''


        svg = """\
<text style="%(style)s" x="%(x)f" y="%(y)f" %(transform)s>
  %(thetext)s
</text>
""" % locals()
        self._draw_rawsvg(svg)
Esempio n. 20
0
File: point.py Progetto: CETHop/sage
    def _render_on_subplot(self,subplot):
        r"""
        TESTS:

        We check to make sure that \#2076 is fixed by verifying all
        the points are red::

            sage: point(((1,1), (2,2), (3,3)), rgbcolor=hue(1), size=30)
        """
        options = self.options()

        #Convert the color to a hex string so that the scatter
        #method does not interpret it as a list of 3 floating
        #point color specifications when there are
        #three points. This is mentioned in the matplotlib 0.98
        #documentation and fixes \#2076
        from matplotlib.colors import rgb2hex
        c = rgb2hex(to_mpl_color(options['rgbcolor']))

        a = float(options['alpha'])
        z = int(options.pop('zorder', 0))
        s = int(options['size'])
        faceted = options['faceted'] #faceted=True colors the edge of point
        scatteroptions={}
        if not faceted: scatteroptions['edgecolors'] = 'none'
        subplot.scatter(self.xdata, self.ydata, s=s, c=c, alpha=a, zorder=z, label=options['legend_label'], **scatteroptions)
Esempio n. 21
0
def weighted_lines_cm(weights, endpoints, color_pos = '#00ff00', color_neg = '#ff0000', opacity = 0.5,
                     arrows = False, weight = 4):
    min_weight = min(weights)
    max_weight = max(weights)

    cm = plt.cm.cool

    for w, (from_, to) in zip(weights, endpoints):
        w_rel = 0
        if w > 0:
            w_rel = w / max_weight
        elif min_weight < 0:
            w_rel = w / min_weight

        color = cm(w_rel)

        d = {
                'path': [ { 'lat': from_[0], 'lng': from_[1] }, { 'lat': to[0], 'lng': to[1] } ],
                'strokeColor': rgb2hex(color),
                'strokeOpacity': opacity,
                'strokeWeight': weight,
                }
        if arrows:
            d.update({ '_ARROW': True })
        yield d
def visualizeSurface(colrs,centers,n):
#A has the signal values in the first row, and the center of each face in
#the second through fourth rows.

#ColorMat = [[1 1 1];eye(3);[1 .64 0];[1 1 0]];%Standard Rubik's Cube
#ColorMat = [[1 1 1];eye(3);[0 0 0];[1 1 0]];%Standard Rubik's Cube
    fig = plt.figure()
    ax = Axes3D(fig)
    for j in xrange(6*n**2):
        center = centers[:,j]
        color = colrs[:,j]
        for m in xrange(3): #%%This code should be improved, it's simply to fix roundoff
            if color[m] > 1:
                color[m] = 1
        d = 1./n
        if abs(center[0]) == 1:
            x = center[0]*np.ones(4)
            y = center[1] + np.array([d,d,-d,-d])
            z = center[2] + np.array([d,-d,-d,d])
        if abs(center[1]) == 1:
            y = center[1]*np.ones(4)
            x = center[0] + np.array([d,d,-d,-d])
            z = center[2] + np.array([d,-d,-d,d]) 
        if abs(center[2]) == 1:
            z = center[2]*np.ones(4)
            x = center[0] + np.array([d,d,-d,-d])
            y = center[1] + np.array([d,-d,-d,d])     
    #%fill3(x,y,z,ones(4,1)*color); MonoChromatic
        verts = [zip(x/2+.5, y/2+.5,z/2+.5)]
        tri=Poly3DCollection(verts)
        tri.set_color(colors.rgb2hex(color))
        tri.set_edgecolor('k')
        ax.add_collection3d(tri)
    plt.show()
def get_rgb_hexad_color_palete():
    """Returns a list of RGB values with the color palette used to plot the
    transit vehicles returned by NextBus. Each entry returned in the color
    palette has the RGB hexadecimal format, and without the prefix '0x' as
    for colors in Google Maps, nor the prefix '#' for the matplotlib color.
    Ie., the entry for blue is returned as '0000FF' and for red 'FF0000'."""

    # We don't use these color names directly because their intensity might
    # be (are) reflected diferently between between the remote server and
    # matplotlib, and this difference in rendering a same color affects the
    # color-legend in matplotlib. For this reason too, we don't need to use
    # only the named colors in Google Maps but more in matplotlib, for in
    # both cases hexadecimal RGB values are really used.

    high_contrast_colors = ["green", "red", "blue", "yellow", "aqua",
                            "brown", "gray", "honeydew", "purple",
                            "turquoise", "magenta", "orange"]

    from matplotlib.colors import ColorConverter, rgb2hex

    color_converter = ColorConverter()
    hex_color_palette = [rgb2hex(color_converter.to_rgb(cname))[1:] for \
                         cname in high_contrast_colors]
    # matplotlib.colors.cnames[cname] could have been used instead of rgb2hex

    return hex_color_palette
Esempio n. 24
0
def colormapper(value, lower=0, upper=1, cmap=None):
    """
    Maps values to colors by normalizing within [a,b], obtaining rgba from the
    given matplotlib color map for heatmap polygon coloring.

    Parameters
    ----------
    x: float
        The value to be colormapped
    a: float
        Lower bound of colors
    b: float
        Upper bound of colors
    cmap: String or matplotlib.colors.Colormap (optional)
        Colormap object to prevent repeated lookup

    Returns
    -------
    hex_, float
        The value mapped to an appropriate RGBA color value
    """

    cmap = get_cmap(cmap)
    if upper - lower == 0:
        rgba = cmap(0)
    else:
        rgba = cmap((value - lower) / float(upper - lower))
    hex_ = rgb2hex(rgba)
    return hex_
def sb_distplots(plotargs, return_key='close_return', update_type='Revisions'):
    "Plots conditional underpricing distributions. Run set_data(df) first."

    f, ax = plt.subplots(1,1,figsize=(16, 5), sharex=True)
    for arg in plotargs:
        df, c, l, h = arg

        sb.distplot(df[return_key], ax=ax,
            kde_kws={"label": l + "    Obs={N}".format(N=len(df)), "color": c},
            hist_kws={"histtype": "stepfilled", "color": c})

        r = df[return_key]
        m,s,y,med = r.mean(), r.std(), r.skew(), r.median()
        ax.annotate(
            u'μ={:.2f}%,   σ={:.2f},   γ={:.2f}'.format(m,s,y),
            xy=(med+2, h), xytext=(med+6, h+0.01),
            arrowprops=dict(facecolor=cl.rgb2hex(c), width=1.5, headwidth=5, shrink=0.1))


    H, prob = kruskalwallis(*[x[0][return_key] for x in plotargs])
    ax.annotate("Kruskal-Wallis: (H={H:.2f}, prob={p:.3f})".format(H=H, p=prob),
                xy=(66,0.01))

    plt.title("Conditional Underpricing Distributions %s" % update_type)
    plt.ylabel("Density")
    plt.xlim(xmin=-40,xmax=100)
    plt.xlabel("1st Day Returns (%)")
    plt.ylim((0, 0.12))
def on_pick(event):
    r = event.mouseevent.xdata
    g = event.mouseevent.ydata
    b = slider.val
    cbox_im.set_data([[[r, 1 - g, b]]])
    cbox_txt.set_text(rgb2hex((r, g, b)).upper())
    fig.canvas.draw()
Esempio n. 27
0
def line_sets(ll, arrows = False, weight = 4):
    """
    ll = [
             [((lat, lon), (lat, lon)), ((lat, lon), (lat, lon))],
             ...
         ]
    """
    logging.debug(ll)
    assert len(ll[0][0]) == 2
    assert len(ll[0][0][0]) == 2
    assert len(ll[0][0][1]) == 2
    assert type(ll[0][0][0][0]) in (float, np.float64, np.float32)
    assert type(ll[0][0][0][1]) in (float, np.float64, np.float32)
    assert type(ll[0][0][1][0]) in (float, np.float64, np.float32)
    assert type(ll[0][0][1][1]) in (float, np.float64, np.float32)

    ll = list(ll)
    for line_set, c in zip(ll, plt.cm.Set1(np.linspace(0, 1, len(ll)))):
        for (from_, to) in line_set:
            d = {
                    'path': [ { 'lat': from_[0], 'lng': from_[1] }, { 'lat': to[0], 'lng': to[1] } ],
                    'strokeColor': rgb2hex(c),
                    'strokeWeight': weight,
                    'strokeOpacity': 0.5,
                  }
            if arrows:
                d.update({ '_ARROW': True })
            yield d
Esempio n. 28
0
File: utils.py Progetto: nexpy/nexpy
def get_colors(n, first='#1f77b4', last='#d62728'):
    """Return a list of colors interpolating between the first and last.

    The function accepts both strings representing hex colors and tuples 
    containing RGB values, which must be between 0 and 1.

    Parameters
    ----------
    n : int
        Number of colors to be generated.
    first : str or tuple of float
        First color in the list (defaults to Matplotlib default blue).
    last : str, tuple
        Last color in the list(defaults to Matplotlib default red).

    Returns
    -------
    colors : list
        A list of strings containing hex colors
    """
    if not isinstance(first, tuple):
        first = hex2color(first)
    if not isinstance(last, tuple):
        last = hex2color(last)
    return [rgb2hex((first[0]+(last[0]-first[0])*i/(n-1), 
                     first[1]+(last[1]-first[1])*i/(n-1),
                     first[2]+(last[2]-first[2])*i/(n-1))) for i in range(n)]
Esempio n. 29
0
def _color2hex(color):
    """Convert arbitrary color input to hex string"""
    from matplotlib import colors
    cc = colors.ColorConverter()
    rgba = cc.to_rgba(color)
    hexcol = colors.rgb2hex(rgba)
    return hexcol
Esempio n. 30
0
    def plot(self):
        state_values = dict(zip(self.data[self.map_key], self.data[self.map_value]))
        state_names = [shape_dict['NAME'] for shape_dict in self.map.states_info]

        v_min, v_max = 0., 1.
        cmap = plt.cm.hot
        ax = plt.gca()

        for state_code, value in state_values.iteritems():
            if state_code not in self.state_codes:
                continue
            state_name = self.state_codes[state_code]
            #seg = self.map.states[state_names.index(state_name)]

            # calculate state's color on heatmap based on the value
            color_rgb = cmap(1. - np.sqrt((value - v_min)/(v_max - v_min)))[:3]
            color_hex = rgb2hex(color_rgb)

            # get the shape from shape file
            state_shape = self.map.states[state_names.index(state_name)]


            # create polygon based on shape and color, add it to plot
            poly = Polygon(state_shape, facecolor=color_hex, edgecolor=color_hex)
            ax.add_patch(poly)

        plt.title('Default rates in' + self.plot_name)
        plt.legend()

        if self.save_plot:
            plt.savefig(self.plot_name or 'plot name')

        if self.show_plot:
            plt.show()
Esempio n. 31
0
	def Plot(self):
		"""
		Plot a LUT as a 3D RGB cube using matplotlib. Stolen from https://github.com/mikrosimage/ColorPipe-tools/tree/master/plotThatLut.
		"""
		
		try:
			import matplotlib
			# matplotlib : general plot
			from matplotlib.pyplot import title, figure
			# matplotlib : for 3D plot
			# mplot3d has to be imported for 3d projection
			import mpl_toolkits.mplot3d
			from matplotlib.colors import rgb2hex
		except ImportError:
			print "matplotlib not installed. Run: pip install matplotlib"
			return

		#for performance reasons lattice size must be 9 or less
		lut = None
		if self.cubeSize > 9:
			lut = self.Resize(9)
		else:
			lut = self


		# init vars
		cubeSize = lut.cubeSize
		input_range = xrange(0, cubeSize)
		max_value = cubeSize - 1.0
		red_values = []
		green_values = []
		blue_values = []
		colors = []
		# process color values
		for r in input_range:
			for g in input_range:
				for b in input_range:
					# get a value between [0..1]
					norm_r = r/max_value
					norm_g = g/max_value
					norm_b = b/max_value
					# apply correction
					res = lut.ColorFromColor(Color(norm_r, norm_g, norm_b))
					# append values
					red_values.append(res.r)
					green_values.append(res.g)
					blue_values.append(res.b)
					# append corresponding color
					colors.append(rgb2hex([norm_r, norm_g, norm_b]))
		# init plot
		fig = figure()
		fig.canvas.set_window_title('pylut Plotter')
		ax = fig.add_subplot(111, projection='3d')
		ax.set_xlabel('Red')
		ax.set_ylabel('Green')
		ax.set_zlabel('Blue')
		ax.set_xlim(min(red_values), max(red_values))
		ax.set_ylim(min(green_values), max(green_values))
		ax.set_zlim(min(blue_values), max(blue_values))
		title(self.name)
		# plot 3D values
		ax.scatter(red_values, green_values, blue_values, c=colors, marker="o")
		matplotlib.pyplot.show()
Esempio n. 32
0
File: dense.py Progetto: mcxxmc/kviz
    def animate_activations(self,
                            X,
                            filename='activations',
                            duration=1000,
                            x_color="#3498db",
                            x_marker="o"):
        """
        Creates an animation of the graph activated by each data point

        Parameters:
            X : ndarray
                input to a Keras model
            filename : str
                name of file to which visualization will be saved
            duration : int
                duration in ms between images in GIF
            x_color: str.
                the color (in hex form) of the points in the pyplot graph
            x_marker: str.
                the shape of the points in the pyplot graph

        Returns:
            None
        """

        network_images = []
        input_images = []

        predictions = [X]
        for i in range(len(self._int_models)):
            predictions.append(self._int_models[i].predict(X))
        predictions.append(self.model.predict(X))

        for i in range(len(X)):
            for l in range(len(self.model.layers)):
                layer = self.model.layers[l]

                layerVals = predictions[l][i]
                norm = Normalize(vmin=min(layerVals), vmax=max(layerVals))

                color_maps = {}

                for n in range(0, layer.input_shape[1]):
                    act = predictions[l][i][n]

                    index = unique_index(l, n)
                    the_color_map = get_or_create_colormap_with_dict(
                        self._graph.nodes[index]["color"], color_maps)

                    if l == 0:
                        set_node_attributes(
                            self._graph, {
                                index: {
                                    'style': 'filled',
                                    'color': str(
                                        rgb2hex(the_color_map(norm(act))))
                                }
                            })
                        if int(act) == act:
                            set_node_attributes(self._graph,
                                                {index: {
                                                    'label': str(act)
                                                }})
                    else:
                        set_node_attributes(
                            self._graph, {
                                index: {
                                    'style': 'filled',
                                    'color': str(
                                        rgb2hex(the_color_map(norm(act))))
                                }
                            })

                for h in range(0, layer.output_shape[1]):
                    if l == len(self.model.layers) - 1:
                        act = predictions[l + 1][i][h]

                        index = unique_index(l + 1, h)
                        the_color_map = get_or_create_colormap_with_dict(
                            self._graph.nodes[index]["color"], color_maps)

                        set_node_attributes(
                            self._graph, {
                                index: {
                                    'label': str(int(round(act))),
                                    'style': 'filled',
                                    'color': str(
                                        rgb2hex(the_color_map(norm(act))))
                                }
                            })

            network_images.append(self._snap(filename))
            input_images.append(
                self._snap_X([i],
                             X,
                             filename,
                             x_color=x_color,
                             x_marker=x_marker))
            self._reset()

        self._stack_gifs(network_images,
                         input_images,
                         filename,
                         duration=duration)
        return
Esempio n. 33
0
    def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None):
        """
        draw the text by converting them to paths using textpath module.

        Parameters
        ----------
        prop : `matplotlib.font_manager.FontProperties`
          font property

        s : str
          text to be converted

        usetex : bool
          If True, use matplotlib usetex mode.

        ismath : bool
          If True, use mathtext parser. If "TeX", use *usetex* mode.

        """
        writer = self.writer

        writer.comment(s)

        glyph_map=self._glyph_map

        text2path = self._text2path
        color = rgb2hex(gc.get_rgb())
        fontsize = prop.get_size_in_points()

        style = {}
        if color != '#000000':
            style['fill'] = color
        if gc.get_alpha() != 1.0:
            style['opacity'] = short_float_fmt(gc.get_alpha())

        if not ismath:
            font = text2path._get_font(prop)
            _glyphs = text2path.get_glyphs_with_font(
                font, s, glyph_map=glyph_map, return_new_glyphs_only=True)
            glyph_info, glyph_map_new, rects = _glyphs

            if glyph_map_new:
                writer.start('defs')
                for char_id, glyph_path in six.iteritems(glyph_map_new):
                    path = Path(*glyph_path)
                    path_data = self._convert_path(path, simplify=False)
                    writer.element('path', id=char_id, d=path_data)
                writer.end('defs')

                glyph_map.update(glyph_map_new)

            attrib = {}
            attrib['style'] = generate_css(style)
            font_scale = fontsize / text2path.FONT_SCALE
            attrib['transform'] = generate_transform([
                ('translate', (x, y)),
                ('rotate', (-angle,)),
                ('scale', (font_scale, -font_scale))])

            writer.start('g', attrib=attrib)
            for glyph_id, xposition, yposition, scale in glyph_info:
                attrib={'xlink:href': '#%s' % glyph_id}
                if xposition != 0.0:
                    attrib['x'] = short_float_fmt(xposition)
                if yposition != 0.0:
                    attrib['y'] = short_float_fmt(yposition)
                writer.element(
                    'use',
                    attrib=attrib)

            writer.end('g')
        else:
            if ismath == "TeX":
                _glyphs = text2path.get_glyphs_tex(prop, s, glyph_map=glyph_map,
                                                   return_new_glyphs_only=True)
            else:
                _glyphs = text2path.get_glyphs_mathtext(prop, s, glyph_map=glyph_map,
                                                        return_new_glyphs_only=True)

            glyph_info, glyph_map_new, rects = _glyphs

            # we store the character glyphs w/o flipping. Instead, the
            # coordinate will be flipped when this characters are
            # used.
            if glyph_map_new:
                writer.start('defs')
                for char_id, glyph_path in six.iteritems(glyph_map_new):
                    char_id = self._adjust_char_id(char_id)
                    # Some characters are blank
                    if not len(glyph_path[0]):
                        path_data = ""
                    else:
                        path = Path(*glyph_path)
                        path_data = self._convert_path(path, simplify=False)
                    writer.element('path', id=char_id, d=path_data)
                writer.end('defs')

                glyph_map.update(glyph_map_new)

            attrib = {}
            font_scale = fontsize / text2path.FONT_SCALE
            attrib['style'] = generate_css(style)
            attrib['transform'] = generate_transform([
                ('translate', (x, y)),
                ('rotate', (-angle,)),
                ('scale', (font_scale, -font_scale))])

            writer.start('g', attrib=attrib)
            for char_id, xposition, yposition, scale in glyph_info:
                char_id = self._adjust_char_id(char_id)

                writer.element(
                    'use',
                    transform=generate_transform([
                        ('translate', (xposition, yposition)),
                        ('scale', (scale,)),
                        ]),
                    attrib={'xlink:href': '#%s' % char_id})

            for verts, codes in rects:
                path = Path(verts, codes)
                path_data = self._convert_path(path, simplify=False)
                writer.element('path', d=path_data)

            writer.end('g')
Esempio n. 34
0
def plot_tree_barplot(tree_file,
                      taxon2value_list_barplot,
                      header_list,
                      taxon2set2value_heatmap=False,
                      header_list2=False,
                      presence_only=True,
                      biodb="chlamydia_04_16",
                      column_scale=True,
                      general_max=False,
                      barplot2percentage=False):
    '''

    display one or more barplot

    :param tree_file:
    :param taxon2value_list:
    :param biodb:
    :param exclude_outgroup:
    :param bw_scale:
    :param barplot2percentage: list of bool to indicates if the number are percentages and the range should be set to 0-100

    :return:
    '''

    from chlamdb.biosqldb import manipulate_biosqldb
    import matplotlib.cm as cm
    from matplotlib.colors import rgb2hex
    import matplotlib as mpl

    server, db = manipulate_biosqldb.load_db(biodb)

    taxon2description = manipulate_biosqldb.taxon_id2genome_description(
        server, biodb, filter_names=True)

    #print isinstance(tree_file, Tree)
    #print type(tree_file)

    if isinstance(tree_file, Tree):
        t1 = tree_file
    else:
        t1 = Tree(tree_file)

    # Calculate the midpoint node
    R = t1.get_midpoint_outgroup()
    # and set it as tree outgroup
    t1.set_outgroup(R)

    tss = TreeStyle()
    value = 1
    tss.draw_guiding_lines = True
    tss.guiding_lines_color = "gray"
    tss.show_leaf_name = False

    if column_scale and header_list2:
        import matplotlib.cm as cm
        from matplotlib.colors import rgb2hex
        import matplotlib as mpl
        column2scale = {}
        for column in header_list2:
            values = taxon2set2value_heatmap[column].values()

            norm = mpl.colors.Normalize(vmin=min(values), vmax=max(values))
            cmap = cm.OrRd
            m = cm.ScalarMappable(norm=norm, cmap=cmap)
            column2scale[column] = m

    cmap = cm.YlGnBu  #YlOrRd#OrRd

    values_lists = taxon2value_list_barplot.values()

    scale_list = []
    max_value_list = []

    for n, header in enumerate(header_list):
        #print 'scale', n, header
        data = [float(i[n]) for i in values_lists]

        if barplot2percentage is False:
            max_value = max(data)  #3424182#
            min_value = min(data)  #48.23
        else:
            if barplot2percentage[n] is True:
                max_value = 100
                min_value = 0
            else:
                max_value = max(data)  #3424182#
                min_value = min(data)  #48.23
        norm = mpl.colors.Normalize(vmin=min_value, vmax=max_value)
        m1 = cm.ScalarMappable(norm=norm, cmap=cmap)
        scale_list.append(m1)
        if not general_max:
            max_value_list.append(float(max_value))
        else:
            max_value_list.append(general_max)

    for i, lf in enumerate(t1.iter_leaves()):

        #if taxon2description[lf.name] == 'Pirellula staleyi DSM 6068':
        #    lf.name = 'Pirellula staleyi DSM 6068'
        #    continue
        if i == 0:

            col_add = 0
            for col, header in enumerate(header_list):

                #lf.add_face(n, column, position="aligned")
                n = TextFace(' ')
                n.margin_top = 1
                n.margin_right = 2
                n.margin_left = 2
                n.margin_bottom = 1
                n.rotation = 90
                n.inner_background.color = "white"
                n.opacity = 1.
                n.hz_align = 2
                n.vt_align = 2

                tss.aligned_header.add_face(n, col_add)

                n = TextFace('%s' % header)
                n.margin_top = 1
                n.margin_right = 2
                n.margin_left = 2
                n.margin_bottom = 80
                n.rotation = 270
                n.inner_background.color = "white"
                n.opacity = 1.
                n.hz_align = 2
                n.vt_align = 2
                tss.aligned_header.add_face(n, col_add + 1)
                col_add += 2

            if header_list2:
                for col, header in enumerate(header_list2):
                    n = TextFace('%s' % header)
                    n.margin_top = 1
                    n.margin_right = 20
                    n.margin_left = 2
                    n.margin_bottom = 1
                    n.rotation = 270
                    n.hz_align = 2
                    n.vt_align = 2
                    n.inner_background.color = "white"
                    n.opacity = 1.
                    tss.aligned_header.add_face(n, col + col_add)

        try:
            val_list = taxon2value_list_barplot[lf.name]
        except:
            try:
                val_list = taxon2value_list_barplot[int(lf.name)]
            except:
                val_list = [0]
        col_add = 0
        for col, value in enumerate(val_list):

            # show value itself
            try:
                n = TextFace('  %s  ' % str(value))
            except:
                n = TextFace('  %s  ' % str(value))
            n.margin_top = 1
            n.margin_right = 10
            n.margin_left = 2
            n.margin_bottom = 1
            n.inner_background.color = "white"
            n.opacity = 1.

            lf.add_face(n, col_add, position="aligned")
            # show bar

            color = rgb2hex(scale_list[col].to_rgba(float(value)))
            try:
                percentage = (value / max_value_list[col]) * 100
                #percentage = value
            except:
                percentage = 0
            maximum_bar = (
                (max_value_list[col] - value) / max_value_list[col]) * 100
            #maximum_bar = 100-percentage
            b = StackedBarFace([percentage, maximum_bar],
                               width=100,
                               height=10,
                               colors=[color, "white"])
            b.rotation = 0
            b.inner_border.color = "grey"
            b.inner_border.width = 0
            b.margin_right = 15
            b.margin_left = 0
            lf.add_face(b, col_add + 1, position="aligned")
            col_add += 2

        if taxon2set2value_heatmap:
            shift = col + col_add + 1

            i = 0
            for col, col_name in enumerate(header_list2):
                try:
                    value = taxon2set2value_heatmap[col_name][lf.name]
                except:
                    try:
                        value = taxon2set2value_heatmap[col_name][int(lf.name)]
                    except:
                        value = 0

                if int(value) > 0:
                    if int(value) > 9:
                        n = TextFace(' %i ' % int(value))
                    else:
                        n = TextFace(' %i   ' % int(value))
                    n.margin_top = 1
                    n.margin_right = 1
                    n.margin_left = 20
                    n.margin_bottom = 1
                    n.fgcolor = "white"
                    n.inner_background.color = rgb2hex(
                        column2scale[col_name].to_rgba(
                            float(value)))  #"orange"
                    n.opacity = 1.
                    lf.add_face(n, col + col_add, position="aligned")
                    i += 1
                else:
                    n = TextFace('  ')  #% str(value))
                    n.margin_top = 1
                    n.margin_right = 1
                    n.margin_left = 20
                    n.margin_bottom = 1
                    n.inner_background.color = "white"
                    n.opacity = 1.

                    lf.add_face(n, col + col_add, position="aligned")

        #lf.name = taxon2description[lf.name]
        try:
            n = TextFace(taxon2description[lf.name],
                         fgcolor="black",
                         fsize=12,
                         fstyle='italic')
        except:
            n = TextFace(lf.name, fgcolor="black", fsize=12, fstyle='italic')
        lf.add_face(n, 0)

    for n in t1.traverse():
        nstyle = NodeStyle()
        if n.support < 1:
            nstyle["fgcolor"] = "black"
            nstyle["size"] = 6
            n.set_style(nstyle)
        else:
            nstyle["fgcolor"] = "red"
            nstyle["size"] = 0
            n.set_style(nstyle)
    #print t1
    return t1, tss
Esempio n. 35
0
provinces = m.states_info
statenames =[]
colors = {}
cmap = plt.cm.YlOrRd
vmax = 100000000
vmin = 3000000

for each_province in provinces:
    province_name = each_province['NL_NAME_1']
    p = province_name.split('|')
    if len(p) > 1:
        s = p[1]
    else:
        s = p[0]
    s = s[:2]
    if s == '黑龍':
        s = '黑龙江'
    if s == '内蒙':
        s = '内蒙古'
    statenames.append(s)
    pop = df['人口数'][s]
    colors[s] = cmap(np.sqrt((pop - vmin) / (vmax - vmin)))[:3]

ax = plt.gca()
for nshape, seg in enumerate(m.states):
    color = rgb2hex(colors[statenames[nshape]])
    poly = Polygon(seg, facecolor=color, edgecolor=color)
    ax.add_patch(poly)

plt.show()
Esempio n. 36
0
    def plot_geneset_scores(self,
                            geneset,
                            filename=None,
                            cmap='Greens',
                            vmin=None,
                            vmax=None,
                            border_cmap=None,
                            border_scores=None,
                            penwidth=10,
                            legend_title=None,
                            color_edges=True,
                            edge_cmap='RdGy',
                            edge_filter=.2,
                            makeColorbars=False,
                            colorbar_title=None,
                            border_colorbar_title=None,
                            dotprog='dot'):
        """Plot a geneset network with Graphiz

        Args:
            geneset (set): Set of genes that will be plotted.
            filename (str): filename path, should end in '.svg'.
            cmap (str): matplotlib colormap name.
            vmin (float): minimum value for cmap normalization.
                lower scores will not be distinguishable.
            vmax (float): maximum value for cmap normalization, 
                higher scores will not be distinguishable.
            border_cmap (str): colormap for the border.
            border_scores (pd.Series): Instead of the original scores, 
                put in a different metric for border color.
            penwidth (int): the size of the border line around the gene.
            legend_title (str): Title for legend.
            color_edges (bool): Use netwink correlation data for coloring edges.
            edge_cmap (str): If color_edges, which cmap to use.
            edge_filter (float): If color_edges, edges with absolute correlation
                smaller than edge_filter will be filtered. Allows to make more
                comprehensible graphs.
            makeColorbars (bool): If true, make matplotlib figures with the colorbars used.

        Todo:
            * add gradient legend -> dot fillcolor="orange:yellow"
              or generating color bar legend with matplotlib and then referencing that image
            * look into other (python) graph visualizers such as igraph, graph-tool
        """
        # Collect data
        nodes = pd.Index(self.netwink.get_nodes_series())
        originalScores = self.netwink.scoresVector
        diffusedScores = (originalScores @ self.computedMatrix).T
        # Setup colors
        import pydot
        import matplotlib as mpl, tempfile
        from matplotlib.colors import rgb2hex
        from bidali.visualizations import labelcolor_matching_backgroundcolor
        vmin = vmin if vmin else originalScores.min()
        vmax = vmax if vmax else originalScores.max()
        norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
        cmap = plt.get_cmap(cmap)
        fill_color = lambda x: cmap(norm(x))
        if border_scores is not None:
            border_vmin = border_scores.min()
            border_vmax = border_scores.max()
            border_norm = mpl.colors.Normalize(vmin=border_vmin,
                                               vmax=border_vmax)
            border_cmap = plt.get_cmap(border_cmap) if border_cmap else cmap
            border_color = lambda x: border_cmap(border_norm(x))
        else:
            border_color = fill_color
        if makeColorbars:
            # Reference: https://matplotlib.org/examples/api/colorbar_only.html
            cbarfig, cbax = plt.subplots(
                nrows=1 if border_scores is None else 2,
                ncols=1,
                figsize=(5, 2))
            cbarfig.tight_layout()
            if border_scores is not None:
                cbax, cboax = cbax
                mpl.colorbar.ColorbarBase(cboax,
                                          cmap=border_cmap,
                                          norm=border_norm,
                                          orientation='horizontal')
                cboax.set_xlabel(border_colorbar_title
                                 or 'Border score colorbar')
            mpl.colorbar.ColorbarBase(cbax,
                                      cmap=cmap,
                                      norm=norm,
                                      orientation='horizontal')
            cbax.set_xlabel(colorbar_title or 'Center score colorbar')
            # Write out to tempfile
            tf = tempfile.NamedTemporaryFile(suffix='.png')
            print(tf.name)
            tf.close()
            cbarfig.savefig(tf.name)
            plt.close(
                cbarfig)  #closing figure as downstream only file ref needed
            graphlegend = pydot.Cluster(
                graph_name="legend",
                label=legend_title if legend_title else "Color legend",
                fontsize="15",
                color="blue",
                style="filled",
                fillcolor="lightgrey",
                rankdir="LR")
            colorbarnode = pydot.Node('colorbars',
                                      label='',
                                      shape="box",
                                      image=tf.name)
            graphlegend.add_node(colorbarnode)
        # Setup graph
        subgraph = self.netwink.graph.subgraph(geneset)
        dotgraph = nx.drawing.nx_pydot.to_pydot(subgraph)
        for n in dotgraph.get_nodes():
            gene = n.get_name()
            gene_loc = nodes.get_loc(gene)
            n.set_penwidth(10)
            n.set_style('filled')
            fillcolortuple = fill_color(diffusedScores[gene_loc, 0])
            n.set_fillcolor(rgb2hex(fillcolortuple))
            n.set_color(
                rgb2hex(
                    border_color((originalScores if border_scores is None else
                                  border_scores)[gene_loc])))
            n.set_fontcolor(
                rgb2hex(labelcolor_matching_backgroundcolor(fillcolortuple)))
            # If there are negative scores, set different shape
            if diffusedScores[gene_loc, 0] < 0:
                n.set_shape('diamond')
        if color_edges:
            for e in dotgraph.get_edges():
                edge_norm = mpl.colors.Normalize(vmin=-1, vmax=1)
                edge_cmap = plt.get_cmap(edge_cmap)
                edge_color = lambda x: edge_cmap(edge_norm(x))
                try:
                    corr = self.netwink.correlations[e.get_source()][
                        e.get_destination()]
                    if abs(corr) < edge_filter:
                        dotgraph.del_edge(e.get_source(), e.get_destination())
                    else:
                        e.set_color(rgb2hex(edge_color(corr)))
                        if corr < 0: e.set_style('dashed')
                except KeyError:
                    # No correlation info as source or target not in expression data
                    e.set_style('dotted')

        # Create color legend
        #graphlegend = pydot.Cluster(
        #    graph_name="legend", label=legend_title if legend_title else "Color legend",
        #    fontsize="15", color="blue", style="filled", fillcolor="lightgrey", rankdir="LR"
        #)
        #minnode = pydot.Node('min', label="Min: {:.2f}".format(vmin), style="filled",
        #                     fontcolor=rgb2hex(labelcolor_matching_backgroundcolor(cmap(norm(vmin)))),
        #                     fillcolor=rgb2hex(cmap(norm(vmin))),
        #                     shape="Mrecord", rank="same"
        #)
        #graphlegend.add_node(minnode)
        #maxnode = pydot.Node('max', label="Max: {:.2f}".format(vmax), style="filled",
        #                     fontcolor=rgb2hex(labelcolor_matching_backgroundcolor(cmap(norm(vmax)))),
        #                     fillcolor=rgb2hex(cmap(norm(vmax))), shape="Mrecord", rank="same"
        #)
        #graphlegend.add_node(maxnode)
        #graphlegend.add_edge(pydot.Edge(minnode, maxnode, style="invis"))
        dotgraph.add_subgraph(graphlegend)

        # Graph output
        if filename:
            if filename.endswith('.svg'):
                dotgraph.write_svg(filename, prog=dotprog)
            elif filename.endswith('.png'):
                dotgraph.write_png(filename, prog=dotprog)
            else:
                raise TypeError('Only svg or png file types can be written.',
                                filename)
        else:
            import io
            import matplotlib.image as mpimg
            from PIL import Image
            png = io.BytesIO(dotgraph.create_png(prog=dotprog))
            img = Image.open(png)
            #img.thumbnail(resize, Image.ANTIALIAS)
            img.show()
            #imgplot = plt.imshow(mpimg.imread(png))
            #imgplot.get_figure().axes[0].axis('off')
            #return imgplot

        return dotgraph
Esempio n. 37
0
    def draw_candmap_scale(self, title):
        """ 
    Draw a scale hotmap based on the difference of votes between two candidates.

    :param title: The title of scale hotmap
    """
        plt.figure()
        m = Basemap(llcrnrlon=-119,
                    llcrnrlat=22,
                    urcrnrlon=-64,
                    urcrnrlat=49,
                    projection='lcc',
                    lat_1=33,
                    lat_2=45,
                    lon_0=-95)
        # draw state boundaries.
        # data from U.S Census Bureau
        # http://www.census.gov/geo/www/cob/st2000.html
        shp_info = m.readshapefile('datasets/st99_d00',
                                   'states',
                                   drawbounds=True)
        # choose a color for each state based on population density.
        colors = {}
        statenames = []
        cmap = plt.cm.seismic
        norm = mpl.colors.Normalize(vmin=0, vmax=1)
        msm = cm.ScalarMappable(norm=norm, cmap=cmap)
        candidate1 = None
        candidate2 = None
        # print(m.states_info[0].keys())
        for shapedict in m.states_info:
            statename = shapedict['NAME']
            statenames.append(statename)
            # skip DC and Puerto Rico.
            if statename not in ['District of Columbia', 'Puerto Rico']:
                if statename not in self.density_scale:
                    colors[statename] = list(msm.to_rgba(0.5)[:3])
                    continue
                den = self.density_scale[statename]

                cand1 = None
                cand2 = None
                score1 = None
                score2 = None
                for c, s in den.items():
                    if cand1:
                        cand2 = c
                        score2 = s
                    else:
                        cand1 = c
                        score1 = s

                if not candidate1:
                    candidate1 = cand1

                if not candidate2:
                    candidate2 = cand2

                if not cand1:
                    colors[statename] = list(msm.to_rgba(0)[:3])
                    continue
                elif not cand2:
                    colors[statename] = list(msm.to_rgba(1)[:3])
                    continue

                delta = 0
                if (score1 < 0) and (score2 < 0):
                    score1, score2 = score2, score1
                    score1 = -score1
                    score2 = -score2
                if (score1 < 0) or (score2 < 0):
                    delta = -min(score1, score2)
                if (score1 == 0 and score2 == 0):
                    colors[statename] = list(msm.to_rgba(0.5)[:3])
                    continue

                normalized_cand1 = float(score1 + delta)
                normalized_cand2 = float(score2 + delta)

                fraction_cand1 = normalized_cand1 / (normalized_cand1 +
                                                     normalized_cand2)
                fraction_cand2 = 1 - fraction_cand1
                colors[statename] = list(msm.to_rgba(fraction_cand1)[:3])
        # cycle through state names, color each one.
        ax = plt.gca()  # get current axes instance
        for nshape, seg in enumerate(m.states):
            # skip DC and Puerto Rico.
            if statenames[nshape] not in [
                    'District of Columbia', 'Puerto Rico'
            ]:
                color = rgb2hex(colors[statenames[nshape]])
                poly = Polygon(seg, facecolor=color, edgecolor=color)
                ax.add_patch(poly)
        # draw meridians and parallels.
        m.drawparallels(np.arange(25, 65, 20), labels=[1, 0, 0, 0])
        m.drawmeridians(np.arange(-120, -40, 20), labels=[0, 0, 0, 1])
        plt.title(title)
        red_patch = mpatches.Patch(color='r', label=candidate1)
        blue_patch = mpatches.Patch(color='b', label=candidate2)
        plt.legend(handles=[blue_patch, red_patch])
        plt.draw()
Esempio n. 38
0
    def draw_hotmap(self, title, blue=True):
        """ 
    Draw a hotmap based on the counts of pseudo vote on each state.

    :param title: The title of the hotmao
    :param blue: The choosed color, True for blue and False for red.
    """
        plt.figure()
        m = Basemap(llcrnrlon=-119,
                    llcrnrlat=22,
                    urcrnrlon=-64,
                    urcrnrlat=49,
                    projection='lcc',
                    lat_1=33,
                    lat_2=45,
                    lon_0=-95)
        # draw state boundaries.
        # data from U.S Census Bureau
        # http://www.census.gov/geo/www/cob/st2000.html
        shp_info = m.readshapefile('datasets/st99_d00',
                                   'states',
                                   drawbounds=True)
        # population density by state from
        # http://en.wikipedia.org/wiki/List_of_U.S._states_by_population_density

        # set the range to normalize
        vmax = -float("inf")
        vmin = float("inf")
        for k, v in self.density.items():
            if v > vmax:
                vmax = v
            elif v < vmin:
                vmin = v

        # normalize again if vmin < 0
        # if vmin < 0:
        #   for k, v in self.density.items():
        #     self.density[k] -= vmin
        #   vmax -= vmin
        #   vmin = 0

        # choose a color for each state based on population density.
        colors = {}
        statenames = []
        if blue:
            cmap = plt.cm.Blues_r
        else:
            cmap = plt.cm.hot

        # print(m.states_info[0].keys())
        for shapedict in m.states_info:
            statename = shapedict['NAME']
            # skip DC and Puerto Rico.
            if statename not in ['District of Columbia', 'Puerto Rico']:
                den = self.density[statename]
                # calling colormap with value between 0 and 1 returns
                # rgba value.  Invert color range (hot colors are high
                # population), take sqrt root to spread out colors more.
                colors[statename] = list(
                    cmap(1. - np.sqrt((den - vmin) / (vmax - vmin)))[:3])
            statenames.append(statename)
        # cycle through state names, color each one.
        ax = plt.gca()  # get current axes instance
        for nshape, seg in enumerate(m.states):
            # skip DC and Puerto Rico.
            if statenames[nshape] not in [
                    'District of Columbia', 'Puerto Rico'
            ]:
                color = rgb2hex(colors[statenames[nshape]])
                poly = Polygon(seg, facecolor=color, edgecolor=color)
                ax.add_patch(poly)
        # draw meridians and parallels.
        m.drawparallels(np.arange(25, 65, 20), labels=[1, 0, 0, 0])
        m.drawmeridians(np.arange(-120, -40, 20), labels=[0, 0, 0, 1])
        plt.title(title)
        plt.draw()
Esempio n. 39
0
 def entropy_color(entropy):
     rgb = cm.RdGy((entropy - min_s) / (max_s - min_s))
     return colors.rgb2hex(rgb)
Esempio n. 40
0
# Group and count main names of columns
pd.DataFrame.from_dict(Counter(
    [col.split('-')[0].split('(')[0] for col in both_df.columns]),
                       orient='index').rename(columns={
                           0: 'count'
                       }).sort_values('count', ascending=False)
# Get null values and dataframe information
print('Null Values In DataFrame: {}\n'.format(both_df.isna().sum().sum()))
both_df.info()
# Plotting data
label_counts = label.value_counts()

# Get colors
n = label_counts.shape[0]
colormap = get_cmap('viridis')
colors = [rgb2hex(colormap(col)) for col in np.arange(0, 1.01, 1 / (n - 1))]

# Create plot
data = go.Bar(x=label_counts.index, y=label_counts, marker=dict(color=colors))

layout = go.Layout(title='Smartphone Activity Label Distribution',
                   xaxis=dict(title='Activity'),
                   yaxis=dict(title='Count'))

fig = go.Figure(data=[data], layout=layout)
iplot(fig)
# Create datasets
tsne_data = both_df.copy()
data_data = tsne_data.pop('Data')
subject_data = tsne_data.pop('subject')
colormap = cm.jet
label_ids_unique = np.unique(y)
label_ids = y

n_components = 2
fig = plt.figure(1, figsize=(20, 20))
plt.clf()
if n_components == 3:
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(X_z[:, 0], X_z[:, 1], X_z[:, 2], c=y, cmap='jet')
if n_components == 2:
    ax = fig.add_subplot(111)
    ax.scatter(X_z[:, 0], X_z[:, 1], c=y, cmap='jet')

colorlist_unique = [
    ml_colors.rgb2hex(colormap(a))
    for a in label_ids_unique / float(max(label_ids))
]
patches = [
    Line2D([0], [0], marker='o', color='gray', label=a, markerfacecolor=c)
    for a, c in zip(trainset.get_labels_unique(), colorlist_unique)
]
ax.legend(handles=patches)

plt.savefig(
    os.path.join(constants.BASE_PROFILE, "output", "AE_by_samples_sc_z.png"))

n_components = 2
fig = plt.figure(1, figsize=(20, 20))
plt.clf()
if n_components == 3:
Esempio n. 42
0
def colors_at_breaks(cmap, breaks):
    return [rgb2hex(cmap[bb]) for bb in breaks]
Esempio n. 43
0
def main(datasets, algos):

    colormap = cm.rainbow
    colorlist = [ml_colors.rgb2hex(colormap(i)) for i in
                 np.array(list(range(len(algos)))) / float(len(algos) - 1)]
    df_matrix = pd.DataFrame()
    df_summary = pd.DataFrame()
    for cur_ds in datasets:

        constants.update_dirs(DATASET_NAME_u=cur_ds)
        total_num_genes=[]
        avg_num_genes=[]
        std_num_genes=[]
        algos_signals=[]
        algo_go_sims = []

        for i_algo, cur_algo in enumerate(algos):
            print "current aggregation: {}, {}".format(cur_ds,cur_algo)
            try:
                total_num_genes.append(pd.read_csv(
                    os.path.join(constants.OUTPUT_GLOBAL_DIR, constants.DATASET_NAME, cur_algo, "all_modules_general.tsv"),
                    sep="\t")["total_num_genes"][0])
                avg_num_genes.append(pd.read_csv(
                    os.path.join(constants.OUTPUT_GLOBAL_DIR, constants.DATASET_NAME, cur_algo,
                                 "modules_summary.tsv"),
                    sep="\t")["#_genes"].mean())
                std_num_genes.append(pd.read_csv(
                    os.path.join(constants.OUTPUT_GLOBAL_DIR, constants.DATASET_NAME, cur_algo,
                                 "modules_summary.tsv"),
                    sep="\t")["#_genes"].std())
            except:
                print "no genes were found for: {}, {}".format(cur_ds, cur_algo)
                total_num_genes.append(0)
            algos_signals.append(float(file(os.path.join(constants.OUTPUT_GLOBAL_DIR, "emp_fdr", "ds_2_alg_scores",
                              "{}_{}_{}".format(cur_ds, cur_algo, "n_sig.txt"))).read()))
            algo_go_sims.append(float(file(os.path.join(constants.OUTPUT_GLOBAL_DIR, "emp_fdr", "ds_2_alg_scores",
                                                       "{}_{}_{}".format(cur_ds, cur_algo, "var.txt"))).read()))

        fig, ax = plt.subplots(figsize=(10, 10))

        print "all data: \n{}\n{}\n{}\n{}".format(algos_signals, algo_go_sims, algos, total_num_genes)
        for h, s, c, a, gene_size, module_mean, module_std in zip(algos_signals, algo_go_sims, colorlist, algos,
                                         total_num_genes, avg_num_genes, std_num_genes):  # [0 for x in range(len(algo_go_sim_score))]
            print (h, s)
            ax.scatter(h, s, s=(50 + 2000 * (float(gene_size) / (1+np.max(total_num_genes)))),
                       c=c, cmap='jet', label=a)
            df_series=pd.Series({"algo": a, "dataset": cur_ds, "sig_terms": h,
                       "sig_terms_rank": pd.Series(np.array(algos_signals)).rank(ascending=0).values[
                           np.where(np.array(algos_signals) == h)[0][0]], "variability": s,
                       "variability_rank": pd.Series(np.array(algo_go_sims)).rank(ascending=0).values[
                           np.where((np.array(algo_go_sims)) == s)[0][0]], "n_genes": gene_size, "module_size_mean": module_mean, "module_size_std": module_std})
            df_series.name = "{}_{}".format(cur_ds, a)
            df_summary=df_summary.append(df_series)
            df_matrix.loc[a, cur_ds]=h
            colorlist = [ml_colors.rgb2hex(colormap(i)) for i in
                         np.array(list(range(len(algos)))) / float(len(algos) - 1)]
            patches = [Line2D([0], [0], marker='o', color='gray', label=a,
                              markerfacecolor=c) for i, a, c in zip(list(range(len(algos))), algos, colorlist)]
            ax.set_xlabel("# GO terms (-log10(qval)) above threshold")
            ax.set_ylabel("GO terms variability")
            ax.legend(handles=patches)
            ax.grid(True)
        plt.savefig(os.path.join(constants.OUTPUT_GLOBAL_DIR,
                                 "hs_plot_terms_signal_algo_{}.png".format(constants.DATASET_NAME)))
    return df_summary, df_matrix
Esempio n. 44
0
 def css(rgba):
     dark = relative_luminance(rgba) < text_color_threshold
     text_color = '#f1f1f1' if dark else '#000000'
     return 'background-color: {b};color: {c};'.format(
         b=colors.rgb2hex(rgba), c=text_color)
Esempio n. 45
0
def plot_tree_stacked_barplot(
        tree_file,
        taxon2value_list_barplot=False,
        header_list=False,  # header stackedbarplots
        taxon2set2value_heatmap=False,
        taxon2label=False,
        header_list2=False,  # header counts columns
        biodb=False,
        column_scale=True,
        general_max=False,
        header_list3=False,
        set2taxon2value_list_simple_barplot=False,
        set2taxon2value_list_simple_barplot_counts=True,
        rotate=False,
        taxon2description=False):
    '''

    taxon2value_list_barplot list of lists:
    [[bar1_part1, bar1_part2,...],[bar2_part1, bar2_part2]]
    valeures de chaque liste transformes en pourcentages

    :param tree_file:
    :param taxon2value_list:
    :param biodb:
    :param exclude_outgroup:
    :param bw_scale:
    :return:
    '''

    if biodb:
        from chlamdb.biosqldb import manipulate_biosqldb
        server, db = manipulate_biosqldb.load_db(biodb)

        taxon2description = manipulate_biosqldb.taxon_id2genome_description(
            server, biodb, filter_names=True)

    t1 = Tree(tree_file)

    # Calculate the midpoint node
    R = t1.get_midpoint_outgroup()
    # and set it as tree outgroup
    t1.set_outgroup(R)

    colors2 = [
        "red", "#FFFF00", "#58FA58", "#819FF7", "#F781F3", "#2E2E2E",
        "#F7F8E0", 'black'
    ]
    colors = [
        "#7fc97f", "#386cb0", "#fdc086", "#ffffb3", "#fdb462", "#f0027f",
        "#F7F8E0", 'black'
    ]  # fdc086ff 386cb0ff f0027fff

    tss = TreeStyle()
    tss.draw_guiding_lines = True
    tss.guiding_lines_color = "gray"
    tss.show_leaf_name = False
    if column_scale and header_list2:
        import matplotlib.cm as cm
        from matplotlib.colors import rgb2hex
        import matplotlib as mpl
        column2scale = {}
        col_n = 0
        for column in header_list2:
            values = taxon2set2value_heatmap[column].values()
            #print values
            if min(values) == max(values):
                min_val = 0
                max_val = 1.5 * max(values)
            else:
                min_val = min(values)
                max_val = max(values)
            #print 'min-max', min_val, max_val
            norm = mpl.colors.Normalize(vmin=min_val, vmax=max_val)  # *1.1
            if col_n < 4:
                cmap = cm.OrRd  #
            else:
                cmap = cm.YlGnBu  #PuBu#OrRd

            m = cm.ScalarMappable(norm=norm, cmap=cmap)

            column2scale[column] = [m, float(max_val)]  # *0.7
            col_n += 1

    for i, lf in enumerate(t1.iter_leaves()):

        #if taxon2description[lf.name] == 'Pirellula staleyi DSM 6068':
        #    lf.name = 'Pirellula staleyi DSM 6068'
        #    continue
        if i == 0:

            if taxon2label:
                n = TextFace('  ')
                n.margin_top = 1
                n.margin_right = 1
                n.margin_left = 20
                n.margin_bottom = 1
                n.hz_align = 2
                n.vt_align = 2
                n.rotation = 270
                n.inner_background.color = "white"
                n.opacity = 1.

                tss.aligned_header.add_face(n, 0)
                col_add = 1
            else:
                col_add = 1
            if header_list:
                for col, header in enumerate(header_list):

                    n = TextFace('%s' % (header))
                    n.margin_top = 0
                    n.margin_right = 1
                    n.margin_left = 20
                    n.margin_bottom = 1
                    n.rotation = 270
                    n.hz_align = 2
                    n.vt_align = 2
                    n.inner_background.color = "white"
                    n.opacity = 1.
                    tss.aligned_header.add_face(n, col + col_add)
                col_add += col + 1

            if header_list3:
                #print 'header_list 3!'
                col_tmp = 0
                for header in header_list3:
                    n = TextFace('%s' % (header))
                    n.margin_top = 1
                    n.margin_right = 1
                    n.margin_left = 20
                    n.margin_bottom = 1
                    n.rotation = 270
                    n.hz_align = 2
                    n.vt_align = 2
                    n.inner_background.color = "white"
                    n.opacity = 1.

                    if set2taxon2value_list_simple_barplot_counts:
                        if col_tmp == 0:
                            col_tmp += 1
                        tss.aligned_header.add_face(n, col_tmp + 1 + col_add)
                        n = TextFace('       ')
                        tss.aligned_header.add_face(n, col_tmp + col_add)
                        col_tmp += 2
                    else:
                        tss.aligned_header.add_face(n, col_tmp + col_add)
                        col_tmp += 1
                if set2taxon2value_list_simple_barplot_counts:
                    col_add += col_tmp
                else:
                    col_add += col_tmp

            if header_list2:
                for col, header in enumerate(header_list2):
                    n = TextFace('%s' % (header))
                    n.margin_top = 1
                    n.margin_right = 1
                    n.margin_left = 20
                    n.margin_bottom = 1
                    n.rotation = 270
                    n.hz_align = 2
                    n.vt_align = 2
                    n.inner_background.color = "white"
                    n.opacity = 1.
                    tss.aligned_header.add_face(n, col + col_add)
                col_add += col + 1

        if taxon2label:
            try:
                n = TextFace('%s' % taxon2label[lf.name])
            except:
                try:
                    n = TextFace('%s' % taxon2label[int(lf.name)])
                except:
                    n = TextFace('-')
            n.margin_top = 1
            n.margin_right = 1
            n.margin_left = 20
            n.margin_bottom = 1
            n.inner_background.color = "white"
            n.opacity = 1.
            if rotate:
                n.rotation = 270
            lf.add_face(n, 1, position="aligned")
            col_add = 2
        else:
            col_add = 2

        if taxon2value_list_barplot:

            try:
                val_list_of_lists = taxon2value_list_barplot[lf.name]
            except:
                val_list_of_lists = taxon2value_list_barplot[int(lf.name)]

            #col_count = 0
            for col, value_list in enumerate(val_list_of_lists):

                total = float(sum(value_list))
                percentages = [(i / total) * 100 for i in value_list]
                if col % 3 == 0:
                    col_list = colors2
                else:
                    col_list = colors
                b = StackedBarFace(percentages,
                                   width=150,
                                   height=18,
                                   colors=col_list[0:len(percentages)])
                b.rotation = 0
                b.inner_border.color = "white"
                b.inner_border.width = 0
                b.margin_right = 5
                b.margin_left = 5
                if rotate:
                    b.rotation = 270
                lf.add_face(b, col + col_add, position="aligned")
                #col_count+=1

            col_add += col + 1

        if set2taxon2value_list_simple_barplot:
            col_list = [
                '#fc8d59', '#91bfdb', '#99d594', '#c51b7d', '#f1a340',
                '#999999'
            ]
            color_i = 0
            col = 0
            for one_set in header_list3:
                if color_i > 5:
                    color_i = 0
                color = col_list[color_i]
                color_i += 1
                # values for all taxons
                values_lists = [
                    float(i) for i in
                    set2taxon2value_list_simple_barplot[one_set].values()
                ]
                #print values_lists
                #print one_set
                value = set2taxon2value_list_simple_barplot[one_set][lf.name]

                if set2taxon2value_list_simple_barplot_counts:
                    if isinstance(value, float):
                        a = TextFace(" %s " % str(round(value, 2)))
                    else:
                        a = TextFace(" %s " % str(value))
                    a.margin_top = 1
                    a.margin_right = 2
                    a.margin_left = 5
                    a.margin_bottom = 1
                    if rotate:
                        a.rotation = 270
                    lf.add_face(a, col + col_add, position="aligned")

                #print 'value and max', value, max(values_lists)
                fraction_biggest = (float(value) / max(values_lists)) * 100
                fraction_rest = 100 - fraction_biggest

                #print 'fractions', fraction_biggest, fraction_rest
                b = StackedBarFace([fraction_biggest, fraction_rest],
                                   width=100,
                                   height=15,
                                   colors=[color, 'white'])
                b.rotation = 0
                b.inner_border.color = "grey"
                b.inner_border.width = 0
                b.margin_right = 15
                b.margin_left = 0
                if rotate:
                    b.rotation = 270
                if set2taxon2value_list_simple_barplot_counts:
                    if col == 0:
                        col += 1
                    lf.add_face(b, col + 1 + col_add, position="aligned")
                    col += 2
                else:
                    lf.add_face(b, col + col_add, position="aligned")
                    col += 1
            if set2taxon2value_list_simple_barplot_counts:
                col_add += col

            else:
                col_add += col

        if taxon2set2value_heatmap:
            i = 0
            #if not taxon2label:
            #    col_add-=1
            for col2, head in enumerate(header_list2):

                col_name = header_list2[i]
                try:
                    value = taxon2set2value_heatmap[col_name][str(lf.name)]
                except:
                    try:
                        value = taxon2set2value_heatmap[col_name][round(
                            float(lf.name), 2)]
                    except:
                        value = 0
                if header_list2[i] == 'duplicates':
                    print('dupli', lf.name, value)
                #print 'val----------------', value
                if int(value) > 0:
                    if int(value) >= 10 and int(value) < 100:
                        n = TextFace('%4i' % value)
                    elif int(value) >= 100:
                        n = TextFace('%3i' % value)
                    else:

                        n = TextFace('%5i' % value)

                    n.margin_top = 1
                    n.margin_right = 2
                    n.margin_left = 5
                    n.margin_bottom = 1
                    n.hz_align = 1
                    n.vt_align = 1
                    if rotate:
                        n.rotation = 270
                    n.inner_background.color = rgb2hex(
                        column2scale[col_name][0].to_rgba(
                            float(value)))  #"orange"
                    #print 'xaxaxaxaxa', value,
                    if float(value) > column2scale[col_name][1]:

                        n.fgcolor = 'white'
                    n.opacity = 1.
                    n.hz_align = 1
                    n.vt_align = 1
                    lf.add_face(n, col2 + col_add, position="aligned")
                    i += 1
                else:
                    n = TextFace('')
                    n.margin_top = 1
                    n.margin_right = 1
                    n.margin_left = 5
                    n.margin_bottom = 1
                    n.inner_background.color = "white"
                    n.opacity = 1.
                    if rotate:
                        n.rotation = 270
                    lf.add_face(n, col2 + col_add, position="aligned")
                    i += 1

        #lf.name = taxon2description[lf.name]
        n = TextFace(taxon2description[lf.name],
                     fgcolor="black",
                     fsize=12,
                     fstyle='italic')
        lf.add_face(n, 0)

    for n in t1.traverse():
        nstyle = NodeStyle()

        if n.support < 1:
            nstyle["fgcolor"] = "black"
            nstyle["size"] = 6
            n.set_style(nstyle)
        else:
            nstyle["fgcolor"] = "red"
            nstyle["size"] = 0
            n.set_style(nstyle)

    return t1, tss
Esempio n. 46
0
    def __init__(self, parent=None, text=None):
        super(MplLabelDialog, self).__init__(parent)
        
        self.setWindowTitle('Edit text')
        self.setWindowIcon(QtGui.QIcon(':/font_32x32.png'))
        
        layout = QtGui.QVBoxLayout(self)
        
        #self.tab_widget = QtGui.QTabWidget()
        #self.tab_widget.addTab(self, 'test')
        #
        self.font_label = QtGui.QLabel('Font Family:')
        self.size_label = QtGui.QLabel('Size:')
        self.text_label = QtGui.QLabel('Label:')
        self.color_label = QtGui.QLabel('Color:')
        self.alpha_label = QtGui.QLabel('Alpha:')
        self.fill_color_label = QtGui.QLabel("Background color:")
        self.fill_alpha_label = QtGui.QLabel("Background alpha:")
        
        self.font_combo = QtGui.QComboBox()
        self.color_combo = QtGui.QComboBox()
        self.text_edit = QtGui.QLineEdit()
        self.size_spin_box = QtGui.QSpinBox()
        self.alpha_spin_box = QtGui.QDoubleSpinBox()
        self.fill_alpha_spin_box = QtGui.QDoubleSpinBox()
        
        try:
            from matplotlib.backends.qt4_editor.formlayout import ColorButton
            self.color_button = ColorButton()
            self.color_button.colorChanged.connect(lambda x:
                self.callback(self.text.set_color(self.color_button.color)))
        except:
            pass
        
        self.bold_check = QtGui.QPushButton('B')
        self.italics_check = QtGui.QPushButton('I')
        self.underline_check = QtGui.QPushButton('U')
        self.underline_check.setVisible(False)  # not yet implemented
        
        font = QtGui.QFont()
        font.setWeight(600)
        self.bold_check.setFont(font)
        self.bold_check.setCheckable(True)
        self.bold_check.setMinimumWidth(25)
        self.bold_check.setSizePolicy(QtGui.QSizePolicy.Minimum, 
                                      QtGui.QSizePolicy.Preferred)
        
        font = QtGui.QFont()
        font.setItalic(True)
        self.italics_check.setFont(font)
        self.italics_check.setCheckable(True)
        self.italics_check.setMinimumWidth(25)
        self.italics_check.setSizePolicy(QtGui.QSizePolicy.Minimum, 
                                         QtGui.QSizePolicy.Preferred)
        
        
        font = QtGui.QFont()
        font.setUnderline(True)
        self.underline_check.setFont(font)
        self.underline_check.setCheckable(True)
        self.underline_check.setMinimumWidth(25)
        self.underline_check.setSizePolicy(QtGui.QSizePolicy.Minimum, 
                                           QtGui.QSizePolicy.Preferred)
        
        self.alpha_spin_box.setMinimum(0.)
        self.alpha_spin_box.setMaximum(1.)
        self.alpha_spin_box.setSingleStep(0.1)
        
        self.fill_alpha_spin_box.setMinimum(0.)
        self.fill_alpha_spin_box.setMaximum(1.)
        self.fill_alpha_spin_box.setSingleStep(0.1)
        
        self.size_spin_box.setMinimum(1)
        self.size_spin_box.setMaximum(200)
        self.size_spin_box.setSingleStep(1)

        self._populate_fonts()
        self._populate_colors()
        
        spacer = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, 
                                   QtGui.QSizePolicy.Minimum)
        layout.addWidget(self.font_label)
        font_layout = QtGui.QHBoxLayout()
        font_layout.addWidget(self.font_combo)
        font_layout.addWidget(self.bold_check)
        font_layout.addWidget(self.italics_check)
        font_layout.addWidget(self.underline_check)
        font_layout.addItem(spacer)
        layout.addLayout(font_layout)
        
        layout.addWidget(self.size_label)
        layout.addWidget(self.size_spin_box)
        
        layout.addWidget(self.color_label)
        color_layout = QtGui.QHBoxLayout()
        color_layout.addWidget(self.color_combo)
        if hasattr(self, 'color_button'):
            color_layout.addWidget(self.color_button)
        layout.addLayout(color_layout)
        
        layout.addWidget(self.alpha_label)
        layout.addWidget(self.alpha_spin_box)
        
        #layout.addWidget(self.fill_alpha_label)
        #layout.addWidget(self.fill_alpha_spin_box)
        
        layout.addWidget(self.text_label)
        layout.addWidget(self.text_edit)    
        
        #self.addLayout(layout)
        
        self.text = text
        
        try:
            import matplotlib as mpl
        
            self.size_spin_box.setValue(text.get_size() or 12)
            self.text_edit.setText(text.get_text() if text.get_text() != '____' else '')
            self.font_combo.setCurrentIndex(self.families.index(text.get_family()[0]))
            self.font_combo.update()
            color = text.get_color()
            try:
                self.font_combo.setCurrentIndex(self.colors[color])
            except KeyError:
                from matplotlib.colors import ColorConverter, rgb2hex, cnames
                code = rgb2hex(ColorConverter.colors[color])
                
                for name in cnames:
                    if cnames[name] == code:
                        color = name
                
                try:        
                    self.font_combo.setCurrentIndex(self.colors[color])
                except KeyError:
                    self.font_combo.setCurrentIndex(self.colors['black'])
            finally:
                pass
            
            try:
                self.bold_check.setChecked((text.get_weight() >= 600))
            except:
                pass
            
            try: 
                self.italics_check.setChecked(text.get_style() == 'italic')
            except:
                pass
            
        except ImportWarning:
            pass
        
        self.text_edit.textChanged.connect(lambda x: self.callback(self._set_text(x)))
        self.color_combo.currentIndexChanged.connect(lambda x: 
            self.callback(self.text.set_color(str(self.color_combo.itemText(x)))))
        self.font_combo.currentIndexChanged.connect(lambda x: 
            self.callback(self.text.set_family(str(self.font_combo.itemText(x)))))
        self.size_spin_box.valueChanged.connect(lambda x: 
                                        self.callback(self.text.set_size(x)))
        self.alpha_spin_box.valueChanged.connect(lambda x:
                                        self.callback(self.text.set_alpha(x)))
        
        self.bold_check.toggled.connect(lambda x:
                self.callback(self.text.set_weight('bold' if x else 'normal')))
        self.italics_check.toggled.connect(lambda x:
                self.callback(self.text.set_style('italic' if x else 'normal')))
        self.underline_check.toggled.connect(lambda x:
                self.callback(self.text.set_text('\\underline{%s}'
                                                 % self.text.get_text() if x 
                                                 else self.text.get_text())))
Esempio n. 47
0
def plot_heat_tree(tree_file,
                   biodb="chlamydia_04_16",
                   exclude_outgroup=False,
                   bw_scale=True):
    from chlamdb.biosqldb import manipulate_biosqldb
    import matplotlib.cm as cm
    from matplotlib.colors import rgb2hex
    import matplotlib as mpl

    server, db = manipulate_biosqldb.load_db(biodb)

    sql_biodatabase_id = 'select biodatabase_id from biodatabase where name="%s"' % biodb
    db_id = server.adaptor.execute_and_fetchall(sql_biodatabase_id, )[0][0]
    if type(tree_file) == str:
        t1 = Tree(tree_file)
        try:
            R = t1.get_midpoint_outgroup()
            #print 'root', R
            # and set it as tree outgroup
            t1.set_outgroup(R)
        except:
            pass
    elif isinstance(tree_file, Tree):
        t1 = tree_file
    else:
        IOError('Unkown tree format')
    tss = TreeStyle()
    tss.draw_guiding_lines = True
    tss.guiding_lines_color = "gray"
    tss.show_leaf_name = False

    #print "tree", t1

    sql1 = 'select taxon_id, description from bioentry where biodatabase_id=%s and description not like "%%%%plasmid%%%%"' % db_id
    sql2 = 'select t2.taxon_id, t1.GC from genomes_info_%s as t1 inner join bioentry as t2 ' \
           ' on t1.accession=t2.accession where t2.biodatabase_id=%s and t1.description not like "%%%%plasmid%%%%";' % (biodb, db_id)
    sql3 = 'select t2.taxon_id, t1.genome_size from genomes_info_%s as t1 ' \
           ' inner join bioentry as t2 on t1.accession=t2.accession ' \
           ' where t2.biodatabase_id=%s and t1.description not like "%%%%plasmid%%%%";' % (biodb, db_id)
    sql4 = 'select t2.taxon_id,percent_non_coding from genomes_info_%s as t1 ' \
           ' inner join bioentry as t2 on t1.accession=t2.accession ' \
           ' where t2.biodatabase_id=%s and t1.description not like "%%%%plasmid%%%%";' % (biodb, db_id)

    sql_checkm_completeness = 'select taxon_id, completeness from custom_tables.checkm_%s;' % biodb
    sql_checkm_contamination = 'select taxon_id,contamination from custom_tables.checkm_%s;' % biodb

    try:
        taxon_id2completeness = manipulate_biosqldb.to_dict(
            server.adaptor.execute_and_fetchall(sql_checkm_completeness))
        taxon_id2contamination = manipulate_biosqldb.to_dict(
            server.adaptor.execute_and_fetchall(sql_checkm_contamination))
    except:
        taxon_id2completeness = False
    #taxon2description = manipulate_biosqldb.to_dict(server.adaptor.execute_and_fetchall(sql1,))

    taxon2description = manipulate_biosqldb.taxon_id2genome_description(
        server, biodb, filter_names=True)

    taxon2gc = manipulate_biosqldb.to_dict(
        server.adaptor.execute_and_fetchall(sql2, ))
    taxon2genome_size = manipulate_biosqldb.to_dict(
        server.adaptor.execute_and_fetchall(sql3, ))
    taxon2coding_density = manipulate_biosqldb.to_dict(
        server.adaptor.execute_and_fetchall(sql4, ))

    my_taxons = [lf.name for lf in t1.iter_leaves()]

    # Calculate the midpoint node

    if exclude_outgroup:
        excluded = str(list(t1.iter_leaves())[0].name)
        my_taxons.pop(my_taxons.index(excluded))

    genome_sizes = [float(taxon2genome_size[i]) for i in my_taxons]
    gc_list = [float(taxon2gc[i]) for i in my_taxons]
    fraction_list = [float(taxon2coding_density[i]) for i in my_taxons]

    value = 1

    max_genome_size = max(genome_sizes)  #3424182#
    max_gc = max(gc_list)  #48.23

    cmap = cm.YlGnBu  #YlOrRd#OrRd

    norm = mpl.colors.Normalize(vmin=min(genome_sizes) - 100000,
                                vmax=max(genome_sizes))
    m1 = cm.ScalarMappable(norm=norm, cmap=cmap)
    norm = mpl.colors.Normalize(vmin=min(gc_list), vmax=max(gc_list))
    m2 = cm.ScalarMappable(norm=norm, cmap=cmap)
    norm = mpl.colors.Normalize(vmin=min(fraction_list),
                                vmax=max(fraction_list))
    m3 = cm.ScalarMappable(norm=norm, cmap=cmap)

    for i, lf in enumerate(t1.iter_leaves()):
        #if taxon2description[lf.name] == 'Pirellula staleyi DSM 6068':
        #    lf.name = 'Pirellula staleyi DSM 6068'
        #    continue
        if i == 0:
            n = TextFace('Size (Mbp)')
            n.rotation = -25
            n.margin_top = 1
            n.margin_right = 1
            n.margin_left = 20
            n.margin_bottom = 1
            n.inner_background.color = "white"
            n.opacity = 1.
            #lf.add_face(n, 3, position="aligned")
            tss.aligned_header.add_face(n, 3)
            n = TextFace('GC (%)')
            n.rotation = -25
            n.margin_top = 1
            n.margin_right = 1
            n.margin_left = 20
            n.margin_bottom = 1
            n.inner_background.color = "white"
            n.opacity = 1.
            #lf.add_face(n, 5, position="aligned")
            tss.aligned_header.add_face(n, 5)
            n = TextFace('')
            #lf.add_face(n, 2, position="aligned")
            tss.aligned_header.add_face(n, 2)
            #lf.add_face(n, 4, position="aligned")
            tss.aligned_header.add_face(n, 4)
            n = TextFace('Non coding (%)')
            n.margin_top = 1
            n.margin_right = 1
            n.margin_left = 20
            n.margin_bottom = 1
            n.inner_background.color = "white"
            n.opacity = 1.
            n.rotation = -25
            #lf.add_face(n, 7, position="aligned")
            tss.aligned_header.add_face(n, 7)
            n = TextFace('')
            #lf.add_face(n, 6, position="aligned")
            tss.aligned_header.add_face(n, 6)

            if taxon_id2completeness:
                n = TextFace('Completeness (%)')
                n.margin_top = 1
                n.margin_right = 1
                n.margin_left = 20
                n.margin_bottom = 1
                n.inner_background.color = "white"
                n.opacity = 1.
                n.rotation = -25
                #lf.add_face(n, 7, position="aligned")
                tss.aligned_header.add_face(n, 9)
                n = TextFace('')
                #lf.add_face(n, 6, position="aligned")
                tss.aligned_header.add_face(n, 8)

                n = TextFace('Contamination (%)')
                n.margin_top = 1
                n.margin_right = 1
                n.margin_left = 20
                n.margin_bottom = 1
                n.inner_background.color = "white"
                n.opacity = 1.
                n.rotation = -25
                #lf.add_face(n, 7, position="aligned")
                tss.aligned_header.add_face(n, 11)
                n = TextFace('')
                #lf.add_face(n, 6, position="aligned")
                tss.aligned_header.add_face(n, 10)

        value += 1

        #print '------ %s' % lf.name
        if exclude_outgroup and i == 0:
            lf.name = taxon2description[lf.name]
            #print '#######################'
            continue

        n = TextFace(
            '  %s ' %
            str(round(taxon2genome_size[lf.name] / float(1000000), 2)))
        n.margin_top = 1
        n.margin_right = 1
        n.margin_left = 0
        n.margin_bottom = 1
        n.fsize = 7
        n.inner_background.color = "white"
        n.opacity = 1.

        lf.add_face(n, 2, position="aligned")
        #if max_genome_size > 3424182:
        #    max_genome_size = 3424182
        fraction_biggest = (float(taxon2genome_size[lf.name]) /
                            max_genome_size) * 100
        fraction_rest = 100 - fraction_biggest
        if taxon2description[lf.name] == 'Rhabdochlamydia helveticae T3358':
            col = '#fc8d59'
        else:
            if not bw_scale:
                col = rgb2hex(m1.to_rgba(float(
                    taxon2genome_size[lf.name])))  # 'grey'
            else:
                col = '#fc8d59'

        b = StackedBarFace([fraction_biggest, fraction_rest],
                           width=100,
                           height=9,
                           colors=[col, 'white'])
        b.rotation = 0
        b.inner_border.color = "black"
        b.inner_border.width = 0
        b.margin_right = 15
        b.margin_left = 0
        lf.add_face(b, 3, position="aligned")

        fraction_biggest = (float(taxon2gc[lf.name]) / max_gc) * 100
        fraction_rest = 100 - fraction_biggest
        if taxon2description[lf.name] == 'Rhabdochlamydia helveticae T3358':
            col = '#91bfdb'
        else:
            if not bw_scale:
                col = rgb2hex(m2.to_rgba(float(taxon2gc[lf.name])))
            else:
                col = '#91bfdb'
        b = StackedBarFace([fraction_biggest, fraction_rest],
                           width=100,
                           height=9,
                           colors=[col, 'white'])
        b.rotation = 0
        b.inner_border.color = "black"
        b.inner_border.width = 0
        b.margin_left = 0
        b.margin_right = 15

        lf.add_face(b, 5, position="aligned")
        n = TextFace('  %s ' % str(round(float(taxon2gc[lf.name]), 2)))
        n.margin_top = 1
        n.margin_right = 0
        n.margin_left = 0
        n.margin_bottom = 1
        n.fsize = 7
        n.inner_background.color = "white"
        n.opacity = 1.
        lf.add_face(n, 4, position="aligned")

        if taxon2description[lf.name] == 'Rhabdochlamydia helveticae T3358':
            col = '#99d594'
        else:
            if not bw_scale:
                col = rgb2hex(m3.to_rgba(float(taxon2coding_density[lf.name])))
            else:
                col = '#99d594'
        n = TextFace('  %s ' % str(float(taxon2coding_density[lf.name])))
        n.margin_top = 1
        n.margin_right = 0
        n.margin_left = 0
        n.margin_right = 0
        n.margin_bottom = 1
        n.fsize = 7
        n.inner_background.color = "white"
        n.opacity = 1.
        lf.add_face(n, 6, position="aligned")
        fraction = (float(taxon2coding_density[lf.name]) /
                    max(taxon2coding_density.values())) * 100
        fraction_rest = ((max(taxon2coding_density.values()) -
                          taxon2coding_density[lf.name]) /
                         float(max(taxon2coding_density.values()))) * 100
        #print 'fraction, rest', fraction, fraction_rest
        b = StackedBarFace(
            [fraction, fraction_rest],
            width=100,
            height=9,
            colors=[col, 'white'
                    ])  # 1-round(float(taxon2coding_density[lf.name]), 2)
        b.rotation = 0
        b.margin_right = 1
        b.inner_border.color = "black"
        b.inner_border.width = 0
        b.margin_left = 5
        lf.add_face(b, 7, position="aligned")

        if taxon_id2completeness:
            n = TextFace('  %s ' % str(float(taxon_id2completeness[lf.name])))
            n.margin_top = 1
            n.margin_right = 0
            n.margin_left = 0
            n.margin_right = 0
            n.margin_bottom = 1
            n.fsize = 7
            n.inner_background.color = "white"
            n.opacity = 1.
            lf.add_face(n, 8, position="aligned")
            fraction = float(taxon_id2completeness[lf.name])
            fraction_rest = 100 - fraction
            #print 'fraction, rest', fraction, fraction_rest
            b = StackedBarFace(
                [fraction, fraction_rest],
                width=100,
                height=9,
                colors=["#d7191c", 'white'
                        ])  # 1-round(float(taxon2coding_density[lf.name]), 2)
            b.rotation = 0
            b.margin_right = 1
            b.inner_border.color = "black"
            b.inner_border.width = 0
            b.margin_left = 5
            lf.add_face(b, 9, position="aligned")

            n = TextFace('  %s ' % str(float(taxon_id2contamination[lf.name])))
            n.margin_top = 1
            n.margin_right = 0
            n.margin_left = 0
            n.margin_right = 0
            n.margin_bottom = 1
            n.fsize = 7
            n.inner_background.color = "white"
            n.opacity = 1.
            lf.add_face(n, 10, position="aligned")
            fraction = float(taxon_id2contamination[lf.name])
            fraction_rest = 100 - fraction
            #print 'fraction, rest', fraction, fraction_rest
            b = StackedBarFace(
                [fraction, fraction_rest],
                width=100,
                height=9,
                colors=["black", 'white'
                        ])  # 1-round(float(taxon2coding_density[lf.name]), 2)
            b.rotation = 0
            b.margin_right = 1
            b.inner_border.color = "black"
            b.inner_border.width = 0
            b.margin_left = 5
            lf.add_face(b, 11, position="aligned")

            #lf.name = taxon2description[lf.name]
        n = TextFace(taxon2description[lf.name],
                     fgcolor="black",
                     fsize=9,
                     fstyle='italic')
        n.margin_right = 30
        lf.add_face(n, 0)

    for n in t1.traverse():
        nstyle = NodeStyle()
        if n.support < 1:
            nstyle["fgcolor"] = "black"
            nstyle["size"] = 6
            n.set_style(nstyle)
        else:
            nstyle["fgcolor"] = "red"
            nstyle["size"] = 0
            n.set_style(nstyle)

    return t1, tss
Esempio n. 48
0
    def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None):
        writer = self.writer

        color = rgb2hex(gc.get_rgb())
        style = {}
        if color != '#000000':
            style['fill'] = color
        if gc.get_alpha() != 1.0:
            style['opacity'] = short_float_fmt(gc.get_alpha())

        if not ismath:
            font = self._get_font(prop)
            font.set_text(s, 0.0, flags=LOAD_NO_HINTING)

            fontsize = prop.get_size_in_points()

            fontfamily = font.family_name
            fontstyle = prop.get_style()

            attrib = {}
            # Must add "px" to workaround a Firefox bug
            style['font-size'] = short_float_fmt(fontsize) + 'px'
            style['font-family'] = six.text_type(fontfamily)
            style['font-style'] = prop.get_style().lower()
            style['font-weight'] = six.text_type(prop.get_weight()).lower()
            attrib['style'] = generate_css(style)

            if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"):
                # If text anchoring can be supported, get the original
                # coordinates and add alignment information.

                # Get anchor coordinates.
                transform = mtext.get_transform()
                ax, ay = transform.transform_point(mtext.get_position())
                ay = self.height - ay

                # Don't do vertical anchor alignment. Most applications do not
                # support 'alignment-baseline' yet. Apply the vertical layout
                # to the anchor point manually for now.
                angle_rad = np.deg2rad(angle)
                dir_vert = np.array([np.sin(angle_rad), np.cos(angle_rad)])
                v_offset = np.dot(dir_vert, [(x - ax), (y - ay)])
                ax = ax + v_offset * dir_vert[0]
                ay = ay + v_offset * dir_vert[1]

                ha_mpl_to_svg = {'left': 'start', 'right': 'end',
                                 'center': 'middle'}
                style['text-anchor'] = ha_mpl_to_svg[mtext.get_ha()]

                attrib['x'] = short_float_fmt(ax)
                attrib['y'] = short_float_fmt(ay)
                attrib['style'] = generate_css(style)
                attrib['transform'] = "rotate(%s, %s, %s)" % (
                    short_float_fmt(-angle),
                    short_float_fmt(ax),
                    short_float_fmt(ay))
                writer.element('text', s, attrib=attrib)
            else:
                attrib['transform'] = generate_transform([
                    ('translate', (x, y)),
                    ('rotate', (-angle,))])

                writer.element('text', s, attrib=attrib)

            if rcParams['svg.fonttype'] == 'svgfont':
                fontset = self._fonts.setdefault(font.fname, set())
                for c in s:
                    fontset.add(ord(c))
        else:
            writer.comment(s)

            width, height, descent, svg_elements, used_characters = \
                   self.mathtext_parser.parse(s, 72, prop)
            svg_glyphs = svg_elements.svg_glyphs
            svg_rects = svg_elements.svg_rects

            attrib = {}
            attrib['style'] = generate_css(style)
            attrib['transform'] = generate_transform([
                ('translate', (x, y)),
                ('rotate', (-angle,))])

            # Apply attributes to 'g', not 'text', because we likely
            # have some rectangles as well with the same style and
            # transformation
            writer.start('g', attrib=attrib)

            writer.start('text')

            # Sort the characters by font, and output one tspan for
            # each
            spans = OrderedDict()
            for font, fontsize, thetext, new_x, new_y, metrics in svg_glyphs:
                style = generate_css({
                    'font-size': short_float_fmt(fontsize) + 'px',
                    'font-family': font.family_name,
                    'font-style': font.style_name.lower(),
                    'font-weight': font.style_name.lower()})
                if thetext == 32:
                    thetext = 0xa0 # non-breaking space
                spans.setdefault(style, []).append((new_x, -new_y, thetext))

            if rcParams['svg.fonttype'] == 'svgfont':
                for font, fontsize, thetext, new_x, new_y, metrics in svg_glyphs:
                    fontset = self._fonts.setdefault(font.fname, set())
                    fontset.add(thetext)

            for style, chars in six.iteritems(spans):
                chars.sort()

                same_y = True
                if len(chars) > 1:
                    last_y = chars[0][1]
                    for i in xrange(1, len(chars)):
                        if chars[i][1] != last_y:
                            same_y = False
                            break
                if same_y:
                    ys = six.text_type(chars[0][1])
                else:
                    ys = ' '.join(six.text_type(c[1]) for c in chars)

                attrib = {
                    'style': style,
                    'x': ' '.join(short_float_fmt(c[0]) for c in chars),
                    'y': ys
                    }

                writer.element(
                    'tspan',
                    ''.join(unichr(c[2]) for c in chars),
                    attrib=attrib)

            writer.end('text')

            if len(svg_rects):
                for x, y, width, height in svg_rects:
                    writer.element(
                        'rect',
                        x=short_float_fmt(x),
                        y=short_float_fmt(-y + height),
                        width=short_float_fmt(width),
                        height=short_float_fmt(height)
                        )

            writer.end('g')
Esempio n. 49
0
from matplotlib import colors
import argparse

import sys
from numpy import genfromtxt, linspace
from scipy.interpolate import Akima1DInterpolator
import os
import six

xmin = 20000

colors_ = list(six.iteritems(colors.cnames))

# Add the single letter colors.
for name, rgb in six.iteritems(colors.ColorConverter.colors):
    hex_ = colors.rgb2hex(rgb)
    colors_.append((name, hex_))

# Transform to hex color values.
hex_ = [color[1] for color in colors_]
# shuffle(hex_)
hex_ = hex_[2:-1:2]


def plot(column, metric, smoothing, work_dir):

    pretty_colors = ['#FC474C', '#8DE047', '#FFDD50', '#53A3D7']
    hex_ = pretty_colors

    max_x = 0
    max_y = 0
Esempio n. 50
0
    def draw_gouraud_triangle(self, gc, points, colors, trans):
        # This uses a method described here:
        #
        #   http://www.svgopen.org/2005/papers/Converting3DFaceToSVG/index.html
        #
        # that uses three overlapping linear gradients to simulate a
        # Gouraud triangle.  Each gradient goes from fully opaque in
        # one corner to fully transparent along the opposite edge.
        # The line between the stop points is perpendicular to the
        # opposite edge.  Underlying these three gradients is a solid
        # triangle whose color is the average of all three points.

        writer = self.writer
        if not self._has_gouraud:
            self._has_gouraud = True
            writer.start(
                'filter',
                id='colorAdd')
            writer.element(
                'feComposite',
                attrib={'in': 'SourceGraphic'},
                in2='BackgroundImage',
                operator='arithmetic',
                k2="1", k3="1")
            writer.end('filter')

        avg_color = np.sum(colors[:, :], axis=0) / 3.0
        # Just skip fully-transparent triangles
        if avg_color[-1] == 0.0:
            return

        trans_and_flip = self._make_flip_transform(trans)
        tpoints = trans_and_flip.transform(points)

        writer.start('defs')
        for i in range(3):
            x1, y1 = tpoints[i]
            x2, y2 = tpoints[(i + 1) % 3]
            x3, y3 = tpoints[(i + 2) % 3]
            c = colors[i][:]

            if x2 == x3:
                xb = x2
                yb = y1
            elif y2 == y3:
                xb = x1
                yb = y2
            else:
                m1 = (y2 - y3) / (x2 - x3)
                b1 = y2 - (m1 * x2)
                m2 = -(1.0 / m1)
                b2 = y1 - (m2 * x1)
                xb = (-b1 + b2) / (m1 - m2)
                yb = m2 * xb + b2

            writer.start(
                'linearGradient',
                id="GR%x_%d" % (self._n_gradients, i),
                x1=short_float_fmt(x1), y1=short_float_fmt(y1),
                x2=short_float_fmt(xb), y2=short_float_fmt(yb))
            writer.element(
                'stop',
                offset='0',
                style=generate_css({'stop-color': rgb2hex(c),
                                    'stop-opacity': short_float_fmt(c[-1])}))
            writer.element(
                'stop',
                offset='1',
                style=generate_css({'stop-color': rgb2hex(c),
                                    'stop-opacity': "0"}))
            writer.end('linearGradient')

        writer.element(
            'polygon',
            id='GT%x' % self._n_gradients,
            points=" ".join([short_float_fmt(x)
                             for x in (x1, y1, x2, y2, x3, y3)]))
        writer.end('defs')

        avg_color = np.sum(colors[:, :], axis=0) / 3.0
        href = '#GT%x' % self._n_gradients
        writer.element(
            'use',
            attrib={'xlink:href': href,
                    'fill': rgb2hex(avg_color),
                    'fill-opacity': short_float_fmt(avg_color[-1])})
        for i in range(3):
            writer.element(
                'use',
                attrib={'xlink:href': href,
                        'fill': 'url(#GR%x_%d)' % (self._n_gradients, i),
                        'fill-opacity': '1',
                        'filter': 'url(#colorAdd)'})

        self._n_gradients += 1
Esempio n. 51
0
def _paga_graph(
    adata,
    ax,
    solid_edges=None,
    dashed_edges=None,
    adjacency_solid=None,
    adjacency_dashed=None,
    transitions=None,
    threshold=None,
    root=0,
    colors=None,
    labels=None,
    fontsize=None,
    fontweight=None,
    fontoutline=None,
    text_kwds: Mapping[str, Any] = MappingProxyType({}),
    node_size_scale=1.0,
    node_size_power=0.5,
    edge_width_scale=1.0,
    normalize_to_color='reference',
    title=None,
    pos=None,
    cmap=None,
    frameon=True,
    min_edge_width=None,
    max_edge_width=None,
    export_to_gexf=False,
    colorbar=None,
    use_raw=True,
    cb_kwds: Mapping[str, Any] = MappingProxyType({}),
    single_component=False,
    arrowsize=30,
):
    import networkx as nx

    node_labels = labels  # rename for clarity
    if (node_labels is not None and isinstance(node_labels, str)
            and node_labels != adata.uns['paga']['groups']):
        raise ValueError(
            'Provide a list of group labels for the PAGA groups {}, not {}.'.
            format(adata.uns['paga']['groups'], node_labels))
    groups_key = adata.uns['paga']['groups']
    if node_labels is None:
        node_labels = adata.obs[groups_key].cat.categories

    if (colors is None or colors == groups_key) and groups_key is not None:
        if groups_key + '_colors' not in adata.uns or len(
                adata.obs[groups_key].cat.categories) != len(
                    adata.uns[groups_key + '_colors']):
            _utils.add_colors_for_categorical_sample_annotation(
                adata, groups_key)
        colors = adata.uns[groups_key + '_colors']
        for iname, name in enumerate(adata.obs[groups_key].cat.categories):
            if name in settings.categories_to_ignore:
                colors[iname] = 'grey'

    nx_g_solid = nx.Graph(adjacency_solid)
    if dashed_edges is not None:
        nx_g_dashed = nx.Graph(adjacency_dashed)

    # convert pos to array and dict
    if not isinstance(pos, (Path, str)):
        pos_array = pos
    else:
        pos = Path(pos)
        if pos.suffix != '.gdf':
            raise ValueError(
                'Currently only supporting reading positions from .gdf files. '
                'Consider generating them using, for instance, Gephi.')
        s = ''  # read the node definition from the file
        with pos.open() as f:
            f.readline()
            for line in f:
                if line.startswith('edgedef>'):
                    break
                s += line
        from io import StringIO

        df = pd.read_csv(StringIO(s), header=-1)
        pos_array = df[[4, 5]].values

    # convert to dictionary
    pos = {n: [p[0], p[1]] for n, p in enumerate(pos_array)}

    # uniform color
    if isinstance(colors, str) and is_color_like(colors):
        colors = [colors for c in range(len(node_labels))]

    # color degree of the graph
    if isinstance(colors, str) and colors.startswith('degree'):
        # see also tools.paga.paga_degrees
        if colors == 'degree_dashed':
            colors = [d for _, d in nx_g_dashed.degree(weight='weight')]
        elif colors == 'degree_solid':
            colors = [d for _, d in nx_g_solid.degree(weight='weight')]
        else:
            raise ValueError(
                '`degree` either "degree_dashed" or "degree_solid".')
        colors = (np.array(colors) - np.min(colors)) / (np.max(colors) -
                                                        np.min(colors))

    # plot gene expression
    var_names = adata.var_names if adata.raw is None else adata.raw.var_names
    if isinstance(colors, str) and colors in var_names:
        x_color = []
        cats = adata.obs[groups_key].cat.categories
        for icat, cat in enumerate(cats):
            subset = (cat == adata.obs[groups_key]).values
            if adata.raw is not None and use_raw:
                adata_gene = adata.raw[:, colors]
            else:
                adata_gene = adata[:, colors]
            x_color.append(np.mean(adata_gene.X[subset]))
        colors = x_color

    # plot continuous annotation
    if (isinstance(colors, str) and colors in adata.obs
            and not is_categorical_dtype(adata.obs[colors])):
        x_color = []
        cats = adata.obs[groups_key].cat.categories
        for icat, cat in enumerate(cats):
            subset = (cat == adata.obs[groups_key]).values
            x_color.append(adata.obs.loc[subset, colors].mean())
        colors = x_color

    # plot categorical annotation
    if (isinstance(colors, str) and colors in adata.obs
            and is_categorical_dtype(adata.obs[colors])):
        asso_names, asso_matrix = _sc_utils.compute_association_matrix_of_groups(
            adata,
            prediction=groups_key,
            reference=colors,
            normalization='reference' if normalize_to_color else 'prediction',
        )
        _utils.add_colors_for_categorical_sample_annotation(adata, colors)
        asso_colors = _sc_utils.get_associated_colors_of_groups(
            adata.uns[colors + '_colors'], asso_matrix)
        colors = asso_colors

    if len(colors) != len(node_labels):
        raise ValueError(
            f'Expected `colors` to be of length `{len(node_labels)}`, '
            f'found `{len(colors)}`.')

    # count number of connected components
    n_components, labels = scipy.sparse.csgraph.connected_components(
        adjacency_solid)
    if n_components > 1 and not single_component:
        logg.debug(
            'Graph has more than a single connected component. '
            'To restrict to this component, pass `single_component=True`.')
    if n_components > 1 and single_component:
        component_sizes = np.bincount(labels)
        largest_component = np.where(
            component_sizes == component_sizes.max())[0][0]
        adjacency_solid = adjacency_solid.tocsr()[labels ==
                                                  largest_component, :]
        adjacency_solid = adjacency_solid.tocsc()[:,
                                                  labels == largest_component]
        colors = np.array(colors)[labels == largest_component]
        node_labels = np.array(node_labels)[labels == largest_component]
        cats_dropped = (adata.obs[groups_key].cat.categories[
            labels != largest_component].tolist())
        logg.info(
            'Restricting graph to largest connected component by dropping categories\n'
            f'{cats_dropped}')
        nx_g_solid = nx.Graph(adjacency_solid)
        if dashed_edges is not None:
            raise ValueError(
                '`single_component` only if `dashed_edges` is `None`.')

    # edge widths
    base_edge_width = edge_width_scale * 5 * rcParams['lines.linewidth']

    # draw dashed edges
    if dashed_edges is not None:
        widths = [x[-1]['weight'] for x in nx_g_dashed.edges(data=True)]
        widths = base_edge_width * np.array(widths)
        if max_edge_width is not None:
            widths = np.clip(widths, None, max_edge_width)
        nx.draw_networkx_edges(
            nx_g_dashed,
            pos,
            ax=ax,
            width=widths,
            edge_color='grey',
            style='dashed',
            alpha=0.5,
        )

    # draw solid edges
    if transitions is None:
        widths = [x[-1]['weight'] for x in nx_g_solid.edges(data=True)]
        widths = base_edge_width * np.array(widths)
        if min_edge_width is not None or max_edge_width is not None:
            widths = np.clip(widths, min_edge_width, max_edge_width)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            nx.draw_networkx_edges(nx_g_solid,
                                   pos,
                                   ax=ax,
                                   width=widths,
                                   edge_color='black')
    # draw directed edges
    else:
        adjacency_transitions = adata.uns['paga'][transitions].copy()
        if threshold is None:
            threshold = 0.01
        adjacency_transitions.data[adjacency_transitions.data < threshold] = 0
        adjacency_transitions.eliminate_zeros()
        g_dir = nx.DiGraph(adjacency_transitions.T)
        widths = [x[-1]['weight'] for x in g_dir.edges(data=True)]
        widths = base_edge_width * np.array(widths)
        if min_edge_width is not None or max_edge_width is not None:
            widths = np.clip(widths, min_edge_width, max_edge_width)
        nx.draw_networkx_edges(g_dir,
                               pos,
                               ax=ax,
                               width=widths,
                               edge_color='black',
                               arrowsize=arrowsize)

    if export_to_gexf:
        if isinstance(colors[0], tuple):
            from matplotlib.colors import rgb2hex

            colors = [rgb2hex(c) for c in colors]
        for count, n in enumerate(nx_g_solid.nodes()):
            nx_g_solid.node[count]['label'] = str(node_labels[count])
            nx_g_solid.node[count]['color'] = str(colors[count])
            nx_g_solid.node[count]['viz'] = dict(position=dict(
                x=1000 * pos[count][0],
                y=1000 * pos[count][1],
                z=0,
            ))
        filename = settings.writedir / 'paga_graph.gexf'
        logg.warning(f'exporting to {filename}')
        settings.writedir.mkdir(parents=True, exist_ok=True)
        nx.write_gexf(nx_g_solid, settings.writedir / 'paga_graph.gexf')

    ax.set_frame_on(frameon)
    ax.set_xticks([])
    ax.set_yticks([])

    # groups sizes
    if groups_key is not None and groups_key + '_sizes' in adata.uns:
        groups_sizes = adata.uns[groups_key + '_sizes']
    else:
        groups_sizes = np.ones(len(node_labels))
    base_scale_scatter = 2000
    base_pie_size = (base_scale_scatter /
                     (np.sqrt(adjacency_solid.shape[0]) + 10) *
                     node_size_scale)
    median_group_size = np.median(groups_sizes)
    groups_sizes = base_pie_size * np.power(groups_sizes / median_group_size,
                                            node_size_power)

    if fontsize is None:
        fontsize = rcParams['legend.fontsize']
    if fontoutline is not None:
        text_kwds = dict(text_kwds)
        text_kwds['path_effects'] = [
            patheffects.withStroke(linewidth=fontoutline, foreground='w')
        ]
    # usual scatter plot
    if not isinstance(colors[0], cabc.Mapping):
        n_groups = len(pos_array)
        sct = ax.scatter(
            pos_array[:, 0],
            pos_array[:, 1],
            c=colors[:n_groups],
            edgecolors='face',
            s=groups_sizes,
            cmap=cmap,
        )
        for count, group in enumerate(node_labels):
            ax.text(
                pos_array[count, 0],
                pos_array[count, 1],
                group,
                verticalalignment='center',
                horizontalalignment='center',
                size=fontsize,
                fontweight=fontweight,
                **text_kwds,
            )
    # else pie chart plot
    else:
        for ix, (xx, yy) in enumerate(zip(pos_array[:, 0], pos_array[:, 1])):
            if not isinstance(colors[ix], cabc.Mapping):
                raise ValueError(
                    f'{colors[ix]} is neither a dict of valid '
                    'matplotlib colors nor a valid matplotlib color.')
            color_single = colors[ix].keys()
            fracs = [colors[ix][c] for c in color_single]
            total = sum(fracs)

            if total < 1:
                color_single = list(color_single)
                color_single.append('grey')
                fracs.append(1 - sum(fracs))
            elif not np.isclose(total, 1):
                raise ValueError(f'Expected fractions for node `{ix}` to be '
                                 f'close to 1, found `{total}`.')

            cumsum = np.cumsum(fracs)
            cumsum = cumsum / cumsum[-1]
            cumsum = [0] + cumsum.tolist()

            for r1, r2, color in zip(cumsum[:-1], cumsum[1:], color_single):
                angles = np.linspace(2 * np.pi * r1, 2 * np.pi * r2, 20)
                x = [0] + np.cos(angles).tolist()
                y = [0] + np.sin(angles).tolist()

                xy = np.column_stack([x, y])
                s = np.abs(xy).max()

                sct = ax.scatter([xx], [yy],
                                 marker=xy,
                                 s=s**2 * groups_sizes[ix],
                                 color=color)

            if node_labels is not None:
                ax.text(
                    xx,
                    yy,
                    node_labels[ix],
                    verticalalignment='center',
                    horizontalalignment='center',
                    size=fontsize,
                    fontweight=fontweight,
                    **text_kwds,
                )

    return sct
Esempio n. 52
0
#%%
df_neighborhood_score.sort_values(by='Score', ascending=False, inplace=True)
df_neighborhood_score.reset_index(drop=True, inplace=True)
df_neighborhood_score.head()

#%% [markdown]
# And with that we can finally print on the map the 5 best neighborhoods for our user

#%%
recommendation_map = folium.Map(location=[latitude, longitude], zoom_start=11)

# set color scheme for the clusters
x = 5
ys = [i + x + (i * x)**2 for i in range(5)]
colors_array = cm.rainbow(np.linspace(0, 1, len(ys)))
rainbow = [colors.rgb2hex(i) for i in colors_array]

markers_colors = []
for lat, lon, poi, score, index in zip(df_neighborhood_score['Latitude'],
                                       df_neighborhood_score['Longitude'],
                                       df_neighborhood_score['Neighborhood'],
                                       df_neighborhood_score['Score'],
                                       range(5)):
    label = folium.Popup(str(poi) + ' Score ' + str(score), parse_html=True)
    folium.CircleMarker([lat, lon],
                        radius=5,
                        popup=label,
                        color=rainbow[int(index)],
                        fill=True,
                        fill_color=rainbow[int(index)],
                        fill_opacity=0.7).add_to(recommendation_map)
Esempio n. 53
0
for shapedict in m.states_info:
    statename = shapedict['NAME']
    # skip DC and Puerto Rico.
    if statename not in ['District of Columbia', 'Puerto Rico']:
        pos = pos_data[statename]
        pos_colors[statename] = pos_cmap(1. - np.sqrt((pos - vmin) /
                                                      (vmax - vmin)))[:3]
    statenames.append(statename)
# cycle through state names, color each one.

# POSITIVE MAP
ax = plt.gca()  # get current axes instance
for nshape, seg in enumerate(m.states):
    # skip Puerto Rico and DC
    if statenames[nshape] not in ['District of Columbia', 'Puerto Rico']:
        color = rgb2hex(pos_colors[statenames[nshape]])
        poly = Polygon(seg, facecolor=color, edgecolor=color)
        ax.add_patch(poly)
plt.title('Positive Trump Sentiment Across the US')
# plt.show()
plt.savefig("2.png")

# NEGATIVE MAP
m = Basemap(llcrnrlon=-119,
            llcrnrlat=22,
            urcrnrlon=-64,
            urcrnrlat=49,
            projection='lcc',
            lat_1=33,
            lat_2=45,
            lon_0=-95)
Esempio n. 54
0
File: dense.py Progetto: mcxxmc/kviz
    def animate_regression(self,
                           X,
                           filename='activations',
                           duration=1000,
                           x_color="#3498db",
                           x_marker="o",
                           rounded=True,
                           roundedN=2):
        """
        Creates an animation of the graph activated by each data point, used for regression

        Parameters:
            X : ndarray
                input to a Keras model
            filename : str
                name of file to which visualization will be saved
            duration : int
                duration in ms between images in GIF
            x_color: str.
                the color (in hex form) of the points in the pyplot graph
            x_marker: str.
                the shape of the points in the pyplot graph
            rounded: bool.
                whether to round the values
            roundedN: int
                the number of decimal places for the rounded values; will be ignored if rounded is false

        Returns:
            None
        """
        network_images = []
        input_images = []

        color_maps = {}

        predictions = [X]
        for i in range(len(self._int_models)):
            predictions.append(self._int_models[i].predict(X))
        predictions.append(self.model.predict(X))

        for i in range(len(X)):
            for l in range(len(self.model.layers)):
                layer = self.model.layers[l]

                layerVals = predictions[l][i]
                vmax = max(layerVals)
                # multiple here to make the difference of color more obvious
                norm = Normalize(vmin=min(layerVals), vmax=vmax)

                for n in range(0, layer.input_shape[1]):
                    act = predictions[l][i][n]

                    index = unique_index(l, n)
                    the_color_map = get_or_create_colormap_with_dict(
                        self._graph.nodes[index]["color"], color_maps)

                    if rounded:
                        label = str(round(act, roundedN))
                    else:
                        label = str(act)

                    if l == 0:
                        # since this is regression, the first layer is always the input data and they do not have colors
                        set_node_attributes(
                            self._graph,
                            {
                                index: {
                                    'label': label,
                                    'fixedsize': True  # important for graphviz
                                }
                            })
                    else:
                        if act == 0:  # no color for 0
                            color = "#ffffff"
                        else:
                            # minus here, so the higher value has a darker color
                            color = str(
                                rgb2hex(the_color_map(norm(vmax - act))))

                        set_node_attributes(
                            self._graph, {
                                index: {
                                    'label': label,
                                    'style': 'filled',
                                    'color': color,
                                    'fixedsize': True
                                }
                            })

                if l == len(self.model.layers
                            ) - 1:  # need to additionally show the output
                    network_images.append(self._snap(filename))
                    self._update_input_images_for_regression(
                        input_images, [i], X, predictions[-1], x_color,
                        x_marker)

                    for h in range(0, layer.output_shape[1]):
                        act = predictions[l + 1][i][h]

                        if rounded:
                            label = str(round(act, roundedN))
                        else:
                            label = str(act)

                        index = unique_index(l + 1, h)

                        set_node_attributes(
                            self._graph,
                            {index: {
                                'label': label,
                                'fixedsize': True
                            }})

                network_images.append(self._snap(filename))
                self._update_input_images_for_regression(
                    input_images, [i], X, predictions[-1], x_color, x_marker)

            self._reset()

        if len(X[0]) in [1, 2]:
            self._stack_gifs(network_images,
                             input_images,
                             filename,
                             duration=duration)
        else:
            self._convert_gif(network_images, filename, duration)
        return
Esempio n. 55
0
def colors_at_breaks(cmap, breaks=[0, 0.25, 0.5, 0.75, 1.]):
        return [rgb2hex(cmap(bb)[:3]) for bb in breaks]
Esempio n. 56
0
 def to_hex(color):
     return rgb2hex(colorConverter.to_rgb(color))
Esempio n. 57
0
    def __init__(self, OSSA):
        """Receive a OSSA instance as input. That instance is created by running
        the OSSA_launcher."""
        LOGGER.info('OSSA: ChannelSelector GUI', decorate=True)

        # Reference OSSA instance at the root level. Now data and default values
        # set by the OSSA class will be available at self.OSSA
        self.OSSA = OSSA

        # Open window
        self.window = OSSA_window(title=self.OSSA.animal_ID)

        # Make the helper message for keyboard shortcuts
        shortcuts = """
        F1\tHelp
        %s\tReload from disk
        %s\tQuit OSSA and load next recording
        %s\tQuit OSSA and stop workflow
        
        Ctrl+A\tSelect all channels
        
        After highlighting a channel...
        Esc\tReset channel selection
        """ % (self.OSSA.keyboard_shortcuts['reload'],
               self.OSSA.keyboard_shortcuts['discard_and_close'],
               self.OSSA.keyboard_shortcuts['ChannelSelector']['quit_workflow'])
        self.helperWindow = OSSAHelpDialog(shortcuts)

        # Read waveform duration from general_configs
        spike_waveform_duration_ms = GC.spike_waveform_duration
        # Get intervals before / after peak
        self.waveform_before_peak_ms = np.abs(spike_waveform_duration_ms[0])
        self.waveform_after_peak_ms = np.abs(spike_waveform_duration_ms[1])
        self.waveform_before_peak = None
        self.waveform_after_peak = None
        self.spike_waveform_duration = None
        # Initialize fields
        self.current_session = self.OSSA.n_sessions -1
        self.current_session_date = self.OSSA.recording_dates[self.current_session]
        self.INFO = None
        self.n_channels_electrode = None
        self.n_channels_all_shanks = None
        self.channels_in_shank = None
        self.intracortical_neural_shanks = None
        self.n_shanks = 1
        self.spikes_hdf5_filename = None
        self.OSSA_results = None
        self.shanks_with_spikes = None
        self.fig = None
        self.ax = None
        self.lines = None
        self.channel_map = None
        self.colors = None
        self.buttons = None
        self.menu = None
        self.callbacks = None
        self.keyboard = None
        self.NoiseRemoval = None
        self.SpikeSorter = None
        self.shank_selection = None
        self.shank_selection_index = None
        self.shank_selection_names = None
        # Load data of last session
        self.load_data_of_current_session()
        # Get shanks suitable for spike sorting (i.e., with spikes)
        self._get_shanks_suitable_for_sorting()
        # Pre-allocate fields for graphical elements
        initialize_field(self, 'fig')
        initialize_field(self, 'ax')
        initialize_field(self, 'lines')
        initialize_field(self, 'colors')
        initialize_field(self, 'buttons')
        initialize_field(self, 'menu')
        initialize_field(self, 'callbacks')
        initialize_field(self, 'keyboard')
        # Unpack colors
        self.colors.active = colors.rgb2hex(self.OSSA.default['ChannelSelector']['color_channel_active'])
        self.colors.inactive = colors.rgb2hex(self.OSSA.default['ChannelSelector']['color_channel_inactive'])
        self.colors.highlight = colors.rgb2hex(self.OSSA.default['ChannelSelector']['color_channel_highlight'])
        self.colors.discard = colors.rgb2hex(self.OSSA.default['ChannelSelector']['color_channel_discard'])
        self.colors.keep = colors.rgb2hex(self.OSSA.default['ChannelSelector']['color_channel_keep'])
        self.colors.sorted = colors.rgb2hex(self.OSSA.default['ChannelSelector']['color_channel_sorted'])

        # Create main frame and draw channel map on it
        self._GUI_create_main_frame()
        self._draw_channel_map(initialize=True)
        # Reset the exit code and the variables that gets transferred between GUIs
        self._init_GUI_data()
        self.reset_GUI_data()
        # Destroy references to matplotlib's figures. These are now referenced
        # by the Qt event loop and need not to stay opened in matplotlib.
        [plt.close(self.fig.channels[sh][0]) for sh in range(self.n_shanks)]

        # Hide launcher GUI
        self.OSSA.launcher_GUI.hide()

        # This GUI does not show itself, but it's initialized by OSSA and then
        # made visible by other GUIs before deleting themselves.

        self.buttons.run_CCG_selected_channels.setEnabled(False)
        self.menu.session.setCurrentIndex(0)
def process_struct(filename, fig):
    print('Starting struct calculation')
    dataset = pydicom.dcmread(filename)

    k = 0
    for elem in dataset[0x3006, 0x0020]:
        print(elem[0x3006, 0x0028].value, k)
        k = k + 1

    print("Select the two surfaces to find intersection")
    while True:  # example of infinite loops using try and except to catch only numbers
        line = input("Select the first structure from the list > ")
        try:
            num1 = int(
                line.lower())  # temporarily since allows any range of numbers
            break
        except ValueError:  # pylint: disable = bare-except
            print("Please enter a valid option:")

    while True:  # example of infinite loops using try and except to catch only numbers
        line = input("Select the second structure from the list > ")
        try:
            num2 = int(line.lower())
            break
        except ValueError:  # pylint: disable = bare-except
            print("Please enter a valid option:")

    struct_intersect_list = [num1, num2]
    struct_intersect_names_list = [
        dataset[0x3006, 0x0020][num1][0x3006, 0x0028].value,
        dataset[0x3006, 0x0020][num2][0x3006, 0x0028].value
    ]

    dz = abs(
        dataset[0x3006, 0x0039][num1][0x3006, 0x0040][2][0x3006, 0x0050][2] -
        dataset[0x3006, 0x0039][num1][0x3006, 0x0040][1][0x3006, 0x0050][2])
    print('dz=', dz)

    roi_num = []
    roi_color = []

    xs_tot = []
    ys_tot = []
    zs_tot = []
    el_tot = []

    k = 0  #iterator for the number of structures
    for j in struct_intersect_list:
        xs_elem = []
        ys_elem = []
        zs_elem = []
        elem = dataset[0x3006, 0x0039][j]
        roi_color = elem[
            0x3006,
            0x002a].value  # this value is the color of the lesion/structure
        hex_color = colors.rgb2hex(np.asarray(roi_color) / 255)
        roi_num.append(elem[0x3006, 0x0084].value)
        Area = 0
        try:
            for contour in elem[
                    0x3006,
                    0x0040]:  #the area between the two surfaces must be calculated for every contour if there are two areas in each of the contours
                xs = []
                ys = []
                zs = []
                for i in range(0, contour[0x3006, 0x0050].VM, 3):
                    xs_elem.append(contour[0x3006, 0x0050][i])
                    ys_elem.append(contour[0x3006, 0x0050][i + 1])
                    zs_elem.append(contour[0x3006, 0x0050][i + 2])

                    xs_tot.append(contour[0x3006, 0x0050][i])
                    ys_tot.append(contour[0x3006, 0x0050][i + 1])
                    zs_tot.append(contour[0x3006, 0x0050][i + 2])
                    el_tot.append(k)

                # x = np.array(xs).astype(np.float) #this is the collection of points for every slice
                # y = np.array(ys).astype(np.float)
                # z = np.array(zs).astype(np.float)
                #
                #
                #
                # Area = Area + PolyArea(x, y) * dz
                # print('Slice area = ', PolyArea(x, y), Area)

                # poly = Poly3DCollection(verts, alpha=0.5)
                # poly.set_color(hex_color)
                # poly.set_edgecolor('k')
                # ax.add_collection3d(poly)

            x_elem = np.array(xs_elem).astype(
                np.float)  # this is the collection of points for every element
            y_elem = np.array(ys_elem).astype(np.float)
            z_elem = np.array(zs_elem).astype(np.float)

            # points_total = np.stack((x_elem, y_elem, z_elem), axis=1)
            if k == 0:  #if structure 0
                elem_0 = np.stack((x_elem, y_elem, z_elem), axis=1)
                hull = ss.ConvexHull(elem_0)
                print('hull0_stats(volume,area)', hull.volume, hull.area)
                sphericity_0 = (np.pi**(1 / 3) *
                                (6 * hull.volume)**(2 / 3)) / (hull.area)
                print('sphericity_0=', sphericity_0)

                points = go.Scatter3d(mode='markers',
                                      name='',
                                      x=x_elem,
                                      y=y_elem,
                                      z=z_elem,
                                      marker=dict(size=2, color='red'))

                # simplexes = go.Mesh3d(alphahull=2.0,
                #                    name='',
                #                    x=x_elem,
                #                    y=y_elem,
                #                    z=z_elem,
                #                    color='red',  # set the color of simplexes in alpha shape
                #                    opacity=0.15
                #                    )

                # fig = go.Figure(data=[points,simplexes])
                fig = go.Figure(data=[points])
                # fig.show()

            elif k == 1:  #if structure 1
                elem_1 = np.stack((x_elem, y_elem, z_elem), axis=1)
                hull = ss.ConvexHull(elem_1)
                print('hull1_stats(volume,area)', hull.volume, hull.area)
                sphericity_1 = (np.pi**(1 / 3) *
                                (6 * hull.volume)**(2 / 3)) / (hull.area)
                print('sphericity_1=', sphericity_1)

                points = go.Scatter3d(mode='markers',
                                      name='',
                                      x=x_elem,
                                      y=y_elem,
                                      z=z_elem,
                                      marker=dict(size=2, color='red'))

                # simplexes = go.Mesh3d(alphahull=2.0,
                #                    name='',
                #                    x=x_elem,
                #                    y=y_elem,
                #                    z=z_elem,
                #                    color='red',  # set the color of simplexes in alpha shape
                #                    opacity=0.15
                #                    )

                # fig = go.Figure(data=[points,simplexes])
                fig = go.Figure(data=[points])
                # fig.show()

        except:
            print('no contour data')

        k = k + 1

    #the section below is for more accurate calculations of the volume
    # exit(0)

    volume_intersection = 0
    volume_0 = 0
    volume_1 = 0

    for i in range(0, np.shape(elem_0)[0] - 1):
        if elem_0[i, 2] != elem_0[i + 1, 2]:
            elem_0_select = elem_0[elem_0[:, 2] == elem_0[i, 2]]
            poly0 = geometry.Polygon(elem_0_select[:, 0:2])
            volume_0 = volume_0 + poly0.area * dz

    #we also need to include the last layer/shape for a more accurate calculation
    elem_0_select = elem_0[elem_0[:, 2] == elem_0[np.shape(elem_0)[0] - 1, 2]]
    poly0 = geometry.Polygon(elem_0_select[:, 0:2])
    volume_0 = volume_0 + poly0.area * dz

    for i in range(0, np.shape(elem_1)[0] - 1):
        if elem_1[i, 2] != elem_1[i + 1, 2]:
            elem_1_select = elem_1[elem_1[:, 2] == elem_1[i, 2]]
            poly1 = geometry.Polygon(elem_1_select[:, 0:2])
            volume_1 = volume_1 + poly1.area * dz

    # we also need to include the last layer/shape for a more accurate calculation
    elem_1_select = elem_1[elem_1[:, 2] == elem_1[np.shape(elem_1)[0] - 1, 2]]
    poly1 = geometry.Polygon(elem_1_select[:, 0:2])
    volume_1 = volume_1 + poly1.area * dz

    for i in range(0, np.shape(elem_0)[0] - 1):
        if elem_0[i, 2] != elem_0[i + 1, 2]:
            elem_0_select = elem_0[elem_0[:, 2] == elem_0[i, 2]]
            elem_1_select = elem_1[elem_1[:, 2] == elem_0[i, 2]]
            if len(elem_1_select) == 0 or len(elem_0_select) == 0:
                continue
            else:
                poly0 = geometry.Polygon(elem_0_select[:, 0:2])
                poly1 = geometry.Polygon(elem_1_select[:, 0:2])
                if poly0.intersects(poly1) == True:
                    poly_intersect = poly0.intersection(poly1)
                    if type(poly_intersect
                            ) == geometry.multipolygon.MultiPolygon:
                        for poly in list(poly_intersect):
                            volume_intersection = volume_intersection + poly.area * dz
                    elif type(poly_intersect) == geometry.polygon.Polygon:
                        volume_intersection = volume_intersection + poly_intersect.area * dz

    print('volume_intersection=', volume_intersection, 'mm^3')
    print('volume_0', struct_intersect_names_list[0], '=', volume_0, 'mm^3')
    print('volume_1', struct_intersect_names_list[1], '=', volume_1, 'mm^3')
    print('Ratio (volume_1/volume_0) (lesion/prostate)=', volume_1 / volume_0)

    exit(0)

    x_total = np.array(xs_tot).astype(
        np.float)  # this is the total collection of points
    y_total = np.array(ys_tot).astype(np.float)
    z_total = np.array(zs_tot).astype(np.float)
    el_total = np.array(el_tot).astype(np.float)

    ax.set_xlim3d(np.min(xs_tot), np.max(xs_tot))
    ax.set_ylim3d(np.min(ys_tot), np.max(ys_tot))
    ax.set_zlim3d(np.min(zs_tot), np.max(zs_tot))
    plt.show()
Esempio n. 59
0
 def css(rgba) -> str:
     dark = relative_luminance(rgba) < text_color_threshold
     text_color = '#f1f1f1' if dark else '#000000'
     return format_cell(bg=rgb2hex(rgba), t=text_color)
def col2hex(color):
    """Convert matplotlib color to hex before passing to Qt"""
    return rgb2hex(colorConverter.to_rgb(color))