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
Ejemplo n.º 2
0
def plot_variance(tree,path,aa):
    #cycle through the nodes and add a variance attribute to each node postorder, so we start with the
#children that have W attribute and recursively create this attribute as we are traversing through the tree
    all_means=[]
    for node in tree.traverse(strategy="postorder"):
        if not(node.is_leaf()):
            children=node.children
            variance=[]
            for i in range(len(children)):
                aa_feat = getattr(children[i], aa)
                variance.append(aa_feat)
                # variance requires at least two data points, in case there is only one sequence or node
                if len(variance)==1:
                    node.add_feature(aa+"_var",0)
                    node.add_feature(aa+"", np.mean(variance))
                else:
                    node.add_feature(aa+"_var",statistics.variance(variance))
                    node.add_feature(aa+"", np.mean(variance))
            all_means.append(getattr(node, aa+""))
    #plot without sequences (create new tree with cut leave and )
    new_tree=tree.copy()
    maximum=max(all_means)
    minimum=min(all_means)
    #for node in new_tree.traverse(strategy="preorder"):
    ts = TreeStyle()
    ts.mode="c"
    for node in new_tree.traverse():
        if node.is_leaf():
            node.detach()
        else:
            nstyle = NodeStyle()
            nstyle["bgcolor"]="#"+rgb_to_hex(red_gradient(minimum,maximum,(getattr(node, aa+""))))
            node.add_face(TextFace(getattr(node,aa+"")), column=0, position = "branch-right")
            node.set_style(nstyle)
    new_tree.render(path, w=1400, units="mm", tree_style=ts)
Ejemplo n.º 3
0
def get_example_tree():

    # Set dashed blue lines in all leaves
    nst1 = NodeStyle()
    nst1["bgcolor"] = "LightSteelBlue"
    nst2 = NodeStyle()
    nst2["bgcolor"] = "Moccasin"
    nst3 = NodeStyle()
    nst3["bgcolor"] = "DarkSeaGreen"
    nst4 = NodeStyle()
    nst4["bgcolor"] = "Khaki"


    t = Tree("((((a1,a2),a3), ((b1,b2),(b3,b4))), ((c1,c2),c3));")
    for n in t.traverse():
        n.dist = 0

    n1 = t.get_common_ancestor("a1", "a2", "a3")
    n1.set_style(nst1)
    n2 = t.get_common_ancestor("b1", "b2", "b3", "b4")
    n2.set_style(nst2)
    n3 = t.get_common_ancestor("c1", "c2", "c3")
    n3.set_style(nst3)
    n4 = t.get_common_ancestor("b3", "b4")
    n4.set_style(nst4)
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.show_leaf_name = False

    ts.mode = "c"
    ts.root_opening_factor = 1
    return t, ts
Ejemplo n.º 4
0
def get_example_tree():

    # Set dashed blue lines in all leaves
    nst1 = NodeStyle()
    nst1["bgcolor"] = "LightSteelBlue"
    nst2 = NodeStyle()
    nst2["bgcolor"] = "Moccasin"
    nst3 = NodeStyle()
    nst3["bgcolor"] = "DarkSeaGreen"
    nst4 = NodeStyle()
    nst4["bgcolor"] = "Khaki"

    t = Tree("((((a1,a2),a3), ((b1,b2),(b3,b4))), ((c1,c2),c3));")
    for n in t.traverse():
        n.dist = 0

    n1 = t.get_common_ancestor("a1", "a2", "a3")
    n1.set_style(nst1)
    n2 = t.get_common_ancestor("b1", "b2", "b3", "b4")
    n2.set_style(nst2)
    n3 = t.get_common_ancestor("c1", "c2", "c3")
    n3.set_style(nst3)
    n4 = t.get_common_ancestor("b3", "b4")
    n4.set_style(nst4)
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.show_leaf_name = False

    ts.mode = "c"
    ts.root_opening_factor = 1
    return t, ts
Ejemplo n.º 5
0
def get_example_tree():

    # Set dashed blue lines in all leaves
    nst1 = NodeStyle()
    nst1["bgcolor"] = "LightSteelBlue"
    nst2 = NodeStyle()
    nst2["bgcolor"] = "Moccasin"
    nst3 = NodeStyle()
    nst3["bgcolor"] = "DarkSeaGreen"
    nst4 = NodeStyle()
    nst4["bgcolor"] = "Khaki"


    t = Tree("( 🌲,( 🥑,(( 🌷, ( 🌴, ( 🍌, ( 🍍, ( 🌽, ( 🎋, 🌾 )))))),(( 🍇, ((( 🥜, ☘️), ((( 🌹, 🍓 ), (( 🍎, 🍐 ), ( 🍑, (🌸, 🍒) ))), ( 🌰, ( 🎃, ( 🍉, ( 🥒, 🍈)))))), (( 🌺, 🥦 ), (( 🍊, 🍋 ), ( 🍁, 🥭))))),( 🌵, ( 🥝, (( 🍠, ( 🌶️, (🍆, ( 🥔, 🍅)))), ( 🥕,( 🥬, ( 🌻, 🌼)))))))));")
    for n in t.traverse():
        n.dist = 0

    n1 = t.get_common_ancestor("a1", "a2", "a3")
    n1.set_style(nst1)
    n2 = t.get_common_ancestor("b1", "b2", "b3", "b4")
    n2.set_style(nst2)
    n3 = t.get_common_ancestor("c1", "c2", "c3")
    n3.set_style(nst3)
    n4 = t.get_common_ancestor("b3", "b4")
    n4.set_style(nst4)
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.show_leaf_name = False

    ts.mode = "c"
    ts.root_opening_factor = 1
    return t, ts
