Exemplo n.º 1
0
def draw_raw_tree(filename: str) -> None:
    """Draws a raw tree from ete3 representation
    stored in a file

    Parameters
    ----------
    filename : str
        a name of the file

    Returns
    -------
    None
    """

    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.layout_fn = layout_raw
    ts.rotation = 90
    ts.branch_vertical_margin = 10
    ts.show_scale = False
    ts.scale = 50
    ts.title.add_face(TextFace(" ", fsize=20), column=0)

    ete3_desc = read_ete3_from_file(filename)
    tree = Tree(ete3_desc, format=1)

    # tree.show(tree_style=ts)
    return tree.render("%%inline",tree_style=ts)
Exemplo n.º 2
0
def plot_uncorrected_phylogeny(tree, species, latin_names, species_history):
    """
    Generates a PDF figure of the input tree with same length for all branches.

    :param tree: input tree from configuration file
    :param species: the current focal species
    :param latin_names: a dictionary-like data structure that associates each informal species name to its latin name
    :param species_history: the list of ancestor nodes of the focal species, including the focal species and going up to the root.
    """
    label_leaves_with_latin_names(tree, latin_names)
    node_and_branch_style(tree)
    ts = TreeStyle()
    # ts.title.add_face(TextFace("  Input phylogenetic tree", ftype="Arial", fsize=18), column=0)
    ts.orientation = 1
    ts.branch_vertical_margin = 14
    ts.show_leaf_name = False  # because there is a Face showing it
    ts.show_branch_length = False
    ts.margin_left = 25
    ts.margin_right = 25
    ts.margin_top = 25
    ts.margin_bottom = 25
    ts.scale = 200
    ts.show_scale = False
    tree.render(os.path.join("rate_adjustment", f"{species}",
                             f"{_TREE.format(species)}"),
                w=4.5,
                units="in",
                tree_style=ts)
def writeTrees(trees, label):
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.branch_vertical_margin = 20
    ts.scale = 0.05
    outtrees = open(lengthdir + label + ".newick", "w")
    #round the branch lengths
    for index, tree in enumerate(trees):
        #print(tree)
        for branch in tree.traverse():
            branch.dist = round(branch.dist)
        line = tree.write(format=1)
        outtrees.write(line + "\n")
        if (showTrees):
            for branch in tree.traverse():
                if branch.dist != 0:
                    text_face = TextFace(str(round(branch.dist, 2)), fsize=30)
                    branch.add_face(text_face, column=1, position="branch-top")
                elif branch.name != "":
                    name_face = AttrFace("name", fsize=30)
                    branch.add_face(name_face,
                                    column=0,
                                    position="branch-right")
                else:
                    print("Branch found of length zero but not a tip in tree",
                          label)
                    print(branch)
            filename = label
            if len(trees) > 1:
                filename += "_" + str(index)
            filename += ".png"
            tree.render(lengthdir + filename, tree_style=ts)
            #foo()
    outtrees.close()
Exemplo n.º 4
0
def traitTreeMinimal(traits, mapper):
    ### Take dict of traits and [R,G,B]-returning function
    ### Draw a tree with the continuous trait painted on via a colormapping function
    def rgb2hex(r, g, b):
        hex = "#{:02x}{:02x}{:02x}".format(r, g, b)
        return hex

    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.rotation = 270
    ts.complete_branch_lines_when_necessary = False
    #ts.optimal_scale_level = "full"
    ts.scale = 800

    # default NodeStyle
    nstyle = NodeStyle()
    nstyle["size"] = 0
    nstyle["hz_line_color"] = "grey"
    nstyle["vt_line_color"] = "grey"
    nstyle["hz_line_width"] = 3
    nstyle["vt_line_width"] = 3

    for n in tree.traverse():
        chroma = rgb2hex(*[
            int(val) for val in mapper(traits[n.ND], gamma=0.8, scaleMax=255)
        ])  # setup for wl2RGB
        nf = CircleFace(radius=10, color='none', style='circle', label=None)
        n.set_style(nstyle)
        n.add_face(nf, column=0, position='branch-top')

    outFile = args.output + "/test_trees/cont_trait.pdf"
    tree.render(outFile, tree_style=ts)
    print >> sys.stderr, outFile
def get_tree(tree1, abundance):

    for n in tree1.iter_leaves():

        face1 = CircleFace(abundance[n.name][0],
                           abundance[n.name][1],
                           style='sphere')
        face2 = TextFace(n.name,
                         ftype='Verdana',
                         fsize=10,
                         fgcolor='black',
                         penwidth=0,
                         fstyle='normal',
                         tight_text=False,
                         bold=False)
        face1.opacity = 0.9

        n.add_face(face1, column=0)
        n.add_face(
            face2, column=0,
            position="branch-right")  #branch-top branch-bottom branch-right

    tree1.ladderize()

    ts = TreeStyle()
    ts.mode = 'r'
    ts.scale = scale1
    ts.show_leaf_name = False

    return tree1, ts
Exemplo n.º 6
0
def add_labels_n_colors_2_tree(tree_path, refseq_2_entropy, colors, feature, out):
    """
    add entropy measurement to a tree and color it's leaves
    :param tree_path: a path to a tree
    :param refseq_2_entropy: a data base with entropy values for each refseq id
    :param out: output directory path to save the results
    :return: a tree with colors and entropy labels
    """
    print(tree_path)
    str_tree = tree_2_string(tree_path)
    if str_tree == '':
        return
    tree = Tree(str_tree)


    # get all refseq ids in the tree and all corresponding entropy values
    all_leaves = []

    for node in tree:
        if node.is_leaf():
            all_leaves.append(node.name)

    #all_values = refseq_2_entropy[refseq_2_entropy['refseq_id'].isin(all_leaves)]['entropy_5'].values
    all_values = refseq_2_entropy[feature].values

    num_leaves = len(all_leaves)

    # create a gradient color bar
    #colors = linear_gradient("#DC9221", "#33C193", n=num_leaves)

    #mapping = value_2_color(all_values, colors['hex'])
    mapping = value_2_color(all_values, colors['hex'])

    for node in tree:
        if node.is_leaf():
            value = refseq_2_entropy[refseq_2_entropy['refseq_id'] == node.name.split('.')[0]][feature].values[0]
            virus_name = refseq_2_entropy[refseq_2_entropy['refseq_id'] == node.name.split('.')[0]]['virus_name'].values[0]

            # change virus name
            node.name = virus_name
            c = mapping[str(value)]
            node.add_feature("label", value)
            label_face = TextFace(node.label, fgcolor=c, fsize=22)
            node.add_face(label_face, column=0, position='branch-right')


    family = os.path.basename(tree_path).split('.')[0]

    ts = TreeStyle()
    ts.mode = 'c'
    ts.scale = 5
    # Disable the default tip names config
    ts.show_leaf_name = True
    ts.show_scale = True
    ts.show_branch_length = True
    ts.title.add_face(TextFace("{} values for {}".format(feature, family), fsize=20), column=0)
    # Draw Tree
    tree.render(os.path.join(out, '{}_{}_tree.pdf'.format(family, feature)), dpi=300, tree_style=ts)
