Ejemplo n.º 1
0
 def my_layout(node):
     if node.is_leaf():
         # If terminal node, draws its name
         name_face = ete3.AttrFace("name")
     else:
         # If internal node, draws label with smaller font size
         name_face = ete3.AttrFace("name", fsize=10)
     # Adds the name face to the image at the preferred position
     ete3.faces.add_face_to_node(name_face,
                                 node,
                                 column=0,
                                 position="branch-right")
 def tree_profile_layout(node):
     if node.is_leaf(
     ):  # the aligned leaf is "column 0", thus traits go to column+1
         node.set_style(
             ns1)  ## may be postponed to when we have ancestral states
         ete3.add_face_to_node(ete3.AttrFace("name",
                                             fsize=label_font_size,
                                             text_suffix="   "),
                               node,
                               0,
                               position="aligned")
         for column, (rgb_val, lab) in enumerate(
                 zip(d_seq[node.name], d_seq_lab[
                     node.name])):  ## colour of csv.loc[node.name, "adm2"]
             label = {
                 "text": lab[:10],
                 "color": "Black",
                 "fontsize": label_font_size - 1
             }
             ete3.add_face_to_node(ete3.RectFace(50,
                                                 10,
                                                 fgcolor=rgb_val,
                                                 bgcolor=rgb_val,
                                                 label=label),
                                   node,
                                   column + 1,
                                   position="aligned")
     else:
         node.set_style(ns2)
    def mylayout(n):
        if not n.is_leaf():
            #print("\n\n\nintnode_lossdict", intnode_lossdict.keys())
            shortn = int(n.name.split('_')[1])

            number_of_hogs = len(HOG_groups_dict[intnodes[shortn]].keys())
            number_of_gains = number_of_hogs
            try:
                number_of_losses = int(intnode_lossdict[shortn])
            except:
                number_of_losses = 0

            #thisface = ete3.faces.BarChartFace([int(number_of_losses), int(number_of_gains)],
            #                                   colors=ete3.COLOR_SCHEMES["set1"],
            #                              #["Tomato","DarkCyan"],
            #                              labels=["#Losses","#Gains"],
            #                              width=20, height=40, min_value=0, max_value=4100)
            #thisface.opacity = 0.8


            thisfaceA = ete3.faces.TextFace('L: ' + str(int(number_of_losses)) + '\n' + 'G: ' + str(int(number_of_gains)))
            thisfaceA.opacity = 0.8
            ete3.faces.add_face_to_node(thisfaceA, n, column=0, position="branch-right")
            ete3.faces.add_face_to_node(ete3.AttrFace("name"), n, column=1)
        else:
            pass
Ejemplo n.º 4
0
def _align_leaf_name(tree):
    attr_face = ete3.AttrFace('name')
    text_face = ete3.TextFace('  ')
    for leaf in tree:
        leaf.add_face(text_face, column=0, position='aligned')
        leaf.add_face(attr_face, column=1, position='aligned')
    return 0
Ejemplo n.º 5
0
 def CanSNPer_tree_layout(self, node):
     '''Layout function for ETE3 trees.'''
     # Adds the name face to the image at the top side of the branch
     if not node.is_root():
         ete3.faces.add_face_to_node(ete3.AttrFace("name"),
                                     node,
                                     column=0,
                                     position="branch-top")
Ejemplo n.º 6
0
    def layout(node):
        N = ete3.AttrFace("name", fsize=30)
        N.margin_right = 10
        if node.is_leaf():
            if node.name == "Orussus_abietinus":
                N.background.color = "lightblue"
            elif node.name == "Athalia_rosae":
                N.background.color = "lightgreen"

            ete3.faces.add_face_to_node(N, node, 0, position="aligned")
    def tree_profile_layout(
        node
    ):  # prepare table and other node information (local function so mind the identation)
        if "NORW" in (getattr(node, "submission_org_code")):
            this_color = "darkred"
        else:
            this_color = "#080816"

        node.img_style['hz_line_type'] = node.img_style[
            'vt_line_type'] = 0  # 0=solid, 1=dashed, 2=dotted
        node.img_style['hz_line_width'] = node.img_style['vt_line_width'] = 4
        node.img_style['hz_line_color'] = node.img_style[
            'vt_line_color'] = this_color

        if node.is_leaf(
        ):  # the aligned leaf is "column 0", thus traits go to column+1
            node.img_style['size'] = 2
            node.img_style['shape'] = "sphere"
            node.img_style['fgcolor'] = this_color
            ete3.add_face_to_node(ete3.AttrFace("name",
                                                fsize=label_font_size,
                                                text_suffix="   "),
                                  node,
                                  0,
                                  position="aligned")
            for column, (rgb_val, lab, wdt) in enumerate(
                    zip(d_seq_color[node.name], d_seq_label[node.name],
                        rect_width)):
                label = {
                    "text": lab[:10],
                    "color": "Black",
                    "fontsize": label_font_size - 1
                }
                ete3.add_face_to_node(ete3.RectFace(wdt,
                                                    12,
                                                    fgcolor=rgb_val,
                                                    bgcolor=rgb_val,
                                                    label=label),
                                      node,
                                      2 * column + 1,
                                      position="aligned")
                ete3.add_face_to_node(ete3.RectFace(2,
                                                    12,
                                                    fgcolor="#ffffff",
                                                    bgcolor="#ffffff",
                                                    label=""),
                                      node,
                                      2 * column + 2,
                                      position="aligned")
        else:
            node.img_style['size'] = 0