Ejemplo n.º 6
0
def buble_tree():
	built = False
	while not built:
		try:
    
			# Random tree
			t = ncbi.get_topology(idtaxa, intermediate_nodes=True)

			# Some random features in all nodes 
			for node,weigh in zip(t,weighs):

				node.add_features(weight=weigh)

			# Create an empty TreeStyle
			ts = TreeStyle()

			# Set our custom layout function
			ts.layout_fn = layout

			# Draw a tree
			ts.mode = "c"

			# We will add node names manually
			ts.show_leaf_name = True
			# Show branch data
			ts.show_branch_length = True
			ts.show_branch_support = True
				
			return t, ts
			built = True
		except KeyError as e:
			taxid_not_found = int(e.args[0])
			idtaxa.remove(taxid_not_found)
			print("the following IDs were not found in NCBI taxonomy database:" + str(taxid_not_found))
			pass
Ejemplo n.º 7
0
def plot_trees(tree_fn, output_fn):
    """ Plot a tree """
    os.environ['QT_QPA_PLATFORM'] = 'offscreen'
    style = TreeStyle()
    style.mode = "c"
    style.show_leaf_name = True

    # Set Node Styles
    rstyle = NodeStyle()
    rstyle["shape"] = "sphere"
    rstyle["size"] = 15
    rstyle["fgcolor"] = "blue"
    nstyle = NodeStyle()
    nstyle["shape"] = "sphere"
    nstyle["size"] = 0
    sstyle = NodeStyle()
    sstyle["shape"] = "sphere"
    sstyle["size"] = 15
    sstyle["fgcolor"] = "red"

    #Create the tree object
    ct = Tree(tree_fn)

    for n in ct.traverse():
        if n.name == "Wuhan" or n.name == "Wuhan|402124":
            n.set_style(rstyle)
        elif n.name == "Sample":
            n.set_style(sstyle)
        elif not n.is_leaf():
            n.set_style(nstyle)

    #Draw the tree and write to a file
    ct.render(output_fn, tree_style=style)
Ejemplo n.º 8
0
def get_example_tree(tree, color_dict=None, annot_dict=None, col=None):

    used_colours = set()
    for n in tree.traverse():
        if n.is_leaf():

            if n.name in annot_dict:

                n.img_style["bgcolor"] = color_dict[annot_dict[n.name]]

                used_colours.add(annot_dict[n.name])

            ts = TreeStyle()
            ts.layout_fn = layout
            ts.show_leaf_name = False
            ts.mode = "c"
            # ts.arc_start = -180  # 0 degrees = 3 o'clock
            # ts.arc_span = 180
            # ts.root_opening_factor = 1

            # print (used_colours)

            for k,v in color_dict.items():
                # Check that the specific colour was actually present in the tree we're annotating
                if k in used_colours:
                    ts.legend.add_face(CircleFace(100, v), column=0)
                    ts.legend.add_face(TextFace(k, fsize=50), column=1)

            # Add title
            ts.title.add_face(TextFace("Colouring tips on " + col, fsize=100), column=0)

    return tree, ts
Ejemplo n.º 9
0
def show_tree(experiment_folder):
    model = MDPD.Hierachical_MDPD(1)
    model.load(os.path.join(experiment_folder, 'model.p'))

    width, depth = model.width, model.depth

    root = Tree()

    cache = [(0, root)]

    for i in range(depth + 1):
        foo = []

        for idx, node in cache:
            paren = int((idx - 1) / width)
            kid = idx - paren * width
            face = faces.ImgFace(os.path.join(experiment_folder, 'images', '{}_{}_{}.png'.format(idx, paren, kid)))
            node.add_face(face, 0)

            if i < depth:
                for k in range(width):
                    foo.append((idx * width + k + 1, node.add_child()))

        cache = foo

    ts = TreeStyle()
    ts.mode = "c"

    root.render(os.path.join(experiment_folder, 'images', 'tree_plot.png'), tree_style=ts)
    return root
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))

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    ts.layout_fn = layout

    # Draw a tree
    ts.mode = "c"

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return t, ts
Ejemplo n.º 11
0
def get_example_tree():
    # Random tree
    t = Tree()
    t = Tree(
        "(((yessefk),(ad, tuɣal),((teqbaylit),(d,(tutlayt,tunṣibt)))),(((win,yebɣan), (taqbaylit)),(((ad,yissin, (tira,-s))))),(((win,yebɣan), (taqbaylit)),(((yugar) , (ucerrig)), (tafawet))));"
    )

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

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    ts.layout_fn = layout

    # Draw a tree
    ts.mode = "c"

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return t, ts
Ejemplo n.º 12
0
def get_example_tree():
    # Random tree
    t = Tree(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))

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    ts.layout_fn = layout

    # Draw a tree
    ts.mode = "c"

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return t, ts
Ejemplo n.º 13
0
def get_example_tree():
    t = Tree()
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.mode = "r"
    ts.show_leaf_name = False
    t.populate(10)
    return t, ts
Ejemplo n.º 14
0
def get_example_tree():
    t = Tree()
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.mode = "r"
    ts.show_leaf_name = False
    t.populate(10)
    return t, ts
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
Archivo: tree.py Proyecto: 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)
Ejemplo n.º 17
0
def get_example_tree():
    t = Tree()
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.mode = "c"
    ts.show_leaf_name = True
    ts.min_leaf_separation = 15
    t.populate(100)
    return t, ts
Ejemplo n.º 18
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)
Ejemplo n.º 19
0
def get_example_tree():
    t = Tree()
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.mode = "c"
    ts.show_leaf_name = True
    ts.min_leaf_separation = 15
    t.populate(100)
    return t, ts
