Ejemplo n.º 1
0
def mylayout(node):
    # Internal Node formatting
    nstyle = NodeStyle()
    nstyle["size"] = 0
    nstyle["vt_line_width"] = 2
    nstyle["hz_line_width"] = 2

    if node.is_leaf():
        circle_face = CircleFace(10, color_dict[node.name], style='circle')
        faces.add_face_to_node(circle_face,
                               node,
                               position="branch-right",
                               column=0)

        text_face = TextFace(meta_dict[node.name][0])
        text_face.fgcolor = color_dict[node.name]
        faces.add_face_to_node(text_face,
                               node,
                               position="branch-right",
                               column=1)

        node.set_style(nstyle)

    elif node.is_root():
        node.dist = 0
        node.set_style(nstyle)

    else:
        node.set_style(nstyle)
Ejemplo n.º 2
0
def plot_tree_barplot(tree_file,
                      taxon2value_list_barplot,
                      header_list,
                      taxon2set2value_heatmap=False,
                      header_list2=False,
                      column_scale=True,
                      general_max=False,
                      barplot2percentage=False,
                      taxon2mlst=False):
    '''

    display one or more barplot

    :param tree_file:
    :param taxon2value_list:
    :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:
    '''

    import matplotlib.cm as cm
    from matplotlib.colors import rgb2hex
    import matplotlib as mpl

    if taxon2mlst:
        mlst_list = list(set(taxon2mlst.values()))
        mlst2color = dict(zip(mlst_list, get_spaced_colors(len(mlst_list))))
        mlst2color['-'] = 'white'

    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

            if taxon2mlst:
                header_list = ['MLST'] + header_list

            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 + 1)

                n = TextFace('%s' % header)
                n.margin_top = 1
                n.margin_right = 2
                n.margin_left = 2
                n.margin_bottom = 2
                n.rotation = 270
                n.inner_background.color = "white"
                n.opacity = 1.
                n.hz_align = 2
                n.vt_align = 1
                tss.aligned_header.add_face(n, col_add)
                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)

        if taxon2mlst:

            try:
                #if lf.name in leaf2mlst or int(lf.name) in leaf2mlst:
                n = TextFace(' %s ' % taxon2mlst[int(lf.name)])
                n.inner_background.color = 'white'
                m = TextFace('  ')
                m.inner_background.color = mlst2color[taxon2mlst[int(lf.name)]]
            except:
                n = TextFace(' na ')
                n.inner_background.color = "grey"
                m = TextFace('    ')
                m.inner_background.color = "white"

            n.opacity = 1.
            n.margin_top = 2
            n.margin_right = 2
            n.margin_left = 0
            n.margin_bottom = 2

            m.margin_top = 2
            m.margin_right = 0
            m.margin_left = 2
            m.margin_bottom = 2

            lf.add_face(m, 0, position="aligned")
            lf.add_face(n, 1, position="aligned")
            col_add = 2
        else:
            col_add = 0

        try:
            val_list = taxon2value_list_barplot[lf.name]
        except:
            if not taxon2mlst:
                val_list = ['na'] * len(header_list)
            else:
                val_list = ['na'] * (len(header_list) - 1)

        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 = 5
            n.margin_left = 10
            n.margin_bottom = 1
            n.inner_background.color = "white"
            n.opacity = 1.

            lf.add_face(n, col_add, position="aligned")
            # show bar
            try:
                color = rgb2hex(scale_list[col].to_rgba(float(value)))
            except:
                color = 'white'
            try:
                percentage = (value / max_value_list[col]) * 100
                #percentage = value
            except:
                percentage = 0
            try:
                maximum_bar = (
                    (max_value_list[col] - value) / max_value_list[col]) * 100
            except:
                maximum_bar = 0
            #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")

        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)

    return t1, tss
Ejemplo n.º 3
0
    time_begin = trackResult[r, 1]
    time_end = trackResult[r, 2]
    parent_id = trackResult[r, 3]
    time_duration = np.abs(time_begin-time_end)
    # for root
    if parent_id == 0:
        # Add name to root for the first iteration
        root.add_feature("name", str(cell_id))
        # change the branch length
        root.add_feature("dist", time_duration)
        #change node style
        root.set_style(ns_root)
        
        # set node name to face
        nameFace = TextFace(root.name)
        nameFace.fgcolor = "white"
        nameFace.fsize = 15