Ejemplo n.º 8
0
def tree_plot(phylo, Bsize=1.0):
    T = phylo
    ts = ete3.TreeStyle()
    ts.show_leaf_name = False
    for n in T.traverse():
        if n.is_leaf():
            Nlabel = ete3.AttrFace('name',
                                   fsize=14,
                                   ftype='Arial',
                                   fstyle='italic')
            n.add_face(face=Nlabel, column=0, position='aligned')
        NOg = ete3.AttrFace('Total', fsize=10, ftype='Arial')
        n.add_face(face=NOg, column=0, position='branch-bottom')
        #Set node style
        nstyle = ete3.NodeStyle()
        nstyle["fgcolor"] = 'Red'
        nstyle["shape"] = "circle"
        nstyle["hz_line_color"] = "Gray"
        nstyle["hz_line_width"] = 2
        nstyle["vt_line_width"] = 2
        nstyle["vt_line_color"] = "Gray"
        nstyle["size"] = n.Total * Bsize
        n.set_style(nstyle)
    return ts
Ejemplo n.º 9
0
def mkEteHlaTree(newick_str, midpoint=False, colorfun=(lambda x: 'black')):
    """
    Transform a Newick tree into the ETE format.

    Args:
        newick_str (str): a string representing the tree in the Newick format

    Kwargs:
        midpoint (bool): if True, find the midpoint of the tree and re-root.
        colorfun (function): a rule for coloring faces (TODO)

    Returns:
        A tuple consisting of an ete3.Tree object and a list of integer node names
    """
    tree = ete3.Tree(newick_str)
    if midpoint:
        tree.set_outgroup(
            tree.get_leaves()[0])  ## make arbitrary leaf the outgroup
        outgrp_node = tree.get_midpoint_outgroup()  ## now use ete algorithm
        tree.set_outgroup(outgrp_node)  ## and re-define the outgroup
    ## give nodes a name to be used in Bayesian model
    nodeNames = []
    for i, node in enumerate(tree.traverse()):
        if node.name != '':
            hla = mhctools.MhcObject(node.name, fmt="Newick")
            node.add_feature('hla', str(hla))  ## FIXME: use MhcObject
        node.name = str(i)
        nodeNames.append(i)
        ## set width and color of edges
        size = 10
        nstyle = ete3.treeview.NodeStyle()
        nstyle["vt_line_width"] = size
        nstyle[
            "hz_line_width"] = size  ## FIXME make sure that ultrametric trees are rendered properly
        ## make sure that ultrametric trees are rendered correctly
        nstyle["size"] = 0  ## do not render nodes
        node.set_style(nstyle)
        ## NB: colorEteTree overrides set_style
    ## set colors of the HLA tags
    for leaf in tree:
        N = ete3.AttrFace("hla", fsize=50, fgcolor=colorfun(leaf.hla))
        leaf.add_face(N, 0)
    return (tree, nodeNames)
    def plot_tree(self, pdf_fn):
        print("Plotting", pdf_fn, file=sys.stderr)
        ts = ete3.TreeStyle()
        ant = self.antibiotics.upper()
        ts.title.add_face(ete3.TextFace("{}{}".format(18 * " ", ant),
                                        fsize=60),
                          column=0)
        ts.show_leaf_name = False

        for n in self.tree.traverse():
            taxid = n.name
            nstyle = ete3.NodeStyle()
            res_cat = self.res_dict[taxid]
            nstyle["fgcolor"] = cat_to_color[res_cat]
            nstyle["size"] = 15
            n.set_style(nstyle)

            if n.is_leaf():
                N = ete3.AttrFace("name", fsize=20)
                n.add_face(N, 0)
                #add_face_to_node(N, n, 0, position="aligned")
                #n.add_face_to_node(ete3.TextFace("XXX"))

        self.tree.render(pdf_fn, tree_style=ts)
Ejemplo n.º 11
0
def layout(node):
    if node.is_leaf():
        N = ete3.AttrFace("name", fsize=30)
        ete3.faces.add_face_to_node(N, node, 0, position="aligned")
Ejemplo n.º 12
0
    tstyle.show_leaf_name = False
    tstyle.show_branch_length = False
    for branch in t:
        if "N" in branch.name:
            branch.delete()
    for branch in t:
        if "blood" in branch.name:
            t.set_outgroup(branch)
            root = t.get_tree_root()
            root.dist = 2 * branch.dist
            branch.delete()
            root.get_children()[0].delete()
    for branch in t.traverse():
        if "_" in branch.name:
            #Print the leaf names in our own font
            name_face = ete3.AttrFace("name", fsize=vertical_margins[pid] + 10)
            branch.add_face(name_face, column=0, position="branch-right")
            branch.name = branch.name.split("_")[0]