Ejemplo n.º 20
0
def create_tree_style():
    ts = TreeStyle()
    ts.title.add_face(TextFace("Randomly pruned data", fsize=20), column=0)
    ts.layout_fn = remove_blue_dots
    ts.mode = "c"
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    return ts
def tree_style() -> TreeStyle:
    style = TreeStyle()
    style.mode = "c"  # draw tree in circular mode
    # style.scale = 20
    # style.branch_vertical_margin = 15
    style.root_opening_factor = 0.04
    style.show_leaf_name = False
    style.show_branch_length = False
    style.show_branch_support = False
    return style
Ejemplo n.º 22
0
def balanceplot(balances, tree,
                layout=None,
                mode='c'):
    """ Plots balances on tree.

    Parameters
    ----------
    balances : np.array
        A vector of internal nodes and their associated real-valued balances.
        The order of the balances will be assumed to be in level order.
    tree : skbio.TreeNode
        A strictly bifurcating tree defining a hierarchical relationship
        between all of the features within `table`.
    layout : function, optional
        A layout for formatting the tree visualization. Must take a
        `ete.tree` as a parameter.
    mode : str
        Type of display to show the tree. ('c': circular, 'r': rectangular).

    Note
    ----
    The `tree` is assumed to strictly bifurcating and
    whose tips match `balances.

    See Also
    --------
    TreeNode.levelorder
    """
    # The names aren't preserved - let's pray that the topology is consistent.
    ete_tree = Tree(str(tree))
    # Some random features in all nodes
    i = 0
    for n in ete_tree.traverse():
        if not n.is_leaf():
            n.add_features(weight=balances[-i])
            i += 1

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    if layout is None:
        ts.layout_fn = default_layout
    else:
        ts.layout_fn = layout
    # Draw a tree
    ts.mode = mode

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return ete_tree, ts
Ejemplo n.º 23
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
Ejemplo n.º 24
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
Ejemplo n.º 25
0
def _get_motif_tree(tree, data, circle=True, vmin=None, vmax=None):
    try:
        from ete3 import Tree, NodeStyle, TreeStyle
    except ImportError:
        print("Please install ete3 to use this functionality")
        sys.exit(1)

    t = Tree(tree)

    # Determine cutoff for color scale
    if not (vmin and vmax):
        for i in range(90, 101):
            minmax = np.percentile(data.values, i)
            if minmax > 0:
                break
    if not vmin:
        vmin = -minmax
    if not vmax:
        vmax = minmax

    norm = Normalize(vmin=vmin, vmax=vmax, clip=True)
    mapper = cm.ScalarMappable(norm=norm, cmap="RdBu_r")

    m = 25 / data.values.max()

    for node in t.traverse("levelorder"):
        val = data[[l.name for l in node.get_leaves()]].values.mean()
        style = NodeStyle()
        style["size"] = 0

        style["hz_line_color"] = to_hex(mapper.to_rgba(val))
        style["vt_line_color"] = to_hex(mapper.to_rgba(val))

        v = max(np.abs(m * val), 5)
        style["vt_line_width"] = v
        style["hz_line_width"] = v

        node.set_style(style)

    ts = TreeStyle()

    ts.layout_fn = _tree_layout
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.branch_vertical_margin = 10

    if circle:
        ts.mode = "c"
        ts.arc_start = 180  # 0 degrees = 3 o'clock
        ts.arc_span = 180

    return t, ts
Ejemplo n.º 26
0
def _get_motif_tree(tree, data, circle=True, vmin=None, vmax=None):
    try:
        from ete3 import Tree, NodeStyle, TreeStyle
    except ImportError:
        print("Please install ete3 to use this functionality")
        sys.exit(1)

    t = Tree(tree)
    
    # Determine cutoff for color scale
    if not(vmin and vmax):
        for i in range(90, 101):
            minmax = np.percentile(data.values, i)
            if minmax > 0:
                break
    if not vmin:
        vmin = -minmax
    if not vmax:
        vmax = minmax
    
    norm = Normalize(vmin=vmin, vmax=vmax, clip=True)
    mapper = cm.ScalarMappable(norm=norm, cmap="RdBu_r")
    
    m = 25 / data.values.max()
    
    for node in t.traverse("levelorder"):
        val = data[[l.name for l in node.get_leaves()]].values.mean()
        style = NodeStyle()
        style["size"] = 0
        
        style["hz_line_color"] = to_hex(mapper.to_rgba(val))
        style["vt_line_color"] = to_hex(mapper.to_rgba(val))
        
        v = max(np.abs(m * val), 5)
        style["vt_line_width"] = v
        style["hz_line_width"] = v

        node.set_style(style)
    
    ts = TreeStyle()

    ts.layout_fn = _tree_layout
    ts.show_leaf_name= False
    ts.show_scale = False
    ts.branch_vertical_margin = 10

    if circle:
        ts.mode = "c"
        ts.arc_start = 180 # 0 degrees = 3 o'clock
        ts.arc_span = 180
    
    return t, 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)
Ejemplo n.º 28
0
def get_style():
	# Create an empty TreeStyle
    ts = TreeStyle()
    # Set our custom layout function
    ts.layout_fn = layout
    # Draw a tree
    ts.mode = "c"
    # We will add node names manually
    ts.show_leaf_name = True
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True
    return ts
Ejemplo n.º 29
0
def plot_tree(tree, save=False, path=''):

    # style
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.mode = "c"
    ts.arc_start = -180
    ts.arc_span = 360

    #plot tree
    if save:
        tree.render(file_name=path, tree_style=ts)

    tree.show(tree_style=ts)
Ejemplo n.º 30
0
def plot_taxids(taxids_list, tree_png, tree_nw, tax_db=None):
    if tax_db is not None:
        ncbi = NCBITaxa(dbfile=tax_db)
    else:
        ncbi=NCBITaxa()

    tree = ncbi.get_topology(taxids_list)
    ts = TreeStyle()
    ncbi.annotate_tree(tree, taxid_attr="sci_name")
    ts.show_leaf_name = False
    ts.mode = "c"
    ts.layout_fn = layout
    tree.render(tree_png, tree_style=ts)
    tree.write(format=1, outfile=tree_nw)