def draw_tree(pstrains, names=False, subset=None):
    evol = {x.rstrip() for x in open('input/evolution_experiment.txt')}

    tree = get_tree('input/tree.nwk')

    strains = {x.name for x in tree.traverse() if x.name != ''}
    if subset is None:
        subset = strains
    evol_tree = {x.name for x in tree.traverse() if x.name in evol}

    commensals = {}
    for x in strains:
        if pstrains[x] == 'Commensal strain':
            commensals[x] = colors.cnames['blue']
        elif pstrains[x] == 'Pathogenic strain':
            commensals[x] = colors.cnames['red']
        else:
            commensals[x] = colors.cnames['white']

    ref = NodeStyle()
    ref['fgcolor'] = sns.xkcd_rgb['light red']
    inner = NodeStyle()
    inner['size'] = 0
    for n in tree.traverse():
        if not n.is_leaf():
            n.set_style(inner)
            continue
        if n.name not in subset:
            continue
        if not names:
            r = RectFace(10, 3, commensals[n.name], commensals[n.name])
            n.add_face(r, 0, position="aligned")
        ev = NodeStyle()
        ev["fgcolor"] = "black"
        ev['size'] = 3
        n.set_style(ev)

    circular_style = TreeStyle()
    circular_style.mode = "c"
    if not names:
        circular_style.scale = 1300
    else:
        circular_style.scale = 7300
    circular_style.show_leaf_name = names
    return tree, circular_style
Exemplo n.º 8
0
Arquivo: tree.py Projeto: senaj/atlas
def render_tree(T, out):

    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.mode = "c"
    ts.scale = 200
    ts.show_scale = False

    T.render(out, tree_style=ts, layout=layout_black_circles)
Exemplo n.º 9
0
    def draw(self,
             file,
             colors,
             color_internal_nodes=True,
             legend_labels=(),
             show_branch_support=True,
             show_scale=True,
             legend_scale=1,
             mode="c",
             neighbours=None,
             neighbours_block=None):
        max_color = len(colors)

        used_colors = set()
        for node in self.tree.traverse():
            if not (color_internal_nodes or node.is_leaf()): continue
            color = colors[min(node.color, max_color - 1)]
            node.img_style['bgcolor'] = color
            used_colors.add(color)

        ts = TreeStyle()
        ts.mode = mode
        ts.scale = self.scale
        # Disable the default tip names config
        ts.show_leaf_name = False
        ts.show_branch_support = show_branch_support

        # ts.branch_vertical_margin = 20
        ts.show_scale = show_scale
        cur_max_color = max(v.color for v in self.tree.traverse())
        current_colors = colors[0:cur_max_color + 1]

        for i, (label, color_) in enumerate(zip(legend_labels,
                                                current_colors)):
            if color_ not in used_colors: continue
            rf = RectFace(20 * legend_scale, 16 * legend_scale, color_, color_)
            rf.inner_border.width = 1
            rf.margin_right = 14
            rf.margin_left = 14

            tf = TextFace(label, fsize=26 * legend_scale)
            tf.margin_right = 14

            ts.legend.add_face(rf, column=0)
            ts.legend.add_face(tf, column=1)

        if neighbours:
            old_tree = self.tree.copy()
            self.draw_neighbours(neighbours, neighbours_block)

        self.tree.render(file, w=1000, tree_style=ts)

        if neighbours:
            self.tree = old_tree