#        else:
    if displaySVs:
        displaySVsOnPhylogenies(pid, t, SVs)
    else:
        displayDriversOnPhylogenies(pid, t, drivers, deletions)

    if displayCombo and displaySVs:
        displayDriversOnPhylogenies(pid, t, drivers, deletions)

    #        else:
    #            branch.add_feature(stuff="I'm internal!")
    #            upper = ete3.AttrFace("stuff", fsize=vertical_margins[pid])
    #            lower = ete3.TextFace("below", fsize=vertical_margins[pid])
Ejemplo n.º 13
0
        if leaf.genome_name in recipient_branch.get_leaf_names()
    ]

    donor_branch_in_reticulation = reticulation.get_common_ancestor(
        donor_intersection)
    recipient_branch_in_reticulation = reticulation.get_common_ancestor(
        recipient_intersection)

    reticulation.set_style(reticulation_style)
    donor_branch_in_reticulation.set_style(donor_style)
    recipient_branch_in_reticulation.set_style(recipient_style)

##color palette: blue, red, green , orange, purple, black
#color_palette   = '#2e2be2 #e22e2b #2be22e #f9a82c #8a2be2 #000000'
nameFaces = {}
nameFaces[1117] = ete3.AttrFace("name", fsize=10, fgcolor='#000000')
nameFaces[1224] = ete3.AttrFace("name", fsize=10, fgcolor='#a20417')


def myLayout(node):
    if node.is_leaf():
        node.img_style['size'] = 0
        genome_name, gene_name = node.name.split('_')
        node.name = genome_table.loc[genome_name, 'organism_name']
        ete3.add_face_to_node(nameFaces[genome_table.loc[genome_name,
                                                         'phylum']],
                              node,
                              2,
                              aligned=True)
    elif node.is_root():
        node.img_style['size'] = 0
Ejemplo n.º 14
0
def main(treefile,
         outfile=None,
         cladelistfile=None,
         datafile=None,
         prune=False,
         log_dist=False,
         values=None,
         quoted_node_names=False,
         startmatch=False):

    global tot_clades
    tot_clades = 0

    tree = ete3.Tree(treefile, format=1, quoted_node_names=quoted_node_names)
    if cladelistfile:
        with open(cladelistfile) as f:
            cladelist = set((line.rstrip().split('\t')[0] for line in f if \
                                not line.startswith('#')))
    else:
        cladelist = set()

    if datafile:
        assert values
        data = pd.read_csv(datafile, sep='\t', index_col=0, header=0)
        assert all(val in data.columns for val in values)
        value_face = {
            val: ete3.AttrFace(val,
                               formatter=' %.2f ',
                               fgcolor='grey',
                               fsize=8)
            for val in values
        }
        max_val = data[values].max().max()
        min_val = data[values].min().min()
        average_val = data[values].mean().mean()

    alt_col = ['#7FD09C', '#4cbdad']

    ns = [ete3.NodeStyle(bgcolor=col) for col in alt_col]
    default_ns = ete3.NodeStyle(size=0)
    labelface = ete3.AttrFace('name')

    if startmatch:
        test = lambda node: any(
            node.name.startswith(clade) for clade in cladelist) and not prune
    else:
        test = lambda node: node.name in cladelist and not prune
    #for node in tree.traverse():
    def mylayout(node):
        global tot_clades
        if log_dist:
            node.add_feature('orig_dist', node.dist)
            node.dist = log10(
                node.dist
            ) if node.dist > 0 else -log10(-node.dist) if node.dist < 0 else 0

        if test(node):
            node.set_style(ns[0])
            ns.insert(0, ns.pop())  #Cycle through colors
            if not node.is_leaf():
                ete3.add_face_to_node(labelface,
                                      node,
                                      column=0,
                                      position='branch-right')
            tot_clades += 1
        else:
            node.set_style(default_ns)

        if datafile and node.is_leaf():
            node.add_feature('profile',
                             [data[val][node.name] for val in values])
            node.add_feature('deviation', [0.0] * len(values))
            heatface = ete3.ProfileFace(max_val,
                                        min_val,
                                        average_val,
                                        width=20 * len(values),
                                        height=20,
                                        style='heatmap')
            ete3.add_face_to_node(heatface, node, column=1, aligned=True)

            for i, val in enumerate(values, start=2):
                node.add_feature(val, data[val][node.name])
                ete3.add_face_to_node(value_face[val],
                                      node,
                                      column=i,
                                      aligned=True)

    if prune:
        tree.prune(cladelist, preserve_branch_length=True)
        tree.dist = 0

    if outfile:
        tree.render(outfile, mylayout)
    else:
        tree.show(layout=mylayout)

    # Print summary
    print("Found %d clades" % tot_clades)