Ejemplo n.º 31
0
def set_default_TreeStyle(tree, draw_nodes):
    ts = TreeStyle()
    ts.mode = "c"
    ts.arc_start = -180
    ts.arc_span = 180
    ts.root_opening_factor = 1
    ts.show_branch_length = False
    ts.show_branch_support = True
    ts.force_topology = False
    ts.show_leaf_name = False
    ts.min_leaf_separation = 10
    ts.root_opening_factor = 1
    ts.complete_branch_lines_when_necessary = True

    return ts, tree
def main(args):

    # STEP 1: Set up logger
    log = logging.getLogger(__name__)
    coloredlogs.install(fmt='%(asctime)s [%(levelname)s] %(message)s', level='DEBUG', logger=log)

    # STEP 2: Retrieve and/or update localized NCBI Taxonomy database
    ncbi = NCBITaxa()
    if (time.time() - os.path.getmtime(os.path.join(Path.home(), ".etetoolkit/taxa.sqlite"))) > 604800:
        ncbi.update_taxonomy_database()

    # STEP 3: Prune species-level tree to family-level

        # Step 3.1 Read tree from input file
    log.debug("Loading Tree...")
    t = Tree(args.infn, format=5)
        # STEP 3.2: Add species names to species_set_from_tree set
    log.debug("Gathering species(leaf) names...")
    species_set_from_tree = set()
    for leaf in t.iter_leaves():
        species_set_from_tree.add(leaf.name.replace("_"," "))
        # STEP 3.3: Assign species to families
    log.debug("Constructing dict of species in family...")
    species_in_family = get_species_in_family(species_set_from_tree, ncbi)
        # STEP 3.4: Prune the tree
    log.debug("Pruning Tree to family level...")
    prune_to_family(t, species_in_family)

    # STEP 4: Calculate counts of species per family and plastid genome entries per family and attach them to the tree leaves

        # STEP 4.1: Read plastid genome information from input table
    species_list_from_table = get_species_list_from_table(args.tablefn)
        # STEP 4.2: Count plastid genome entries per family
    log.debug("Counting plastid genome entries per family...")
    genome_count_per_family = get_genome_count_per_family(species_list_from_table, species_in_family)
        # STEP 4.3: Attach counts to tree leaves
    log.debug("Attaching counts to Tree...")
    attach_counts_to_tree(t, genome_count_per_family, get_species_count_per_family(species_in_family))

    # STEP 5: Set TreeStyle and render tree
    ts = TreeStyle()
    ts.mode = "c"
    ts.draw_guiding_lines = True
    ts.show_leaf_name = False
    log.debug("Rendering Tree...")
    t.render(args.outfn, w=10000, h=10000, tree_style=ts)
Ejemplo n.º 33
0
def my_tree():
    ncbi = NCBITaxa()
    my_tree = ncbi.get_topology([54263, 8324, 8323, 8327, 8325, 57571, 323754])

    for n in my_tree.traverse():
        n.add_features(weight=random.randint(0, 50))

    ts = TreeStyle()

    ts.layout_fn = layout

    ts.mode = "c"

    ts.show_branch_length = True
    ts.show_branch_support = True
    my_tree.get_ascii(attributes=["sci_name", "rank"])
    return my_tree, ts
Ejemplo n.º 34
0
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
Ejemplo n.º 35
0
def render_tree(tree, fname):
    # Generates tree snapshot
    npr_nodestyle = NodeStyle()
    npr_nodestyle["fgcolor"] = "red"
    for n in tree.traverse():
        if hasattr(n, "nodeid"):
            n.set_style(npr_nodestyle)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    ts.mode = "r"
    iterface = faces.TextFace("iter")
    ts.legend.add_face(iterface, 0)

    tree.dist = 0
    tree.sort_descendants()
    tree.render(fname, tree_style=ts, w=700)
Ejemplo n.º 36
0
def render_tree(tree, fname):
    # Generates tree snapshot
    npr_nodestyle = NodeStyle()
    npr_nodestyle["fgcolor"] = "red"
    for n in tree.traverse():
        if hasattr(n, "nodeid"):
            n.set_style(npr_nodestyle)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    ts.show_branch_support = True
    ts.mode = "r"
    iterface = faces.TextFace("iter")
    ts.legend.add_face(iterface, 0)

    tree.dist = 0
    tree.sort_descendants()
    tree.render(fname, tree_style=ts, w=700)
Ejemplo n.º 37
0
def make_plot():
    df = pd.read_csv(f'{args.output}/aa_comp.tsv', sep="\t")
    df = df.set_index('Taxon')

    z = shc.linkage(df, method='ward')
    t = distance_matrix2tree(z, df.index.values)
    t.write(outfile=f'{args.output}/distance_matrix.tre')

    # Basic tree style
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.mode = "c"
    ts.show_scale = False
    ts.layout_fn = mylayout
    # PDF rendering
    t.render(f'{args.output}/aa_comp_calculator.pdf',
             w=183,
             units="mm",
             tree_style=ts)