Exemplo n.º 10
0
def get_tree_style():
    ts = TreeStyle()
    ts.show_leaf_name = False  # True
    ts.layout_fn = layout
    ts.rotation = 90
    ts.branch_vertical_margin = 10
    ts.show_scale = False
    # ts.mode = "c"
    ts.scale = 50

    ts.title.add_face(TextFace(" ", fsize=20), column=0)

    # for n in t.traverse():
    #     nstyle = NodeStyle()
    #     nstyle["fgcolor"] = "red"
    #     nstyle["size"] = 15
    #     n.set_style(nstyle)

    # ts.show_leaf_name = True
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, NO_SUPPORT_COLOR, NO_SUPPORT_COLOR),
                       column=0)
    ts.legend.add_face(TextFace("  Topic with no support (u(t)=0)"), column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, "#90ee90", "#90ee90"), column=0)
    ts.legend.add_face(TextFace("  Topic with minor support 0<u(t)<=0.4"),
                       column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, "green", "green"), column=0)
    ts.legend.add_face(
        TextFace(u"  Topic with medium support 0.4<u(t)<=0.6   "), column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(20, 20, "#004000", "#004000"), column=0)
    ts.legend.add_face(TextFace("  Topic with high support u(t)>0.6"),
                       column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(CircleFace(10, "red"), column=0)
    ts.legend.add_face(TextFace("  Gap"), column=1)
    ts.legend.add_face(TextFace("  "), column=0)
    ts.legend.add_face(TextFace("  "), column=1)
    ts.legend.add_face(RectFace(40, 40, "#004000", "#004000"),
                       column=0)  # green
    # ts.legend.add_face(CircleFace(15, "green"), column=1)
    ts.legend.add_face(TextFace("  Head subject or offshoot"), column=1)
    ts.legend_position = 4

    # ts.title.add_face(TextFace(" ", fsize=20), column=0)

    return ts
Exemplo n.º 11
0
def ete_draw(t,fname=None,title='',mode='r',outfile='ete_tree.png'):
    from ete3 import Tree, TreeStyle, Phyloxml, TextFace
    t.children
    ts = TreeStyle()
    #ts.branch_vertical_margin = 10
    ts.show_scale=False
    ts.scale =  800
    ts.show_leaf_name = False    
    ts.mode = mode
    ts.title.add_face(TextFace(title, fsize=20), column=0)        
    t.render(outfile,dpi=300,h=800,tree_style=ts)
    return ts
Exemplo n.º 12
0
    def markSpeciesOnTree(self, tree, output_name):

        for species in self.species:
            nstyle = NodeStyle()
            nstyle["bgcolor"] = "purple"
            (tree & species).set_style(nstyle)

        ts = TreeStyle()
        #ts.mode = "c"
        ts.scale = 500
        #tree.show(tree_style=ts)
        tree.render(output_name, dpi=300, units="mm", tree_style=ts)
Exemplo n.º 13
0
    def draw(self, Ts):

        circular_style = TreeStyle()
        #circular_style.mode = "c"
        circular_style.scale = 20
        img_fname = '.'.join([self.tree_bname, self.img_format])
        self.tree.render(img_fname, tree_style=Ts, w=400, units="mm")
        #, tree_style=circular_style)
        try:
            subprocess.call(['gpicview', img_fname])
        except:
            pass
Exemplo n.º 14
0
def drawTree(treeFile, ShowBool):
	"""
	Draw a tree from a phy file
	"""
	t = Tree(treeFile)
	imgFile = treeFile.replace(".tree", ".tree.png")

	# Basic tree style
	ts = TreeStyle()
	ts.show_leaf_name = True
	ts.show_branch_support = True
	ts.scale =  160

	# Draws nodes as small red spheres of diameter equal to 10 pixels
	nstyle = NodeStyle()
	nstyle["shape"] = "sphere"
	nstyle["size"] = 10
	nstyle["fgcolor"] = "darkred"
	#nstyle["faces_bgcolor"] = "pink"

	nstyle2 = NodeStyle()
	nstyle2["shape"] = "sphere"
	nstyle2["size"] = 10
	nstyle2["fgcolor"] = "darkblue"
	


	# Gray dashed branch lines
	nstyle["hz_line_type"] = 1
	nstyle["hz_line_color"] = "#cccccc"

	# Applies the same static style to all nodes in the tree. Note that,
	# if "nstyle" is modified, changes will affect to all nodes
	for n in t.traverse():
		if n.is_leaf():
			if n.name.split("|")[-1] == "GI":
				n.set_style(nstyle)
			if n.name.split("|")[-1] == "plasmid":
				n.set_style(nstyle2)
			gi = n.name.split("|")[1]
			n.name = n.name.split("|")[0] #+ "   " + n.name.split("|")[1]
			n.name = n.name.replace("_tRNA_modification_GTPase_", "")
			n.name = n.name.replace("_DNA", "")
			n.name = " " + n.name + " "
			if n.name[-1] == "_": n.name.rstrip()
			
			taxon, color = taxonToColour(gi)
			n.add_face(TextFace(taxon, fgcolor = color, fsize = 8), column=1, position="branch-right")
			#n.img_style["bgcolor"] = color
			
	if ShowBool == True: #permet de flipper les braches pour avoir des topologies similaires
		t.show(tree_style=ts)
	t.render(imgFile, w=393, units="mm", tree_style=ts)
Exemplo n.º 15
0
def drawTree(treeFile, ShowBool):
    """
	Draw a tree from a phy file
	"""
    t = Tree(treeFile)
    imgFile = treeFile.replace(".tree", ".tree.pdf")

    # Basic tree style
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_support = True
    ts.scale = 50

    # Draws nodes as small red spheres of diameter equal to 10 pixels
    nstyle = NodeStyle()
    nstyle["shape"] = "sphere"
    nstyle["size"] = 10
    nstyle["fgcolor"] = "darkred"
    #nstyle["faces_bgcolor"] = "pink"

    nstyle2 = NodeStyle()
    nstyle2["shape"] = "sphere"
    nstyle2["size"] = 10
    nstyle2["fgcolor"] = "darkblue"

    # Gray dashed branch lines
    nstyle["hz_line_type"] = 1
    nstyle["hz_line_color"] = "#cccccc"

    # Applies the same static style to all nodes in the tree. Note that,
    # if "nstyle" is modified, changes will affect to all nodes
    for n in t.traverse():
        if n.is_leaf():
            if n.name.split("|")[-1] == "GI":
                n.set_style(nstyle)
            if n.name.split("|")[-1] == "plasmid":
                n.set_style(nstyle2)
            gi = n.name.split("|")[1]
            n.name = n.name.split("|")[0]  #+ "   " + n.name.split("|")[1]
            n.name = n.name.replace("_tRNA_modification_GTPase_", "")
            n.name = n.name.replace("_DNA", "")
            n.name = " " + n.name + " "
            if n.name[-1] == "_": n.name.rstrip()

            taxon, color = taxonToColour(gi)
            n.add_face(TextFace(taxon, fgcolor=color, fsize=8),
                       column=1,
                       position="branch-right")
            #n.img_style["bgcolor"] = color

    if ShowBool == True:  #permet de flipper les braches pour avoir des topologies similaires
        t.show(tree_style=ts)
    t.render(imgFile, w=1024, units="mm", tree_style=ts)
def Generate_CircleTree(treeData, output_path):
    # Define output file name and its path
    file_name = "circle_tree.png"
    out_file = output_path + "/" + file_name

    # Build tree & incorporate desired parameters for visualization
    t = Tree(treeData)
    circular_style = TreeStyle()
    circular_style.mode = "c"
    circular_style.scale = 20

    # Produce/draw output figure: phylogeny
    t.render(file_name, w=183, units="mm", tree_style=circular_style)
def Generate_NormalTree(treeData, output_path):
    file_name = "normal_tree.png"
    out_file = output_path + "/" + file_name

    # Build tree & incorporate desired parameters for visualization
    t = Tree(treeData)
    #t.populate(50, random_dist=True)
    ts = TreeStyle()
    ts.show_leaf_name = True
    #ts.show_branch_length = True
    #ts.show_branch_support = True
    ts.scale = 20  # 120 pixels per branch length unit
    t.render(file_name, w=183, units="mm", tree_style=ts)
Exemplo n.º 18
0
def show_tree(tree):

    ts = TreeStyle()
    ts.scale = 1
    ts.show_leaf_name = True
    '''
	ts.rotation = 90
	ts.branch_vertical_margin = 10
	ts.scale = 50
	'''

    #ts.mode = "c"

    tree.show(tree_style=ts)
Exemplo n.º 19
0
def main(file_name):
	t = read_tree(file_name)

	nstyle = NodeStyle()
	nstyle["size"] = 0

	ts = TreeStyle()
	ts.show_leaf_name = False
	ts.scale = 25000 # pixels per branch length unit
	ts.layout_fn = layout

	for n in t.traverse():
		n.set_style(nstyle)

	# t.show(tree_style=ts)
	t.render(out_stem + "." + out_format, tree_style=ts)
Exemplo n.º 20
0
def writeTrees(trees, label):
    """
    Now that we have branch lengths, write out new Newick trees with the
    branch lengths included.  Note that ete3 does not seem to write out
    the length of the root automatically, so we add it in by hand.
    """
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.branch_vertical_margin = 20
    ts.scale = 0.05
    outtrees = open(lengthdir + label + ".newick", "w")
    for index, tree in enumerate(trees):
        #print(tree)
        #If needed:  round the branch lengths
        #        for branch in tree.traverse():
        #            branch.dist = round(branch.dist)
        line = tree.write(format=1)
        rootlen = round(tree.get_tree_root().dist)
        line = line[:-1] + ":" + str(rootlen) + ";"
        outtrees.write(line + "\n")
        if (showTrees):
            for branch in tree.traverse():
                if branch.name != "":
                    name_face = AttrFace("name", fsize=30)
                    branch.add_face(name_face,
                                    column=0,
                                    position="branch-right")
                if branch.dist != 0:
                    if branch.name == "":
                        text_face = TextFace(str(round(branch.dist, 2)),
                                             fsize=30)
                        branch.add_face(text_face,
                                        column=1,
                                        position="branch-top")
                else:
                    print("Branch found of length zero but not a tip in tree",
                          label)
                    print(branch)
            filename = label
            if len(trees) > 1:
                filename += "_" + str(index)
            filename += ".png"
            tree.render(lengthdir + filename, tree_style=ts)
            #foo()
    outtrees.close()
Exemplo n.º 21
0
def show(tf):
    try:
        os.environ['DISPLAY']
        from ete3 import TreeStyle
        flag = 0
    except (KeyError, ImportError):
        flag = 1
    if flag:
        tree = dp.Tree.get(path=tf, schema='newick', rooting='force-rooted')
        print(tree.as_ascii_plot())
    else:
        tree = ete.Tree(tf)
        ts = TreeStyle()
        ts.show_leaf_name = True
        ts.show_branch_length = True
        ts.scale = 25
        tree.show(tree_style=ts)
    return "Done"
Exemplo n.º 22
0
def plot_newick(aug_cluster_list, mode='c', db=-1):
    circular_style = TreeStyle()
    circular_style.mode = mode  # draw tree in circular mode
    circular_style.scale = 20
    circular_style.arc_span = 360

    if db > 0:
        newick = convert_to_newick_db(aug_cluster_list,
                                      len(aug_cluster_list) - 1, db)
        circular_style.mode = mode
    else:
        newick = convert_to_newick(aug_cluster_list, len(aug_cluster_list) - 1)
    newick = newick + ':0;'

    t = Tree(newick, format=1)
    t.show(tree_style=circular_style)
    if False:
        t.render('tree3.png', w=100, units='in', tree_style=circular_style)
    def draw(self,
             file,
             colors,
             color_internal_nodes=True,
             legend_labels=(),
             show_branch_support=True,
             show_scale=True,
             legend_scale=1,
             mode="c"):
        max_color = len(colors)

        for node in self.tree.traverse():
            if not (color_internal_nodes or node.is_leaf()): continue
            color = colors[min(node.color, max_color - 1)]
            node.img_style['bgcolor'] = color

        ts = TreeStyle()
        ts.mode = mode
        ts.scale = self.scale
        # Disable the default tip names config
        ts.show_leaf_name = False
        ts.show_branch_support = show_branch_support

        # ts.branch_vertical_margin = 20
        ts.show_scale = show_scale
        cur_max_color = max(v.color for v in self.tree.traverse())
        current_colors = colors[0:cur_max_color + 1]

        for i, (label, color_) in enumerate(zip(legend_labels,
                                                current_colors)):
            ts.legend.add_face(CircleFace(24 * legend_scale, color_), column=0)
            ts.legend.add_face(CircleFace(13 * legend_scale, 'White'),
                               column=1)
            ts.legend.add_face(TextFace(label, fsize=53 * legend_scale),
                               column=2)
            ts.legend.add_face(CircleFace(13 * legend_scale, 'White'),
                               column=3)

        # self.tree.render("ete_tree.pdf", dpi=300, tree_style=ts)
        self.tree.render(file, w=1000, tree_style=ts)
Exemplo n.º 24
0
def tree_viewer(treefolder):
    """
    DESCRIPTION:
    A function to create the representation of the tree with ete. Given the folder with the files in the tree folder it
    creates the tree representation in the media folder.
    :param treefolder: [pathlib] route to the subfolder in the tree folder which contains the data of the inference.
    :return: None. It writes the image in the media folder.
    """
    filename = os.path.basename(os.path.normpath(treefolder)) + '.txt.treefile'
    imagefile = os.path.basename(os.path.normpath(treefolder)) + '.png'
    treeroute = treefolder / filename
    file = open(treeroute, 'r')
    tree = file.read()
    file.close()
    tree = Tree(tree)
    circular_style = TreeStyle()
    circular_style.mode = "c"
    circular_style.scale = 20
    tree.render(str(MEDIA_DIR / imagefile),
                w=1024,
                units='mm',
                tree_style=circular_style)
Exemplo n.º 25
0
def showTreeStructure(inputfile):
    t = ClusterTree(
        "./OUTPUT/%s/NWK/HIER_CLUST_%s.nwk" %
        ((inputfile.split("_")[0]).upper(), inputfile.split(".")[0]))

    def mylayout(node):
        global flag
        #print node.left
        # print "node",len(node )
        #if len(node)!=1:# and flag == 1:
        #    if flag == 1:
        #        pidlist= getpid(node)
        #print pidlist
        #       dcs=DoCS(pidlist,PRO_pfam)
        #print dcs
        #       if dcs>=0.5:
        #          flag=0

        # print pidlist,len(node),dcs
        # print "_____________________"

        if node.is_leaf():
            node.img_style["shape"] = "sphere"
            node.img_style["size"] = 10
            node.img_style["fgcolor"] = 'purple'

    t.dist = 0
    t.convert_to_ultrametric(1, strategy="fixed")

    ts = TreeStyle()
    ts.scale = 230
    ts.root_opening_factor = 5.0
    ts.mode = "c"
    ts.layout_fn = mylayout
    #print mylayout
    t.show(tree_style=ts)
    print("--------------------------------")
    print("completed")
Exemplo n.º 26
0
def get_tree_style(**kwargs):
    style = TreeStyle()
    style.layout_fn = layout
    style.allow_face_overlap = True
    style.branch_vertical_margin = 5
    style.complete_branch_lines_when_necessary = False
    style.draw_aligned_faces_as_table = False
    style.scale = 1500
    style.scale_length = 0.05
    style.show_branch_support = False
    style.show_leaf_name = False

    for key, value in kwargs.items():
        if value == "True":
            value = True
        else:
            try:
                value = float(value)
            except ValueError:
                pass
        setattr(style, key, value)

    return style
Exemplo n.º 27
0
    def __init__(self, root_text):
        # Inicializa la estructura árbol
        tree = Tree()

        # Formateamos el árbol indicandole un estilo
        style = TreeStyle()
        style.show_leaf_name = True
        style.show_scale = False
        style.scale = 100
        style.branch_vertical_margin = 30
        style.rotation = 0
        style.orientation = 0
        self.style = style
        self.tree = tree

        # Le damos estilo a la raíz del árbol
        self.tree.add_face(TextFace(root_text, fsize=10, fgcolor='darkred'),
                           column=0,
                           position='branch-right')
        self.tree.set_style(NodeStyle(size=20, hz_line_width=2,
                                      fgcolor='blue'))

        # Almacenamos la raíz del árbol como nodo actual
        self.curr_node = self.tree
    def create_plot(self, target_outputfile):
        from ete3 import Tree, TreeStyle, NodeStyle, faces, AttrFace, CircleFace, TextFace
        t = Tree()

        def layout(node):
            if node.is_leaf():
                N = AttrFace("name", fgcolor="black")
                faces.add_face_to_node(N, node, 0)
            if "weight" in node.features:
                # Creates a sphere face whose size is proportional to node's
                # feature 1/gini index
                circle_face = CircleFace(radius=node.weight,
                                         color="RoyalBlue",
                                         style="sphere")
                circle_face.hz_align = 2
                circle_face.opacity = 0.3
                text_face = TextFace(text=node.name)
                faces.add_face_to_node(circle_face, node, 0, position="float")
                faces.add_face_to_node(text_face, node, 0, position="float")

        # Create an empty TreeStyle
        ts = TreeStyle()

        # Set our custom layout function
        ts.layout_fn = layout
        ts.scale = 140
        # # Draw a tree
        # ts.mode = "c"
        # We will add node names manually
        ts.show_leaf_name = False
        ts.branch_vertical_margin = 30
        ts.show_scale = False

        t = self.head_node.create_equivalent_ete_tree()

        t.render(target_outputfile, w=183, units="mm", tree_style=ts)
Exemplo n.º 29
0
# remove dodgy sample
big_tree.search_nodes(name="'EBOV|EMLab-RT|IPDPFHGINSP_GUI_2015_5339||GIN|Conakry|?|MinION_LQ05|2015-04-08'")[0].delete(
    preserve_branch_length=True
)
# root the same as the MCC tree
ancestor = big_tree.get_common_ancestor(
    "'EBOV|EMLab|EM_079422|KR817187|GIN|Macenta|?||2014-03-27'",
    "'EBOV|EMLab|Gueckedou-C05|KJ660348|GIN|Gueckedou|?||2014-03-19'",
)
big_tree.set_outgroup(ancestor)
big_tree.ladderize()

ts = TreeStyle()
ts.show_leaf_name = False
# ts.show_branch_support = True
ts.scale = 100000
if mode == "small":
    ts.scale = 750000

# add legend
for each in colourDict.keys():
    ts.legend.add_face(CircleFace(radius=size[mode] / 2, color=colourDict[each]), column=0)
    ts.legend.add_face(TextFace(each, ftype="Helvetica", fsize=size[mode]), column=1)
ts.legend.add_face(CircleFace(radius=size[mode] / 2, color="#F1F1F1"), column=0)
ts.legend.add_face(TextFace("Guinea", ftype="Helvetica", fsize=size[mode]), column=1)
ts.legend.add_face(RectFace(width=size[mode], height=size[mode], bgcolor="#D3D3D3", fgcolor="#FFFFFF"), column=0)
ts.legend.add_face(TextFace("Sierra Leone", ftype="Helvetica", fsize=size[mode]), column=1)
ts.legend.add_face(
    RectFace(triangle=True, width=size[mode], height=size[mode], bgcolor="#939393", fgcolor="#FFFFFF"), column=0
)
ts.legend.add_face(TextFace("Liberia", ftype="Helvetica", fsize=size[mode]), column=1)
Exemplo n.º 30
0
							for key in  speciescolors:
								genusSpecies = key.split()
								for name in genusSpecies:
									if name in lineage:
										nst['bgcolor'] = speciescolors[key]	
										break
					leaf.img_style = nst 

	nst = NodeStyle()
	nst["size"] = 0
	nst["fgcolor"] = 'black'
	nst["hz_line_width"] = 2
	nst["vt_line_width"]= 2
	for n in t.traverse():
		if n.is_leaf() == False:
			n.img_style = nst 

	ts = TreeStyle()
	for i,ref in enumerate(colormap.keys()):
		if 'ubi' not in ref and 'HH' not in ref and 'LOMETS' not in ref:
			ts.title.add_face(TextFace(ref, fsize=12), column=0)
			ts.title.add_face( RectFace(10 , 10 , colormap[ref] , colormap[ref]), column = 1)
	#ts.mode = "c"
	#ts.arc_start = -180 #0 degrees = 3 o'clock
	ts.scale =  150 
	ts.show_leaf_name = False
	ts.show_branch_support = True
	#t.show(tree_style = ts)
	outpng = treefile+'outnocolor.png'
	t.render(outpng , tree_style = ts)
Exemplo n.º 31
0
def showTree(delimitation, scale = 500, render = False, fout = "", form = "svg", show_support = False):
    """delimitation: species_setting class"""
    tree = delimitation.root
    style0 = NodeStyle()
    style0["fgcolor"] = "#000000"
    style0["vt_line_color"] = "#0000aa"
    style0["hz_line_color"] = "#0000aa"
    style0["vt_line_width"] = 2
    style0["hz_line_width"] = 2
    style0["vt_line_type"] = 0 
    style0["hz_line_type"] = 0
    style0["size"] = 0
    
    #tree.clear_face()
    tree._faces = _FaceAreas()
    for node in tree.get_descendants():
        node.set_style(style0)
        node.img_style["size"] = 0
        node._faces = _FaceAreas()
        #node.clear_face()
    
    tree.set_style(style0)
    tree.img_style["size"] = 0
    
    style1 = NodeStyle()
    style1["fgcolor"] = "#000000"
    style1["vt_line_color"] = "#ff0000"
    style1["hz_line_color"] = "#0000aa"
    style1["vt_line_width"] = 2
    style1["hz_line_width"] = 2
    style1["vt_line_type"] = 0 
    style1["hz_line_type"] = 0
    style1["size"] = 0
    
    style2 = NodeStyle()
    style2["fgcolor"] = "#0f0f0f"
    style2["vt_line_color"] = "#ff0000"
    style2["hz_line_color"] = "#ff0000"
    style2["vt_line_width"] = 2
    style2["hz_line_width"] = 2
    style2["vt_line_type"] = 0 
    style2["hz_line_type"] = 0
    style2["size"] = 0
    
    for node in delimitation.active_nodes:
        node.set_style(style1)
        node.img_style["size"] = 0
        for des in node.get_descendants():
            des.set_style(style2)
            des.img_style["size"] = 0
    
    for node in delimitation.root.traverse(strategy='preorder'):
        if show_support and hasattr(node, "bs"):
            if node.bs == 0.0:
                node.add_face(TextFace("0", fsize = 8), column=0, position = "branch-top")
            else:
                node.add_face(TextFace("{0:.2f}".format(node.bs), fsize = 8), column=0, position = "branch-top")
    
    ts = TreeStyle()
    """scale pixels per branch length unit"""
    ts.scale =  scale 
    ts.branch_vertical_margin = 7
    if render:
        tree.render(fout+"."+form, tree_style=ts)
    else:
        tree.show(tree_style=ts)
Exemplo n.º 32
0
def draw_tree(tree, conf, outfile):
    try:
        from ete3 import (add_face_to_node, AttrFace, TextFace, TreeStyle, RectFace, CircleFace,
                             SequenceFace, random_color, SeqMotifFace)
    except ImportError as e:
        print(e)
        return

    def ly_basic(node):
        if node.is_leaf():
            node.img_style['size'] = 0
        else:
            node.img_style['size'] = 0
            node.img_style['shape'] = 'square'
            if len(MIXED_RES) > 1 and hasattr(node, "tree_seqtype"):
                if node.tree_seqtype == "nt":
                    node.img_style["bgcolor"] = "#CFE6CA"
                    ntF = TextFace("nt", fsize=6, fgcolor='#444', ftype='Helvetica')
                    add_face_to_node(ntF, node, 10, position="branch-bottom")
            if len(NPR_TREES) > 1 and hasattr(node, "tree_type"):
                node.img_style['size'] = 4
                node.img_style['fgcolor'] = "steelblue"

        node.img_style['hz_line_width'] = 1
        node.img_style['vt_line_width'] = 1

    def ly_leaf_names(node):
        if node.is_leaf():
            spF = TextFace(node.species, fsize=10, fgcolor='#444444', fstyle='italic', ftype='Helvetica')
            add_face_to_node(spF, node, column=0, position='branch-right')
            if hasattr(node, 'genename'):
                geneF = TextFace(" (%s)" %node.genename, fsize=8, fgcolor='#777777', ftype='Helvetica')
                add_face_to_node(geneF, node, column=1, position='branch-right')

    def ly_supports(node):
        if not node.is_leaf() and node.up:
            supFace = TextFace("%0.2g" %(node.support), fsize=7, fgcolor='indianred')
            add_face_to_node(supFace, node, column=0, position='branch-top')

    def ly_tax_labels(node):
        if node.is_leaf():
            c = LABEL_START_COL
            largest = 0
            for tname in TRACKED_CLADES:
                if hasattr(node, "named_lineage") and tname in node.named_lineage:
                    linF = TextFace(tname, fsize=10, fgcolor='white')
                    linF.margin_left = 3
                    linF.margin_right = 2
                    linF.background.color = lin2color[tname]
                    add_face_to_node(linF, node, c, position='aligned')
                    c += 1

            for n in range(c, len(TRACKED_CLADES)):
                add_face_to_node(TextFace('', fsize=10, fgcolor='slategrey'), node, c, position='aligned')
                c+=1

    def ly_full_alg(node):
        pass

    def ly_block_alg(node):
        if node.is_leaf():
            if 'sequence' in node.features:
                seqFace = SeqMotifFace(node.sequence, [])
                # [10, 100, "[]", None, 10, "black", "rgradient:blue", "arial|8|white|domain Name"],
                motifs = []
                last_lt = None
                for c, lt in enumerate(node.sequence):
                    if lt != '-':
                        if last_lt is None:
                            last_lt = c
                        if c+1 == len(node.sequence):
                            start, end = last_lt, c
                            motifs.append([start, end, "()", 0, 12, "slategrey", "slategrey", None])
                            last_lt = None
                    elif lt == '-':
                        if last_lt is not None:
                            start, end = last_lt, c-1
                            motifs.append([start, end, "()", 0, 12, "grey", "slategrey", None])
                            last_lt = None

                seqFace = SeqMotifFace(node.sequence, motifs,
                                       intermotif_format="line",
                                       seqtail_format="line", scale_factor=ALG_SCALE)
                add_face_to_node(seqFace, node, ALG_START_COL, aligned=True)


    TRACKED_CLADES = ["Eukaryota", "Viridiplantae",  "Fungi",
                      "Alveolata", "Metazoa", "Stramenopiles", "Rhodophyta",
                      "Amoebozoa", "Crypthophyta", "Bacteria",
                      "Alphaproteobacteria", "Betaproteobacteria", "Cyanobacteria",
                      "Gammaproteobacteria",]

    # ["Opisthokonta",  "Apicomplexa"]

    colors = random_color(num=len(TRACKED_CLADES), s=0.45)
    lin2color = dict([(ln, colors[i]) for i, ln in enumerate(TRACKED_CLADES)])

    NAME_FACE = AttrFace('name', fsize=10, fgcolor='#444444')

    LABEL_START_COL = 10
    ALG_START_COL = 40
    ts = TreeStyle()
    ts.draw_aligned_faces_as_table = False
    ts.draw_guiding_lines = False
    ts.show_leaf_name = False
    ts.show_branch_support = False
    ts.scale = 160

    ts.layout_fn = [ly_basic, ly_leaf_names, ly_supports, ly_tax_labels]

    MIXED_RES = set()
    MAX_SEQ_LEN = 0
    NPR_TREES = []
    for n in tree.traverse():
        if hasattr(n, "tree_seqtype"):
            MIXED_RES.add(n.tree_seqtype)
        if hasattr(n, "tree_type"):
            NPR_TREES.append(n.tree_type)
        seq = getattr(n, "sequence", "")
        MAX_SEQ_LEN = max(len(seq), MAX_SEQ_LEN)

    if MAX_SEQ_LEN:
        ALG_SCALE = min(1, 1000./MAX_SEQ_LEN)
        ts.layout_fn.append(ly_block_alg)

    if len(NPR_TREES) > 1:
        rF = RectFace(4, 4, "steelblue", "steelblue")
        rF.margin_right = 10
        rF.margin_left = 10
        ts.legend.add_face(rF, 0)
        ts.legend.add_face(TextFace(" NPR node"), 1)
        ts.legend_position = 3

    if len(MIXED_RES) > 1:
        rF = RectFace(20, 20, "#CFE6CA", "#CFE6CA")
        rF.margin_right = 10
        rF.margin_left = 10
        ts.legend.add_face(rF, 0)
        ts.legend.add_face(TextFace(" Nucleotide based alignment"), 1)
        ts.legend_position = 3


    try:
        tree.set_species_naming_function(spname)
        annotate_tree_with_ncbi(tree)
        a = tree.search_nodes(species='Dictyostelium discoideum')[0]
        b = tree.search_nodes(species='Chondrus crispus')[0]
        #out = tree.get_common_ancestor([a, b])
        #out = tree.search_nodes(species='Haemophilus parahaemolyticus')[0].up
        tree.set_outgroup(out)
        tree.swap_children()
    except Exception:
        pass

    tree.render(outfile, tree_style=ts, w=170, units='mm', dpi=150)
    tree.render(outfile+'.svg', tree_style=ts, w=170, units='mm', dpi=150)
    tree.render(outfile+'.pdf', tree_style=ts, w=170, units='mm', dpi=150)
Exemplo n.º 33
0
#figure IES loss
from __future__ import print_function
from ete3 import Tree, NodeStyle, TreeStyle
from pyies.userOptions import basePath
import os.path
import string

geneFamily = '4137'
analysis = '2'
phyldogResultsPath = "analysis/phyldogT" + analysis + "/results"
treeF = os.path.join(basePath, 'analysis', 'phyldogT' + analysis, 'results', geneFamily + ".ReconciledTree"
)
alnF = os.path.join(basePath, 'analysis', 'msas', 'filtered', 'cluster.' + geneFamily + '.nucl.fa')
t = Tree(treeF)
ts = TreeStyle()
ts.scale = 500
nstyle = NodeStyle()
nstyle["size"] = 0
for n in t.traverse():
   n.set_style(nstyle)

#seqs = SeqGroup(sequences = alnF, format = "fasta")

# for leaf in t:
#     geneId = leaf.name
#     seq = seqs.get_seq(geneId)
#     seq = seq.translate(None, string.ascii_lowercase) # keep only CDS
#     #iesmotif = [[1, len(seq), "line", 2, 5, None, None, None]]
#     #seqFace = SeqMotifFace(seq = seq, gap_format = "blank", seq_format = "line")
#     seqFace = SequenceFace(seq, seqtype = 'dna')
#     leaf.add_face(seqFace, 0, "aligned")
Exemplo n.º 34
0
This script plots trees of our wikipedia data.

"""

from ete3 import Tree, TreeStyle, NodeStyle

with open('/Users/diyadas/cdips/Topic-Ontology/SimpleWikiTree_u.txt','r') as f:
    treestr = f.readlines()[0]    
    

t = Tree( treestr.rstrip(),format=8)

circular_style = TreeStyle()
circular_style.mode = "c" # draw tree in circular mode
circular_style.scale = 120
circular_style.show_leaf_name = True
circular_style.show_branch_length = True
circular_style.show_branch_support = True
t.render("mytree.png", tree_style=circular_style)


nstyle = NodeStyle()
nstyle["hz_line_width"] = 3
nstyle["vt_line_width"] = 3

# Applies the same static style to all nodes in the tree. Note that,
# if "nstyle" is modified, changes will affect to all nodes
for n in t.traverse():
   n.set_style(nstyle)
Exemplo n.º 35
0
def get_example_tree():
    t = Tree()
    t.populate(10)

    # Margins, alignment, border, background and opacity can now be set for any face
    rs1 = faces.TextFace("branch-right\nmargins&borders",
                         fsize=12, fgcolor="#009000")
    rs1.margin_top = 10
    rs1.margin_bottom = 50
    rs1.margin_left = 40
    rs1.margin_right = 40
    rs1.border.width = 1
    rs1.background.color = "lightgreen"
    rs1.inner_border.width = 0
    rs1.inner_border.line_style = 1
    rs1.inner_border.color= "red"
    rs1.opacity = 0.6
    rs1.hz_align = 2 # 0 left, 1 center, 2 right
    rs1.vt_align = 1 # 0 left, 1 center, 2 right

    br1 = faces.TextFace("branch-right1", fsize=12, fgcolor="#009000")
    br2 = faces.TextFace("branch-right3", fsize=12, fgcolor="#009000")

    # New face positions (branch-top and branch-bottom)
    bb = faces.TextFace("branch-bottom 1", fsize=8, fgcolor="#909000")
    bb2 = faces.TextFace("branch-bottom 2", fsize=8, fgcolor="#909000")
    bt = faces.TextFace("branch-top 1", fsize=6, fgcolor="#099000")

    # And faces can also be used as headers or foot notes of aligned
    # columns
    t1 = faces.TextFace("Header Face", fsize=12, fgcolor="#aa0000")
    t2 = faces.TextFace("Footer Face", fsize=12, fgcolor="#0000aa")

    # Attribute faces can now contain prefix and suffix fixed text
    aligned = faces.AttrFace("name", fsize=12, fgcolor="RoyalBlue",
                             text_prefix="Aligned (", text_suffix=")")
    # horizontal and vertical alignment per face
    aligned.hz_align = 1 # 0 left, 1 center, 2 right
    aligned.vt_align = 1

    # Node style handling is no longer limited to layout functions. You
    # can now create fixed node styles and use them many times, save them
    # or even add them to nodes before drawing (this allows to save and
    # reproduce an tree image design)
    style = NodeStyle()
    style["fgcolor"] = "Gold"
    style["shape"] = "square"
    style["size"] = 15
    style["vt_line_color"] = "#ff0000"
    t.set_style(style)
    # add a face to the style. This face will be render in any node
    # associated to the style.
    fixed = faces.TextFace("FIXED branch-right", fsize=11, fgcolor="blue")
    t.add_face(fixed, column=1, position="branch-right")
    # Bind the precomputed style to the root node

    # ETE 2.1 has now support for general image properties
    ts = TreeStyle()

    # You can add faces to the tree image (without any node
    # associated). They will be used as headers and foot notes of the
    # aligned columns (aligned faces)
    ts.aligned_header.add_face(t1, column = 0)
    ts.aligned_header.add_face(t1, 1)
    ts.aligned_header.add_face(t1, 2)
    ts.aligned_header.add_face(t1, 3)
    t1.hz_align = 1 # 0 left, 1 center, 2 right
    t1.border.width = 1

    ts.aligned_foot.add_face(t2, column = 0)
    ts.aligned_foot.add_face(t2, 1)
    ts.aligned_foot.add_face(t2, 2)
    ts.aligned_foot.add_face(t2, 3)
    t2.hz_align = 1

    # Set tree image style. Note that aligned header and foot is only
    # visible in "rect" mode.

    ts.mode =  "r"
    ts.scale = 10
    for node in t.traverse():
        # If node is a leaf, add the nodes name and a its scientific
        # name
        if node.is_leaf():
            node.add_face(aligned, column=0, position="aligned")
            node.add_face(aligned, column=1, position="aligned")
            node.add_face(aligned, column=3, position="aligned")
        else:
            node.add_face(bt, column=0, position="branch-top")
            node.add_face(bb, column=0, position="branch-bottom")
            node.add_face(bb2, column=0, position="branch-bottom")
            node.add_face(br1, column=0, position="branch-right")
            node.add_face(rs1, column=0, position="branch-right")
            node.add_face(br2, column=0, position="branch-right")

    return t, ts
Exemplo n.º 36
0
def format( tree , genedict , detection , includenames , filename , speciescolors = None):
	print 'final output...'
	red = Color('red')
	blue = Color('blue')
	colorvec = list(red.range_to(blue, len(genedict.keys())))
	colormap = {}
	columnmap = {}
	for i,ref in enumerate(genedict):
		if ref not in detection:	
			columnmap[ref] = 3
			if 'hybrid' in ref.lower():
				columnmap[ref] = 0
			if 'eff' in ref.lower():
				columnmap[ref] = 1
			if 'hap' in ref.lower():
				columnmap[ref] = 2
			colormap[ref] = colorvec[i].hex
	for i,ref in enumerate(detection):
		columnmap[ref] = 3 + i
		colormap[ref] = colorvec[i].hex 

	print columnmap
	print colormap

	circledict = {}
	for n in t.traverse():
		
		nst = NodeStyle()
		nst["size"] = 0
		nst["fgcolor"] = 'black'
		nst["hz_line_width"] = 4
		nst["vt_line_width"]= 4
		nst.show_name = False
		if n.is_leaf():
			if speciescolors != None and n.name in speciescolors:
				nst["bgcolor"] = colors[n.name]
			nst.show_name = True			
			n.add_face( AttrFace(attr = 'name', ftype='Helvetica', fgcolor='black', fsize =18 ,fstyle = 'normal'   ), column =0 )
			refs = json.loads(n.refs)
			for ref in genedict:
				if ref in refs and ref in detection:
					n.add_face( CircleFace ( 10 , colormap[ref]), column =  2 + columnmap[ref] )
					n.img_style = nst
				if ref in refs and ref not in detection:
					n.add_face( RectFace ( 20 , 20 , colormap[ref], colormap[ref] ), column =  2 + columnmap[ref] )
					n.img_style = nst
				if ref not in refs and ref not in detection:
					n.add_face( RectFace ( 20 , 20 , colormap[ref], 'white' ), column =  2 + columnmap[ref] )
					n.img_style = nst
			###color by species
			if n.name in speciescolors:
				nst['bgcolor'] = speciescolors[n.name]
		else:
			if n.name.strip() in includenames:
				n.add_face( AttrFace(attr = 'name', ftype='Helvetica', fgcolor='black', fsize =20 ,fstyle = 'normal'   ), column =0 )
				nst.size = 2
				n.img_style = nst
			else:
				nst.size = 0
				n.img_style = nst 
	ts = TreeStyle()
	for i,ref in enumerate(colormap.keys()):
		if 'ubi' not in ref:
			ts.title.add_face(TextFace(ref, fsize=12), column=0)
			ts.title.add_face( RectFace(10 , 10 , colormap[ref] , colormap[ref]), column = 1)
	ts.show_leaf_name=False 

	"""ts.mode = "c"
				ts.arc_start = 270
				ts.arc_span = 359
				ts.root_opening_factor = 1
			"""
	ts.scale =  190
	
	t.show(tree_style = ts)
	t.render(filename + ".png", tree_style = ts)
	t.render( filename +".svg" , tree_style = ts)
        F = faces.TextFace(mynode.name,fsize=20)
        faces.add_face_to_node(F,mynode,0,position="aligned")

#Plot Pie Chart	
ts = TreeStyle()
ts.show_leaf_name = False

ts.layout_fn = phyparts_pie_layout
nstyle = NodeStyle()
nstyle["size"] = 0
for n in plot_tree.traverse():
	n.set_style(nstyle)
	n.img_style["vt_line_width"] = 0

ts.draw_guiding_lines = True
ts.guiding_lines_color = "black"
ts.guiding_lines_type = 0
ts.scale = 30
ts.branch_vertical_margin = 10
plot_tree.convert_to_ultrametric()
plot_tree.ladderize(direction=1)    
my_svg = plot_tree.render(args.svg_name,tree_style=ts,w=595,dpi=300)

if args.show_nodes:
	node_style = TreeStyle()
	node_style.show_leaf_name=False
	node_style.layout_fn = node_text_layout
	plot_tree.show(tree_style=node_style)

     
    
Exemplo n.º 38
0
    nstyle["fgcolor"] = "yellow"
    nstyle["size"] = 10
    n.set_style(nstyle)

my_tree.img_style["size"] = 20
my_tree.img_style["fgcolor"] = "green"

code_name = {
    "54263": "Ichthyosaura alpestris",
    "8324": "Lissotriton vulgaris",
    "8323": "Triturus cristatus",
    "8327": "Triturus dobrogicus",
    "8325": "Triturus karelinii ",
    "57571": "Salamandra salamandra ",
    "323754": "Lissotriton montandoni"
}


def mylayout(node):

    if node.is_leaf():
        longNameFace = faces.TextFace(code_name[node.name],
                                      fsize=15,
                                      fgcolor="green")
        faces.add_face_to_node(longNameFace, node, column=0)


ts = TreeStyle()
ts.layout_fn = mylayout
ts.scale = 100
my_tree.show(tree_style=ts)
Exemplo n.º 39
0
def testTreesMinimal(scenarios, traits, mapper):
    def rgb2hex(r, g, b):
        hex = "#{:02x}{:02x}{:02x}".format(r, g, b)
        return hex

    ### Draw test trees. This is a modified version of the test routine in pcoc_num_tree.py, stuffed in a for loop
    for cutoff in sorted(scenarios.keys()):
        tree = init_tree(args.tree)
        # not mucking with additive trees yet; ultrametrize the tree and normalize to length 1
        tree.convert_to_ultrametric(tree_length=1)

        # read scenario into a dict
        manual_mode_nodes = {"T": [], "C": []}
        p_events = scenarios[cutoff].strip().split("/")
        for e in p_events:
            l_e = map(int, e.split(","))
            manual_mode_nodes["T"].append(l_e[0])
            manual_mode_nodes["C"].extend(l_e[1:])

        ts = TreeStyle()
        # ts.allow_face_overlap = True
        ts.show_leaf_name = False
        ts.rotation = 270
        ts.complete_branch_lines_when_necessary = False
        # ts.optimal_scale_level = "full"
        ts.scale = 800

        for n in tree.traverse():

            # default NodeStyle
            nstyle = NodeStyle()
            nstyle["size"] = 0
            nstyle["hz_line_color"] = "none"
            nstyle["vt_line_color"] = "none"
            nstyle["hz_line_width"] = 3
            nstyle["vt_line_width"] = 3

            # colored faces
            chroma = rgb2hex(*[
                int(val)
                for val in mapper(traits[n.ND], gamma=0.8, scaleMax=255)
            ])  # setup for wl2RGB
            nf = CircleFace(radius=10,
                            color=chroma,
                            style='circle',
                            label=None)

            # scenario-dependent features
            if manual_mode_nodes:
                # if transition node
                if n.ND in manual_mode_nodes["T"]:
                    #nstyle["hz_line_color"] = "orange"
                    nf.inner_border.width = 4
                    nf.inner_border.color = 'red'
                # if convergent node
                elif n.ND in manual_mode_nodes["C"]:
                    #nstyle["hz_line_color"] = "violet"
                    nf.inner_border.width = 4
                    nf.inner_border.color = 'white'
                # if ancestral
                else:
                    nstyle["hz_line_color"] = "none"

                n.set_style(nstyle)
                n.add_face(nf, column=0, position='branch-top')

        # limiting number of digits
        outFile = args.output + "/test_trees/" + str(cutoff).replace(
            '.', '_')[:np.min([5, len(str(cutoff))])] + ".pdf"
        tree.render(outFile, tree_style=ts)
        print >> sys.stderr, outFile
Exemplo n.º 40
0
# for key in prune_count.keys():
#     # node_weight = ln(prune_count[key])
#     # node_weight = ln(n_children)
#     # print(node_weight,n_children)
#     # node = lookup[key]
#     node.add_features(weight=random.randint(50))

for n in t.traverse():
    n.add_face(TextFace(n.name, fsize = 16), column=0, position="branch-bottom")
    # n.add_features(weight=random.randint(0,20))

t.prune(prune_list)
# Create an empty TreeStyle
ts = TreeStyle()
# Set our custom layout function
ts.layout_fn = layout
# Draw a tree
# ts.mode = "c"  # this makes it circular
# False need to add node names manually
ts.show_leaf_name = False
ts.scale = 120

# Show branch data
ts.show_branch_length = False
ts.show_branch_support = True


# print (t.get_ascii(show_internal=True))

t.show(tree_style=ts)
Exemplo n.º 41
0
                    default="pies.svg")

args = parser.parse_args()
plot_tree, subtrees_dict, subtrees_topids = get_phyparts_nodes(
    args.species_tree, args.phyparts_root)

concord_dict, conflict_dict = get_concord_and_conflict(args.phyparts_root,
                                                       subtrees_dict,
                                                       subtrees_topids)
phyparts_dist, phyparts_pies = get_pie_chart_data(args.phyparts_root,
                                                  args.num_genes, concord_dict,
                                                  conflict_dict)

#Plot Pie Chart
ts = TreeStyle()
ts.show_leaf_name = False

ts.layout_fn = phyparts_pie_layout
nstyle = NodeStyle()
nstyle["size"] = 0
for n in plot_tree.traverse():
    n.set_style(nstyle)
    n.img_style["vt_line_width"] = 0

ts.draw_guiding_lines = True
ts.guiding_lines_color = "black"
ts.guiding_lines_type = 0
ts.scale = 30
ts.branch_vertical_margin = 10
plot_tree.convert_to_ultrametric()
my_svg = plot_tree.render(args.svg_name, tree_style=ts, w=595)
Exemplo n.º 42
0
import random
from ete3 import Tree, TreeStyle, NodeStyle, faces, AttrFace, TreeFace

# Tree Style used to render small trees used as leaf faces
small_ts = TreeStyle()
small_ts.show_leaf_name = True
small_ts.scale = 10

def layout(node):
    if node.is_leaf():
        # Add node name to laef nodes
        N = AttrFace("name", fsize=14, fgcolor="black")
        faces.add_face_to_node(N, node, 0)

        t = Tree()
        t.populate(10)

        T = TreeFace(t, small_ts)
        # Let's make the sphere transparent
        T.opacity = 0.8
        # And place as a float face over the tree
        faces.add_face_to_node(T, node, 1, position="aligned")

def get_example_tree():
    # Random tree
    t = Tree()
    t.populate(20, random_branches=True)

    # Some random features in all nodes
    for n in t.traverse():
        n.add_features(weight=random.randint(0, 50))