#        nameFace.border.width = 1
        nameFace.background.color = "green"
        node_cur.add_face(nameFace, column=1, position="branch-bottom")
    
    else:  # for child
        #### search the parent node by parent_id
        node_cur = root.search_nodes(name=str(parent_id))
        # there should be only one parent node
        if len(node_cur) == 1:
            #### set child with its id
            node_cur = node_cur[0].add_child(name=str(cell_id))  
            #### set duration
            node_cur.add_feature("dist", time_duration)
            
Ejemplo n.º 4
0
def plot_ete_tree(tree_file,
                  ordered_queries,
                  leaf_id2protein_id2identity,
                  leaf_id2mlst,
                  leaf_id2spa,
                  leaf_id2meca,
                  show_identity_values=True,
                  leaf_id2description=False):
    mlst_list = list(set(leaf_id2mlst.values()))
    mlst2color = dict(zip(mlst_list, get_spaced_colors(len(mlst_list))))
    mlst2color['-'] = 'white'

    t1 = Tree(tree_file)
    tss = TreeStyle()
    R = t1.get_midpoint_outgroup()
    t1.set_outgroup(R)
    t1.ladderize()

    head = True
    column_add = 4
    for lf in t1.iter_leaves():
        lf.branch_vertical_margin = 0
        # add MLST
        if head:
            n = TextFace(' MLST ')
            n.margin_top = 2
            n.margin_right = 2
            n.margin_left = 2
            n.margin_bottom = 2
            n.rotation = 270
            n.vt_align = 2
            n.hz_align = 2
            n.inner_background.color = "white"
            n.opacity = 1.
            tss.aligned_header.add_face(n, 1)

        if lf.name in leaf2mlst:
            n = TextFace(' %s ' % leaf_id2mlst[lf.name])
            n.inner_background.color = 'white'
            m = TextFace('  ')
            m.inner_background.color = mlst2color[leaf_id2mlst[lf.name]]
        else:
            n = TextFace(' na ')
            n.inner_background.color = "grey"
            m = TextFace('    ')
            m.inner_background.color = "white"

        n.opacity = 1.
        n.margin_top = 2
        n.margin_right = 2
        n.margin_left = 0
        n.margin_bottom = 2

        m.margin_top = 2
        m.margin_right = 0
        m.margin_left = 20
        m.margin_bottom = 2

        lf.add_face(m, 0, position="aligned")
        lf.add_face(n, 1, position="aligned")

        # add spa typing
        if head:
            n = TextFace(' spa ')
            n.margin_top = 2
            n.margin_right = 2
            n.margin_left = 2
            n.margin_bottom = 2
            n.rotation = 270
            n.vt_align = 2
            n.hz_align = 2
            n.inner_background.color = "white"
            n.opacity = 1.
            tss.aligned_header.add_face(n, column_add-2)
        if lf.name in leaf_id2spa:
            n = TextFace(' %s ' % leaf_id2spa[lf.name])
            n.inner_background.color = "white"
        else:
            n = TextFace('  na  ')
            n.inner_background.color = "grey"
        n.opacity = 1.
        n.margin_top = 2
        n.margin_right = 2
        n.margin_left = 2
        n.margin_bottom = 2

        lf.add_face(n, column_add-2, position="aligned")

        # add mecA typing
        if head:
            n = TextFace(' mecA ')
            n.margin_top = 2
            n.margin_right = 2
            n.margin_left = 2
            n.margin_bottom = 2
            n.rotation = 270
            n.vt_align = 2
            n.hz_align = 2
            n.inner_background.color = "white"
            n.opacity = 1.
            tss.aligned_header.add_face(n, column_add-1)
        if lf.name in leaf_id2meca:
            n = TextFace(' %s ' % leaf_id2meca[lf.name])
            if leaf_id2meca[lf.name] == 'Perfect':
                n.inner_background.color = "red"
            elif leaf_id2meca[lf.name] == 'Strict':
                n.inner_background.color = "orange"
            else:
                n.inner_background.color = "white"
        else:
            n = TextFace('   na   ')
            n.inner_background.color = "grey"
        n.opacity = 1.
        n.margin_top = 2
        n.margin_right = 2
        n.margin_left = 2
        n.margin_bottom = 2

        lf.add_face(n, column_add-1, position="aligned")

        # loop to add virulence gene hits
        for column, protein_id in enumerate(ordered_queries):
            # draw labels at the top of each column
            if head:
                if show_identity_values:
                    n = TextFace(' %s ' % str(protein_id))
                    n.margin_top = 2
                    n.margin_right = 2
                    n.margin_left = 2
                    n.margin_bottom = 2
                    n.rotation = 270
                    n.vt_align = 2
                    n.hz_align = 2
                    n.inner_background.color = "white"
                    n.opacity = 1.
                    tss.aligned_header.add_face(n, column+column_add)
                else:
                    n = TextFace(' %s ' % str(protein_id), fsize=6)
                    n.margin_top = 0
                    n.margin_right = 0
                    n.margin_left = 0
                    n.margin_bottom = 0
                    n.rotation = 270
                    n.vt_align = 2
                    n.hz_align = 2
                    n.inner_background.color = "white"
                    n.opacity = 1.
                    # lf.add_face(n, col, position="aligned")
                    tss.aligned_header.add_face(n, column+column_add)
            # draw column content
            if lf.name not in leaf_id2protein_id2identity:
                n = TextFace(' %s ' % str('  na  '))
                n.opacity = 1.
                n.margin_top = 2
                n.margin_right = 2
                n.margin_left = 2
                n.margin_bottom = 2
                n.inner_background.color = "grey"
                lf.add_face(n, column+column_add, position="aligned")
            else:
                if protein_id in leaf_id2protein_id2identity[lf.name]:
                    identity_value = float(leaf_id2protein_id2identity[lf.name][protein_id])
                    color = rgb2hex(m_blue.to_rgba(identity_value))


                    if show_identity_values:
                        # report identity values in coloured boxes
                        # adapt box size depending the digit width
                        if str(identity_value) == '100.00' or str(identity_value) == '100.0':
                            identity_value = '100'
                            n = TextFace(" %s  " % identity_value)
                        else:
                            n = TextFace("%.2f" % round(float(identity_value), 2))
                        # color text to white for dark cells
                        if float(identity_value) > 95:
                            n.fgcolor = "white"
                        n.opacity = 1.
                        n.margin_top = 2
                        n.margin_right = 2
                        n.margin_left = 2
                        n.margin_bottom = 2
                        n.inner_background.color = color
                        lf.add_face(n, column+column_add, position="aligned")
                    else:
                        # draw coloured boxes without text
                        n = TextFace('  ')
                        n.margin_top = 0
                        n.margin_right = 0
                        n.margin_left = 0
                        n.margin_bottom = 0
                        # n.color = color
                        n.inner_background.color = color
                        lf.add_face(n, column+column_add, position="aligned")
                else:
                    n = TextFace('  %s  ' % str('  -  '))
                    n.opacity = 1.
                    n.margin_top = 2
                    n.margin_right = 2
                    n.margin_left = 2
                    n.margin_bottom = 2
                    n.inner_background.color = "white"
                    lf.add_face(n, column+column_add, position="aligned")

        # end of first leaf: turn off header
        head = False

    # add boostrap supports
    for n in t1.traverse():
        nstyle = NodeStyle()
        if n.support < 0.9:
            nstyle["fgcolor"] = "blue"
            nstyle["size"] = 6
            n.set_style(nstyle)
        else:
            nstyle["fgcolor"] = "red"
            nstyle["size"] = 0
            n.set_style(nstyle)

    return t1, tss