Ejemplo n.º 38
0
    def visualize(self, group1=None, group2=None):
        import matplotlib
        import matplotlib.pyplot as plt

        # annotate the cluster roots with their fractions
        if group1 or group2:
            for i, cluster_root in enumerate(self.cluster_roots):
                # count downstream conditions in the leafs
                datapoints_in_cluster = list(self.nodes2leaves[cluster_root])
                cluster_root.add_face(
                    TextFace(f"Group1: {len(group1)}// Group2:{len(group2)}"),
                    column=0,
                    position="branch-right")

        def _custom_layout(node):
            cmap_cluster = plt.cm.tab10(
                np.linspace(0, 1, len(self.cluster_roots)))
            cmap_treated = plt.cm.viridis(np.linspace(0, 1, 2))

            if node.is_leaf():
                c_cluster = matplotlib.colors.rgb2hex(
                    cmap_cluster[node.clustering, :])
                c_treat = matplotlib.colors.rgb2hex(
                    cmap_treated[node.treated, :])
                node.img_style["fgcolor"] = c_treat
                node.img_style["bgcolor"] = c_cluster

            if 'is_cluster_root' in node.features:
                c_cluster = matplotlib.colors.rgb2hex(
                    cmap_cluster[node.is_cluster_root, :])
                node.img_style["bgcolor"] = c_cluster
                node.img_style["draw_descendants"] = False
                node.add_face(TextFace(f"#data:{node.n_datapoints}"),
                              column=0,
                              position="branch-right")

        ts = TreeStyle()
        ts.mode = "r"
        ts.show_leaf_name = False
        ts.arc_start = -180  # 0 degrees = 3 o'clock
        ts.arc_span = 270
        ts.layout_fn = _custom_layout
        self.tree.show(tree_style=ts)
Ejemplo n.º 39
0
def get_default_tree_style(color_dict):
    ts = TreeStyle()
    ts.mode = "c"
    # ts.layout_fn = layout
    ts.margin_top = 50
    ts.margin_bottom = 0
    ts.margin_left = 50
    ts.margin_right = 50
    ts.show_scale = False
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    for p, c in color_dict.iteritems():
        ts.legend.add_face(TextFace("    ", fsize=30), column=0)
        ts.legend.add_face(CircleFace(10, c), column=1)
        ts.legend.add_face(TextFace("   %s" % p, fsize=30), column=2)
    legend_margin_line = 5
    while legend_margin_line:
        ts.legend.add_face(TextFace(" "), column=0)
        ts.legend.add_face(TextFace(" "), column=1)
        ts.legend.add_face(TextFace(" "), column=2)
        legend_margin_line -= 1
    ts.legend_position = 3
    return ts
Ejemplo n.º 40
0
def balancetest(table, grouping, tree,
                significance_test=None,
                layout=None,
                normalize=True,
                mode='c'):
    """ Performs statistical test on ilr balances and plots on tree.

    Parameters
    ----------
    table : pd.DataFrame
        A 2D matrix of strictly positive values (i.e. counts or proportions)
        where the rows correspond to samples and the columns correspond to
        features.
    grouping : pd.Series
        Vector indicating the assignment of samples to groups.  For example,
        these could be strings or integers denoting which group a sample
        belongs to.  It must be the same length as the samples in `table`.
        The index must be the same on `table` and `grouping` but need not be
        in the same order.
    tree : skbio.TreeNode
        A strictly bifurcating tree defining a hierarchical relationship
        between all of the features within `table`
    significance_test : function, optional
        A statistical significance function to test for significance between
        classes.  This function must be able to accept at least two 1D
        array_like arguments of floats and returns a test statistic and a
        p-value, or a single statistic. By default ``scipy.stats.f_oneway``
        is used.
    layout : function, optional
        A layout for formatting the tree visualization. Must take a
        `ete.tree` as a parameter.
    mode : str
        Type of display to show the tree. ('c': circular, 'r': rectangular).

    Returns
    -------
    ete_tree : ete.Tree
        ETE tree converted from the `skbio.TreeNode` object
    ts : ete.TreeStyle
        ETE tree style used for formatting the visualized tree,
        with the test statistic plotted on each of the internal nodes.

    Note
    ----
    The `skbio.TreeNode` is assumed to strictly bifurcating and
    whose tips match `table`.  Also, it is assumed that none
    of the values in `table` are zero.  Replace with a pseudocount
    if necessary.

    See also
    --------
    skbio.TreeNode.bifurcate
    skbio.stats.composition.ilr
    skbio.stats.multiplicative_replacement
    scipy.stats.f_oneway
    """

    if np.any(table <= 0):
        raise ValueError('Cannot handle zeros or negative values in `table`. '
                         'Use pseudo counts or ``multiplicative_replacement``.'
                         )

    if significance_test is None:
        significance_test = scipy.stats.f_oneway

    sorted_features = [n.name for n in tree.tips()][::-1]
    if len(sorted_features) != len(table.columns):
        raise ValueError('The number of tips (%d) in the tree must be equal '
                         'to the number features in the table (%d).' %
                         (len(sorted_features), len(table.columns)))
    table = table.reindex(columns=sorted_features)

    mat, cats = check_table_grouping(table, grouping)

    basis, nodes = phylogenetic_basis(tree)
    ilr_coords = ilr(mat, basis=basis)

    ete_tree = Tree(str(tree))

    _cats = set(cats)
    i = 0
    for n in ete_tree.traverse():
        if not n.is_leaf():
            diffs = [ilr_coords[(cats == x).values, i] for x in _cats]

            stat = significance_test(*diffs)
            if len(stat) == 2:
                n.add_features(weight=-np.log(stat[1]))
            elif len(stat) == 1:
                n.add_features(weight=stat)
            else:
                raise ValueError(
                    "Too many arguments returned by %s" %
                    significance_test.__name__)
            i += 1

    # Create an empty TreeStyle
    ts = TreeStyle()

    # Set our custom layout function
    if layout is None:
        ts.layout_fn = default_layout
    else:
        ts.layout_fn = layout

    # Draw a tree
    ts.mode = mode

    # We will add node names manually
    ts.show_leaf_name = False
    # Show branch data
    ts.show_branch_length = True
    ts.show_branch_support = True

    return ete_tree, ts
Ejemplo n.º 41
0
def run(args):
    if args.text_mode:
        from ete3 import Tree
        for tindex, tfile in enumerate(args.src_tree_iterator):
            #print tfile
            if args.raxml:
                nw = re.sub(":(\d+\.\d+)\[(\d+)\]", ":\\1[&&NHX:support=\\2]", open(tfile).read())
                t = Tree(nw)
            else:
                t = Tree(tfile)

            print(t.get_ascii(show_internal=args.show_internal_names,
                              attributes=args.show_attributes))
        return

    import random
    import re
    import colorsys
    from collections import defaultdict
    from ete3 import (Tree, PhyloTree, TextFace, RectFace, faces, TreeStyle,
                         add_face_to_node, random_color)

    global FACES

    if args.face:
        FACES = parse_faces(args.face)
    else:
        FACES = []

    # VISUALIZATION
    ts = TreeStyle()
    ts.mode = args.mode
    ts.show_leaf_name = True
    ts.tree_width = args.tree_width


    for f in FACES:
        if f["value"] == "@name":
            ts.show_leaf_name = False
            break

    if args.as_ncbi:
        ts.show_leaf_name = False
        FACES.extend(parse_faces(
            ['value:@sci_name, size:10, fstyle:italic',
             'value:@taxid, color:grey, size:6, format:" - %s"',
             'value:@sci_name, color:steelblue, size:7, pos:b-top, nodetype:internal',
             'value:@rank, color:indianred, size:6, pos:b-bottom, nodetype:internal',
         ]))


    if args.alg:
        FACES.extend(parse_faces(
            ['value:@sequence, size:10, pos:aligned, ftype:%s' %args.alg_type]
         ))

    if args.heatmap:
        FACES.extend(parse_faces(
            ['value:@name, size:10, pos:aligned, ftype:heatmap']
         ))

    if args.bubbles:
        for bubble in args.bubbles:
            FACES.extend(parse_faces(
                ['value:@%s, pos:float, ftype:bubble, opacity:0.4' %bubble,
             ]))

    ts.branch_vertical_margin = args.branch_separation
    if args.show_support:
        ts.show_branch_support = True
    if args.show_branch_length:
        ts.show_branch_length = True
    if args.force_topology:
        ts.force_topology = True
    ts.layout_fn = lambda x: None

    for tindex, tfile in enumerate(args.src_tree_iterator):
        #print tfile
        if args.raxml:
            nw = re.sub(":(\d+\.\d+)\[(\d+)\]", ":\\1[&&NHX:support=\\2]", open(tfile).read())
            t = PhyloTree(nw)
        else:
            t = PhyloTree(tfile)


        if args.alg:
            t.link_to_alignment(args.alg, alg_format=args.alg_format)

        if args.heatmap:
            DEFAULT_COLOR_SATURATION = 0.3
            BASE_LIGHTNESS = 0.7
            def gradient_color(value, max_value, saturation=0.5, hue=0.1):
                def rgb2hex(rgb):
                    return '#%02x%02x%02x' % rgb
                def hls2hex(h, l, s):
                    return rgb2hex( tuple([int(x*255) for x in colorsys.hls_to_rgb(h, l, s)]))

                lightness = 1 - (value * BASE_LIGHTNESS) / max_value
                return hls2hex(hue, lightness, DEFAULT_COLOR_SATURATION)


            heatmap_data = {}
            max_value, min_value = None, None
            for line in open(args.heatmap):
                if line.startswith('#COLNAMES'):
                    pass
                elif line.startswith('#') or not line.strip():
                    pass
                else:
                    fields = line.split('\t')
                    name = fields[0].strip()

                    values = [float(x) if x else None for x in fields[1:]]

                    maxv = max(values)
                    minv = min(values)
                    if max_value is None or maxv > max_value:
                        max_value = maxv
                    if min_value is None or minv < min_value:
                        min_value = minv
                    heatmap_data[name] = values

            heatmap_center_value = 0
            heatmap_color_center = "white"
            heatmap_color_up = 0.3
            heatmap_color_down = 0.7
            heatmap_color_missing = "black"

            heatmap_max_value = abs(heatmap_center_value - max_value)
            heatmap_min_value = abs(heatmap_center_value - min_value)

            if heatmap_center_value <= min_value:
                heatmap_max_value = heatmap_min_value + heatmap_max_value
            else:
                heatmap_max_value = max(heatmap_min_value, heatmap_max_value)



        # scale the tree
        if not args.height:
            args.height = None
        if not args.width:
            args.width = None

        f2color = {}
        f2last_seed = {}
        for node in t.traverse():
            node.img_style['size'] = 0
            if len(node.children) == 1:
                node.img_style['size'] = 2
                node.img_style['shape'] = "square"
                node.img_style['fgcolor'] = "steelblue"

            ftype_pos = defaultdict(int)

            for findex, f in enumerate(FACES):
                if (f['nodetype'] == 'any' or
                    (f['nodetype'] == 'leaf' and node.is_leaf()) or
                    (f['nodetype'] == 'internal' and not node.is_leaf())):


                    # if node passes face filters
                    if node_matcher(node, f["filters"]):
                        if f["value"].startswith("@"):
                            fvalue = getattr(node, f["value"][1:], None)
                        else:
                            fvalue = f["value"]

                        # if node's attribute has content, generate face
                        if fvalue is not None:
                            fsize = f["size"]
                            fbgcolor = f["bgcolor"]
                            fcolor = f['color']

                            if fcolor:
                                # Parse color options
                                auto_m = re.search("auto\(([^)]*)\)", fcolor)
                                if auto_m:
                                    target_attr = auto_m.groups()[0].strip()
                                    if not target_attr :
                                        color_keyattr = f["value"]
                                    else:
                                        color_keyattr = target_attr

                                    color_keyattr = color_keyattr.lstrip('@')
                                    color_bin = getattr(node, color_keyattr, None)

                                    last_seed = f2last_seed.setdefault(color_keyattr, random.random())

                                    seed = last_seed + 0.10 + random.uniform(0.1, 0.2)
                                    f2last_seed[color_keyattr] = seed

                                    fcolor = f2color.setdefault(color_bin, random_color(h=seed))

                            if fbgcolor:
                                # Parse color options
                                auto_m = re.search("auto\(([^)]*)\)", fbgcolor)
                                if auto_m:
                                    target_attr = auto_m.groups()[0].strip()
                                    if not target_attr :
                                        color_keyattr = f["value"]
                                    else:
                                        color_keyattr = target_attr

                                    color_keyattr = color_keyattr.lstrip('@')
                                    color_bin = getattr(node, color_keyattr, None)

                                    last_seed = f2last_seed.setdefault(color_keyattr, random.random())

                                    seed = last_seed + 0.10 + random.uniform(0.1, 0.2)
                                    f2last_seed[color_keyattr] = seed

                                    fbgcolor = f2color.setdefault(color_bin, random_color(h=seed))

                            if f["ftype"] == "text":
                                if f.get("format", None):
                                    fvalue = f["format"] % fvalue

                                F = TextFace(fvalue,
                                             fsize = fsize,
                                             fgcolor = fcolor or "black",
                                             fstyle = f.get('fstyle', None))

                            elif f["ftype"] == "fullseq":
                                F = faces.SeqMotifFace(seq=fvalue, seq_format="seq",
                                                       seqtail_format="seq",
                                                       height=fsize)
                            elif f["ftype"] == "compactseq":
                                F = faces.SeqMotifFace(seq=fvalue, seq_format="compactseq",
                                                       seqtail_format="compactseq",
                                                       height=fsize)
                            elif f["ftype"] == "blockseq":
                                F = faces.SeqMotifFace(seq=fvalue, seq_format="blockseq",
                                                   seqtail_format="blockseq",
                                                       height=fsize,
                                                       fgcolor=fcolor or "slategrey",
                                                       bgcolor=fbgcolor or "slategrey",
                                                       scale_factor = 1.0)
                                fbgcolor = None
                            elif f["ftype"] == "bubble":
                                try:
                                    v = float(fvalue)
                                except ValueError:
                                    rad = fsize
                                else:
                                    rad = fsize * v
                                F = faces.CircleFace(radius=rad, style="sphere",
                                                     color=fcolor or "steelblue")

                            elif f["ftype"] == "heatmap":
                                if not f['column']:
                                    col = ftype_pos[f["pos"]]
                                else:
                                    col = f["column"]

                                for i, value in enumerate(heatmap_data.get(node.name, [])):
                                    ftype_pos[f["pos"]] += 1

                                    if value is None:
                                        color = heatmap_color_missing
                                    elif value > heatmap_center_value:
                                        color = gradient_color(abs(heatmap_center_value - value), heatmap_max_value, hue=heatmap_color_up)
                                    elif value < heatmap_center_value:
                                        color = gradient_color(abs(heatmap_center_value - value), heatmap_max_value, hue=heatmap_color_down)
                                    else:
                                        color = heatmap_color_center
                                    node.add_face(RectFace(20, 20, color, color), position="aligned", column=col + i)
                                    # Add header
                                    # for i, name in enumerate(header):
                                    #    nameF = TextFace(name, fsize=7)
                                    #    nameF.rotation = -90
                                    #    tree_style.aligned_header.add_face(nameF, column=i)
                                F = None

                            elif f["ftype"] == "profile":
                                # internal profiles?
                                F = None
                            elif f["ftype"] == "barchart":
                                F = None
                            elif f["ftype"] == "piechart":
                                F = None



                            # Add the Face
                            if F:
                                F.opacity = f['opacity'] or 1.0

                                # Set face general attributes
                                if fbgcolor:
                                    F.background.color = fbgcolor

                                if not f['column']:
                                    col = ftype_pos[f["pos"]]
                                    ftype_pos[f["pos"]] += 1
                                else:
                                    col = f["column"]
                                node.add_face(F, column=col, position=f["pos"])

        if args.image:
            t.render("t%d.%s" %(tindex, args.image),
                     tree_style=ts, w=args.width, h=args.height, units=args.size_units)
        else:
            t.show(None, tree_style=ts)