Ejemplo n.º 5
0
    time_begin = trackResult[r, 1]
    time_end = trackResult[r, 2]
    parent_id = trackResult[r, 3]
    time_duration = np.abs(time_begin - time_end)
    # for root
    if parent_id == 0:
        # Add name to root for the first iteration
        root.add_feature("name", str(cell_id))
        # change the branch length
        root.add_feature("dist", time_duration)
        #change node style
        root.set_style(ns_root)

        # set node name to face
        nameFace = TextFace(root.name)
        nameFace.fgcolor = "white"
        nameFace.fsize = 15
        #        nameFace.border.width = 1
        nameFace.background.color = "green"
        node_cur.add_face(nameFace, column=1, position="branch-bottom")

    else:  # for child
        #### search the parent node by parent_id
        node_cur = root.search_nodes(name=str(parent_id))
        # there should be only one parent node
        if len(node_cur) == 1:
            #### set child with its id
            node_cur = node_cur[0].add_child(name=str(cell_id))
            #### set duration
            node_cur.add_feature("dist", time_duration)
Ejemplo n.º 6
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
Ejemplo n.º 7
0
def plot_heatmap_tree_locus(biodb,
                            tree_file,
                            taxid2count,
                            taxid2identity=False,
                            taxid2locus=False,
                            reference_taxon=False,
                            n_paralogs_barplot=False):
    '''

    plot tree and associated heatmap with count of homolgs
    optional:
        - add identity of closest homolog
        - add locus tag of closest homolog

    '''

    from chlamdb.biosqldb import manipulate_biosqldb

    server, db = manipulate_biosqldb.load_db(biodb)

    taxid2organism = manipulate_biosqldb.taxon_id2genome_description(
        server, biodb, True)

    t1 = Tree(tree_file)
    ts = TreeStyle()
    ts.draw_guiding_lines = True
    ts.guiding_lines_color = "gray"
    # Calculate the midpoint node
    R = t1.get_midpoint_outgroup()
    # and set it as tree outgroup
    t1.set_outgroup(R)

    leaf_number = 0

    for lf in t1.iter_leaves():

        if str(lf.name) not in taxid2count:
            taxid2count[str(lf.name)] = 0

    max_count = max([taxid2count[str(lf.name)] for lf in t1.iter_leaves()])

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

        # top leaf, add header
        if i == 0:

            n = TextFace('Number of homologs')
            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")
            ts.aligned_header.add_face(n, 1)

            if taxid2identity:
                n = TextFace('Protein identity')
                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")
                ts.aligned_header.add_face(n, 2)
            if taxid2locus:
                n = TextFace('Locus tag')
                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")
                ts.aligned_header.add_face(n, 3)

        leaf_number += 1

        lf.branch_vertical_margin = 0

        data = [taxid2count[str(lf.name)]]

        # possibility to add one or more columns
        for col, value in enumerate(data):
            col_index = col
            if value > 0:
                n = TextFace(' %s ' % str(value))
                n.margin_top = 2

                n.margin_right = 2
                if col == 0:
                    n.margin_left = 20
                else:
                    n.margin_left = 2
                n.margin_bottom = 2
                n.inner_background.color = "white"  # #81BEF7
                n.opacity = 1.
                lf.add_face(n, col, position="aligned")

            else:
                n = TextFace(' %s ' % str(value))
                n.margin_top = 2
                n.margin_right = 2
                if col == 0:
                    n.margin_left = 20
                else:
                    n.margin_left = 2
                n.margin_bottom = 2
                n.inner_background.color = "white"
                n.opacity = 1.
                lf.add_face(n, col, position="aligned")
        # optionally indicate number of paralogs as a barplot
        if n_paralogs_barplot:
            col_index += 1
            percent = (float(value) / max_count) * 100
            n = StackedBarFace([percent, 100 - percent],
                               width=150,
                               height=18,
                               colors=['#6699ff', 'white'],
                               line_color='white')
            n.rotation = 0
            n.inner_border.color = "white"
            n.inner_border.width = 0
            n.margin_right = 15
            n.margin_left = 0
            lf.add_face(n, col + 1, position="aligned")

        # optionally add additionnal column with identity
        if taxid2identity:
            import matplotlib.cm as cm
            from matplotlib.colors import rgb2hex
            import matplotlib as mpl

            norm = mpl.colors.Normalize(vmin=0, vmax=100)
            cmap = cm.OrRd
            m = cm.ScalarMappable(norm=norm, cmap=cmap)

            try:
                if round(taxid2identity[str(lf.name)], 2) != 100:
                    value = "%.2f" % round(taxid2identity[str(lf.name)], 2)
                else:
                    value = "%.1f" % round(taxid2identity[str(lf.name)], 2)
            except:
                value = '-'
            if str(lf.name) == str(reference_taxon):
                value = '         '
            n = TextFace(' %s ' % value)
            n.margin_top = 2
            n.margin_right = 2
            n.margin_left = 20
            n.margin_bottom = 2
            if not value.isspace() and value is not '-':
                n.inner_background.color = rgb2hex(m.to_rgba(float(value)))
                if float(value) > 82:
                    n.fgcolor = 'white'
            n.opacity = 1.
            if str(lf.name) == str(reference_taxon):
                n.inner_background.color = '#800000'

            lf.add_face(n, col_index + 1, position="aligned")
        # optionaly add column with locus name
        if taxid2locus:
            try:
                value = str(taxid2locus[str(lf.name)])
            except:
                value = '-'
            n = TextFace(' %s ' % value)
            n.margin_top = 2
            n.margin_right = 2
            n.margin_left = 2
            n.margin_bottom = 2
            if str(lf.name) != str(reference_taxon):
                n.inner_background.color = "white"
            else:
                n.fgcolor = '#ff0000'
                n.inner_background.color = "white"
            n.opacity = 1.
            lf.add_face(n, col_index + 2, position="aligned")
        lf.name = taxid2organism[str(lf.name)]

    return t1, leaf_number, ts