Ejemplo n.º 42
0
	else:
		#We're at the root node
		new_node.dist = 0

	cur_node_id = str(current_bud_row.OrgID)

	for idx, new_row in saved_pop_hosts[saved_pop_hosts.ParentID.eq(cur_node_id)].iterrows():	
		build_tree_recursive(new_row, new_node)

	return new_node


root_node_row = saved_pop_hosts[saved_pop_hosts.ParentID == "(none)"].squeeze()
print("Building Tree")
build_tree_recursive(root_node_row, host_phylo)


print("Drawing Tree")
#Some drawing code
ts = TreeStyle()
ts.show_leaf_name = True
ts.mode = "c"
ts.arc_start = -180 # 0 degrees = 3 o'clock
ts.arc_span = 180
host_phylo.render("tree.png", tree_style=ts)

print("Saving Tree")
#Write the Newick Format Tree
host_phylo.write(format=1, outfile="avida_tree.nw")

Ejemplo n.º 43
0
            nstyle['bgcolor'] = cp[0]
        elif abr == 'pbi':
            nstyle['bgcolor'] = cp[1]
        elif abr == 'pte':
            nstyle['bgcolor'] = cp[2]
        elif abr == 'ppe':
            nstyle['bgcolor'] = cp[3]
        elif abr == 'pse':
            nstyle['bgcolor'] = cp[4]
        elif abr == 'poc':
            nstyle['bgcolor'] = cp[5]
        elif abr == 'ptr':
            nstyle['bgcolor'] = cp[6]
        elif abr == 'pso':
            nstyle['bgcolor'] = cp[7]
        elif abr == 'pca':
            nstyle['bgcolor'] = cp[8]
        elif abr == 'tth':
            nstyle['bgcolor'] = cp[9]
        else:
            nstyle['bgcolor'] = "#000000"
        node.set_style(nstyle)


ts = TreeStyle()
#ts.show_leaf_name = False
ts.mode = 'c'
ts.title.add_face(TextFace(title, fsize=20), column=0)
#t.show(tree_style = ts)
t.render(outputfile, tree_style = ts)
Ejemplo n.º 44
0
@author: diyadas

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)
Ejemplo n.º 45
0
                        

#root = Tree( "((a,b),c);" )

[rows, columns] = treeStruct.shape

root = Tree()
node_cur = root

'''#######################
 Tree Style Begin
'''
ts = TreeStyle()
ts.title.add_face(TextFace("Tree example", fsize=8), column=0)
ts.scale = 50
ts.mode = 'r'

# left or right
ts.orientation = 1

ts.rotation = 270
ts.show_leaf_name = False
ts.show_branch_length = True
#ts.show_branch_length = True
'''
 Tree Style End
#######################'''



Ejemplo n.º 46
0
application.CONFIG["DISPLAY"] = ":0" # This is the most common
                                     # configuration

# We extend the minimum WebTreeApplication with our own WSGI
# application
application.set_external_app_handler(example_app)

# Lets now apply our custom tree loader function to the main
# application
application.set_tree_loader(my_tree_loader)

# And our layout as the default one to render trees
ts = TreeStyle()
ts.show_leaf_name = False
ts.layout_fn.append(main_layout)
ts.mode = "r"
ts.branch_vertical_margin = 5
#ts.scale = 20
application.set_tree_style(ts)
#application.set_default_layout_fn(main_layout)
application.set_tree_size(None, None)
# I want to make up how tree image in shown using a custrom tree
# renderer that adds much more HTML code
application.set_external_tree_renderer(tree_renderer)


# ==============================================================================
# ADD CUSTOM ACTIONS TO THE APPLICATION
#
# The function "register_action" allows to attach functionality to
# nodes in the image. All registered accions will be shown in the
Ejemplo n.º 47
0
def main(args):
	if args.alignment:
		t = PhyloTree(args.tree, alignment=args.alignment, alg_format='fasta')
	else:
		t = PhyloTree(args.tree)

	if args.highlight_new:
		runs = read_runs(args.highlight_new)

	t.set_outgroup('EM_079422')
	t.ladderize()

	ts = TreeStyle()
	ts.show_leaf_name = False
	ts.show_branch_support = False
	ts.layout_fn = layout

	thick_hz_line = NodeStyle()
	thick_hz_line["hz_line_width"] = 8
	t.set_style(thick_hz_line)
	#t.children[0].set_style(thick_hz_line)
	#t.children[1].set_style(thick_hz_line)

	thick_vt_line = NodeStyle()
	thick_vt_line["vt_line_width"] = 4
	t.set_style(thick_vt_line)

	# header
	if not args.hide_annotations:
		ts.aligned_header.add_face(MyTextFace('Sample identifier', fstyle='Bold', fsize=8, tight_text=False), column = 1)
		ts.aligned_header.add_face(MyTextFace('Prefecture', fstyle='Bold', fsize=8, tight_text=False), column = 2)
		ts.aligned_header.add_face(MyTextFace('Sous-prefecture', fstyle='Bold', fsize=8, tight_text=False), column = 3)
		ts.aligned_header.add_face(MyTextFace('Village', fstyle='Bold', fsize=8, tight_text=False), column = 4)
		ts.aligned_header.add_face(MyTextFace('Sample received', fstyle='Bold', fsize=8, tight_text=False), column = 5)

	if args.positions:
		positions = read_positions(args.positions)

		alg_header = RulerFace(positions,
                              col_width=11,
                              height=0, # set to 0 if dont want to use values
                              kind="stick",
                              hlines = [0],
                              hlines_col = ["white"], # trick to hide hz line
                              )

		ts.aligned_header.add_face(alg_header, 6)

	#legend
	if args.legend:
		legend = {}
		for s in samples.values():
			legend[s['prefec']] = s['prefec__colour']
		for p in sorted(legend.keys()):
			ts.legend.add_face(CircleFace(4, legend[p]), column=0)
			ts.legend.add_face(MyTextFace(p, fsize=6, tight_text=False), column=1)	
		ts.legend_position=1

	if args.circular:
		ts.mode = "c"
		ts.arc_start = -180 # 0 degrees = 3 o'clock
		ts.arc_span = 180

#	t.show(tree_style=ts)
	t.render(args.output, tree_style=ts, w=1024)
Ejemplo n.º 48
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
                faces.add_face_to_node(name, node, 0, aligned=True)
            fake = faces.TextFace(" ")
            fake.background.color = "white"
            faces.add_face_to_node(fake, node, 1, aligned=True) # fake
        else:
            if not args.no_internal_names and node.get_distance(tNCBI, topology_only=True) < 3:
                name = faces.TextFace(node.sci_name, fsize=12, fstyle='italic')
                faces.add_face_to_node(name, node, 0, position='branch-top')

            
    S = TreeStyle()
    #S.allow_face_overlap = True
    S.show_leaf_name = False
    #S.scale = 200
    #S.draw_aligned_faces_as_table = True
    #S.aligned_table_style = 0
    #S.min_leaf_separation = 1
    if args.mode == 'r':
        S.mode = 'r'
    elif args.mode == 'c':
        S.mode = 'c'

    if args.save:
        tNCBI.render(file_name=args.save, layout=layout, tree_style=S)
    else:
        print "showing"
        tNCBI.show(layout=layout, tree_style=S)