Esempio n. 1
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
Esempio n. 2
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
Esempio 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
Esempio n. 4
0
def custom_treestyle():
    ts = TreeStyle()
    ts.layout_fn = custom_layout
    ts.show_leaf_name = False
    ts.branch_vertical_margin = 0
    ts.min_leaf_separation = 0
    return ts
Esempio n. 5
0
def generate_type_tree_figure(output_file):
    """ Generate type_tree.png image.

    It needs ETE dependencies installed
    cf http://etetoolkit.org/new_download/ or use anaconda

    :param output_file: str
    """
    try:
        from ete3 import faces, TextFace, TreeStyle
    except ImportError as e:
        logger.warning(
            'ImportError : %s Generation of type_tree figure need ETE dependencies to '
            'be installed Use from anaconda, or look at installation procedure on '
            'http://etetoolkit.org/new_download/', e)
        return

    # Define custom tree style
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.orientation = 1
    ts.branch_vertical_margin = 20

    def my_layout(node):
        F = TextFace(node.name, fsize=16, ftype='Courier', bold=True)
        faces.add_face_to_node(F, node, column=10, position="branch-right")

    ts.layout_fn = my_layout

    TYPES_STRING_TREE.render(output_file, tree_style=ts)
Esempio n. 6
0
def createImg(filename, thres=0, samples=1):
    count = parseLineage(filename)
    suffix, matrix, taxo = getSuffixandMatrixandNewick(count,thres,samples)
    newick = convert(taxo,suffix)
    newick += ';'

    t = Tree(newick, format=1)
    ct = ClusterTree(t.write(),  text_array=matrix)
    addColors(ct)

    # nodes are linked to the array table
    array = ct.arraytable
    # Calculates some stats on the matrix. Needed to establish the color gradients.
    matrix_dist = [i for r in xrange(len(array.matrix))for i in array.matrix[r] if np.isfinite(i)]
    matrix_max = np.max(matrix_dist)
    matrix_min = np.min(matrix_dist)
    matrix_avg = (matrix_max+matrix_min)/2
    # Creates a profile face that will represent node's profile as a heatmap
    profileFace  = ProfileFace(matrix_max, matrix_min, matrix_avg, 200, 14, "heatmap",colorscheme=3)
    # Creates my own layout function that uses previous faces
    def mylayout(node):
        # If node is a leaf
        if node.is_leaf():
            # And a line profile
            add_face_to_node(profileFace, node, 0, aligned=True)
            node.img_style["size"]=2

    # Use my layout to visualize the tree
    ts = TreeStyle()
    ts.layout_fn = mylayout
    # ct.show(tree_style=ts)
    filedir = '/'.join(filename.split('/')[:-1])
    # t.write(format=9, outfile="output/newick/"+param+".nw")
    ct.render(filedir+'/phylo.png',tree_style=ts)
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
Esempio n. 8
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
Esempio n. 9
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
Esempio n. 10
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
Esempio n. 11
0
    def ete_draw(self, fname=None):
        """ Draws the tree and saves it to a file.  If `fname` is None,
            show the tree instead of saving it.

            Args:
                fname: filename to save to (default=None)
        """
        if Cfg.USE_ETE3:

            def layout(node):
                faces.add_face_to_node(AttrFace("name"),
                                       node,
                                       column=0,
                                       position="branch-right")

            ts = TreeStyle()
            ts.show_leaf_name = False
            ts.layout_fn = layout
            ts.rotation = 90

            tree = EteTree(self.ete_str(), format=8)

            if fname:
                tree.render(fname, tree_style=ts)
            else:
                tree.show(tree_style=ts)
        else:
            # TODO maybe throw an error?
            pass
Esempio n. 12
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
Esempio n. 13
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)
Esempio n. 14
0
    def ete_draw(self, fname=None):
        """ Draws the tree and saves it to a file.  If `fname` is None,
            show the tree instead of saving it.

            Args:
                fname: filename to save to (default=None)
        """
        if Cfg.USE_ETE3:
            def layout(node):
                faces.add_face_to_node(AttrFace("name"), node, column=0,
                                       position="branch-right")

            ts = TreeStyle()
            ts.show_leaf_name = False
            ts.layout_fn = layout
            ts.rotation = 90
            
            tree = EteTree(self.ete_str(), format=8)

            if fname:
                tree.render(fname, tree_style=ts)
            else:
                tree.show(tree_style=ts)
        else:
            # TODO maybe throw an error?
            pass
Esempio n. 15
0
def make_tree(t):
    ts = TreeStyle()

    ## make the tree in to a cladogram
    most_distant_leaf, tree_length = t.get_farthest_leaf()
    current_dist = 0
    for postorder, node in t.iter_prepostorder():
        if postorder:
            current_dist -= node.dist
        else:
            if node.is_leaf():
                node.dist += tree_length - (current_dist + node.dist)
            elif node.up:  # node is internal
                current_dist += node.dist

    ## Rotate and color the lables
    def rotation_layout(node):
        if node.is_leaf():
            if node.name == 'X':
                F = TextFace(node.name, tight_text=True, fgcolor='Blue')
                F.rotation = 90
                add_face_to_node(F, node, column=0, position="branch-right")
            elif node.name == 'Y':
                F = TextFace(node.name, tight_text=True, fgcolor='Red')
                F.rotation = 90
                add_face_to_node(F, node, column=0, position="branch-right")
            elif node.name == 'A':
                F = TextFace("")
                add_face_to_node(F, node, column=0, position="branch-right")
            else:
                F = TextFace(node.name, tight_text=True, fgcolor='Green')
                F.rotation = 90
                add_face_to_node(F, node, column=0, position="branch-right")

    ## Format the tree image
    nstyle = NodeStyle()
    nstyle["hz_line_type"] = 0
    nstyle["vt_line_color"] = "#ffffff"
    nstyle["hz_line_color"] = "#ffffff"
    nstyle["vt_line_width"] = 4
    nstyle["hz_line_width"] = 4
    nstyle["size"] = 0

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

    ## Set background
    t.img_style["bgcolor"] = "#2e3440"

    ## Tree 'shape'

    ts.min_leaf_separation = 20
    ts.show_leaf_name = False
    ts.layout_fn = rotation_layout
    ts.rotation = -90
    ts.show_scale = False

    #t.show(tree_style=ts)

    t.render(f"{t.name}.svg", tree_style=ts, dpi=900)
Esempio n. 16
0
def show_and_render_tree(tree, output_file_name, mut_order):
    # The following makes it show internal nodes
    def my_layout(node):
        if hasattr(node, 'has_face'):
            return
        if node.is_leaf():
            # If terminal node, draws its name
            name_face = AttrFace("name", fsize=12)
            node.add_face(name_face, column=0, position="branch-right")
        else:
            # If internal node, draws label with smaller font size
            if node.name == 'root':
                label = 'root'
            else:
                label = str(mut_order[int(node.name)])
            name_face = TextFace(label, fsize=10)
            node.add_face(name_face, column=0, position="branch-top")
        node.add_feature('has_face', True)

    # Adds the name face to the image at the preferred position
    #faces.add_face_to_node(name_face, node, column=0, position="branch-top")
    ts = TreeStyle()
    # Do not add leaf names automatically
    ts.show_leaf_name = False
    # Use my custom layout
    ts.layout_fn = my_layout
    tree.show(tree_style=ts)
    tree.render(output_file_name, tree_style=ts, dpi=180)
Esempio n. 17
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
Esempio n. 18
0
def compute_minimum_spanning_tree(file_name, artists, distance_matrix, authors,
                                  styles, list_period_color):
    dst_list = []

    max = len(distance_matrix[-1])
    for line in distance_matrix:
        remain = max - len(line)
        dst_list.append(line + [0.0] * remain)

    G = np.array(dst_list)
    Tcsr = minimum_spanning_tree(G)
    G = nx.Graph(Tcsr)

    elst = bfs_edge_lst(G, 1)
    tree = tree_from_edge_lst(elst)
    newick_minimum_spanning_tree = tree_to_newick(tree) + ';'

    t = Tree(newick_minimum_spanning_tree)
    vl = []
    for node in t.traverse("postorder"):
        if node.is_leaf():
            name = artists[int(node.name)]
            node.name = name
        else:
            name = artists[int(node.support)]
            node.name = name
        vl.append(node.name)

    ts = TreeStyle()
    ts, t = set_default_TreeStyle(t)

    def my_layout(node):
        F = TextFace("\t" + node.name,
                     tight_text=True,
                     fstyle="bold",
                     fsize=40,
                     fgcolor="black")
        F.rotation = 90
        add_face_to_node(F, node, column=0, position="branch-bottom")

    ts.layout_fn = my_layout
    list_of_nodes = {}

    for author in authors:
        for node in t.traverse("postorder"):
            if (node.name == author):
                new_dic = get_sister_common_styles(node, artists, styles)
        list_of_nodes.update(new_dic)

    prevalent_dict = most_prevalent(list_of_nodes)

    for author in authors:
        for node in t.traverse("postorder"):
            if (node.name == author):
                attribute_legend(node, authors, styles)
                add_painting(node, im, basename)

    savename_period = "../plots/" + file_name + "Kruskal_minimum_spanning_tree.pdf"
    t.render(savename_period, tree_style=ts)
Esempio n. 19
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
Esempio n. 20
0
def custom_treestyle():
    #Add treestyle
    ts = TreeStyle()
    #use custom layout fuction
    ts.layout_fn = custom_layout
    #don't show leaf names (leaf names can be customized  in custom layout)
    ts.show_leaf_name = False
    return ts
Esempio n. 21
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
Esempio n. 22
0
 def get_tree_style(self):
     ts = TreeStyle()
     ts.layout_fn = self.custom_layout
     ts.show_leaf_name = False
     ts.draw_guiding_lines = True
     #ts.guiding_lines_type = 1
     self._treestyle = ts
     return ts
Esempio n. 23
0
def export_tree(tree, filename, insignif_color, signif_color, i_group, width):
    '''
    exports the given tree to the given filename
    '''
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.layout_fn = generate_layout(insignif_color, signif_color, i_group)
    tree.render(filename, w=width, tree_style=ts)
Esempio n. 24
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
Esempio n. 25
0
def get_example_tree():
    t = Tree()
    t.populate(10)
    ts = TreeStyle()
    ts.rotation = 45
    ts.show_leaf_name = False
    ts.layout_fn = rotation_layout

    return t, ts
Esempio n. 26
0
def get_example_tree():

    t = Tree()
    t.populate(8, reuse_names=False)

    ts = TreeStyle()
    ts.layout_fn = master_ly
    ts.title.add_face(faces.TextFace("Drawing your own Qt Faces", fsize=15), 0)
    return t, ts
Esempio n. 27
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
Esempio n. 28
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
Esempio n. 29
0
def get_example_tree():

    t = Tree()
    t.populate(8, reuse_names=False)

    ts = TreeStyle()
    ts.layout_fn = master_ly
    ts.title.add_face(faces.TextFace("Drawing your own Qt Faces", fsize=15), 0)
    return t, ts
Esempio n. 30
0
def plot_tree(tree, leafname2data = None , show_support = False, figname = None, outfname_tree = None):

	
	def layout(node):
		
		nst_internal = NodeStyle()   
		nst_internal['size'] = 1
		nst_internal['fgcolor'] = 'black'
		nst_internal["vt_line_color"] = "black"
		nst_internal["hz_line_color"] = "black"
		nst_internal["vt_line_width"] = 1
		nst_internal["hz_line_width"] = 1
		nst_internal["vt_line_type"] = 0 #0 solid, 1 dashed, 2 dotted
		nst_internal["hz_line_type"] = 0
		
		node.set_style(nst_internal) 

		if leafname2data != None and node.is_leaf():  
			if not node.name[0] == '_':
				print(node.name)
				nst = NodeStyle()

				node_data  = leafname2data[node.name]
				node_name  = node.name
				node_shape = None
				node_color = None
				if len(node_data) >= 3:
					node_name  = node_data[0]
					node_shape = node_data[1]
					node_color = '#'+node_data[2].lower()
				else:
					node_shape = node_data[0]
					node_color = '#'+node_data[1].lower()

				nst['size']    = 15
				nst['shape']   = node_shape
				nst['fgcolor'] = node_color
				
				node.set_style(nst)
				#node.add_face(TextFace(node_name, ftype='Verdana', fsize=12), column = 0, position = "aligned")

	ts = TreeStyle()
	ts.layout_fn = layout
	ts.show_leaf_name = False
	if show_support: 
		ts.show_branch_support = True

	ts.branch_vertical_margin  = 10

	if outfname_tree != None:
		tree.write(outfile = outfname_tree)

	if figname != None:
		tree.render(figname, layout=layout, w=None, h=None, tree_style=ts, units='px', dpi=300)
	else:
		tree.show(tree_style=ts)	
Esempio n. 31
0
def get_example_tree():
    with open("avian_tree", "r") as infile:
        data = infile.read()

    t = Tree(data)

    ts = TreeStyle()
    ts.layout_fn = master_ly
    ts.title.add_face(faces.TextFace("Drawing your own Qt Faces", fsize=15), 0)
    return t, ts
Esempio n. 32
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
def set_tree_style_extended():
    ts = TreeStyle()
    # for i in range(16):
    #     ts.legend.add_face(CircleFace(10, color_dictionary["N{0}".format(i)]), column=0)

    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.layout_fn = my_layout_extended

    return ts
Esempio n. 34
0
 def show(self):
     """
     Allows user to quickly view LinkTree
     """
     style = TreeStyle()
     style.show_leaf_name = False
     def my_layout(node):
         node_style = TextFace(node.name, tight_text=True)
         add_face_to_node(node_style, node, column=0, position='branch-bottom')
     style.layout_fn = my_layout
     self._tree.show(tree_style=style)
Esempio n. 35
0
def get_example_tree():

    t = Tree()
    t.populate(8)

    # 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)

    # Set bold red branch to the root node
    style = NodeStyle()
    style["fgcolor"] = "#0f0f0f"
    style["size"] = 0
    style["vt_line_color"] = "#ff0000"
    style["hz_line_color"] = "#ff0000"
    style["vt_line_width"] = 8
    style["hz_line_width"] = 8
    style["vt_line_type"] = 0  # 0 solid, 1 dashed, 2 dotted
    style["hz_line_type"] = 0
    t.set_style(style)

    #Set dotted red lines to the first two branches
    style1 = NodeStyle()
    style1["fgcolor"] = "#0f0f0f"
    style1["size"] = 0
    style1["vt_line_color"] = "#ff0000"
    style1["hz_line_color"] = "#ff0000"
    style1["vt_line_width"] = 2
    style1["hz_line_width"] = 2
    style1["vt_line_type"] = 2  # 0 solid, 1 dashed, 2 dotted
    style1["hz_line_type"] = 2
    t.children[0].img_style = style1
    t.children[1].img_style = style1

    # Set dashed blue lines in all leaves
    style2 = NodeStyle()
    style2["fgcolor"] = "#000000"
    style2["shape"] = "circle"
    style2["vt_line_color"] = "#0000aa"
    style2["hz_line_color"] = "#0000aa"
    style2["vt_line_width"] = 2
    style2["hz_line_width"] = 2
    style2["vt_line_type"] = 1  # 0 solid, 1 dashed, 2 dotted
    style2["hz_line_type"] = 1
    for l in t.iter_leaves():
        l.img_style = style2

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

    return t, ts
Esempio n. 36
0
def get_example_tree():

    t = Tree()
    t.populate(8)

    # 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)

    # Set bold red branch to the root node
    style = NodeStyle()
    style["fgcolor"] = "#0f0f0f"
    style["size"] = 0
    style["vt_line_color"] = "#ff0000"
    style["hz_line_color"] = "#ff0000"
    style["vt_line_width"] = 8
    style["hz_line_width"] = 8
    style["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted
    style["hz_line_type"] = 0
    t.set_style(style)

    #Set dotted red lines to the first two branches
    style1 = NodeStyle()
    style1["fgcolor"] = "#0f0f0f"
    style1["size"] = 0
    style1["vt_line_color"] = "#ff0000"
    style1["hz_line_color"] = "#ff0000"
    style1["vt_line_width"] = 2
    style1["hz_line_width"] = 2
    style1["vt_line_type"] = 2 # 0 solid, 1 dashed, 2 dotted
    style1["hz_line_type"] = 2
    t.children[0].img_style = style1
    t.children[1].img_style = style1

    # Set dashed blue lines in all leaves
    style2 = NodeStyle()
    style2["fgcolor"] = "#000000"
    style2["shape"] = "circle"
    style2["vt_line_color"] = "#0000aa"
    style2["hz_line_color"] = "#0000aa"
    style2["vt_line_width"] = 2
    style2["hz_line_width"] = 2
    style2["vt_line_type"] = 1 # 0 solid, 1 dashed, 2 dotted
    style2["hz_line_type"] = 1
    for l in t.iter_leaves():
        l.img_style = style2

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

    return t, ts
Esempio n. 37
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
Esempio n. 38
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
Esempio n. 39
0
 def run_action_change_style(self, tree, a_data):
     #print "action change style called.."        
     if tree.tree_style == self._treestyle:
        ts2 = TreeStyle()
        ts2.layout_fn = self.custom_layout
        ts2.show_leaf_name = False
        ts2.draw_guiding_lines = True
        ts2.guiding_lines_type = 0 #solid line
        ts2.guiding_lines_color = a_data
        tree.tree_style = ts2
        self._treestyle = ts2
     else:
        tree.tree_style = self._treestyle
Esempio n. 40
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
Esempio n. 41
0
def draw_ete3_tree(organism, snplist, tree_file_name, config, c):
	'''Draws a phylogenetic tree using ETE3

	Keyword arguments:
	organism -- the organism of which to make a tree
	snplist -- a list of the SNP names, positions and state
	file_name -- the name of the out-file _tree.pdf will be added

	'''
	newick = tree_to_newick(organism, config, c)
	tree = Tree(newick, format=1)
	tree_depth = int(tree.get_distance(tree.get_farthest_leaf()[0]))
	for n in tree.traverse():
		# Nodes are set to red colour
		nstyle = NodeStyle()
		nstyle["fgcolor"] = "#BE0508"
		nstyle["size"] = 10
		nstyle["vt_line_color"] = "#000000"
		nstyle["hz_line_color"] = "#000000"
		nstyle["vt_line_type"] = 0
		nstyle["hz_line_type"] = 0
		nstyle["vt_line_width"] = 2
		nstyle["hz_line_width"] = 2
		## ['B.3', 'T', 'C', 'A']
		for snp in snplist.keys():
			if n.name == snp and snplist[snp] == 0:
				# If the SNP is missing due to a gap, make it grey
				nstyle["fgcolor"] = "#DDDDDD"
				nstyle["size"] = 10
				nstyle["vt_line_color"] = "#DDDDDD"
				nstyle["hz_line_color"] = "#DDDDDD"
				nstyle["vt_line_type"] = 1
				nstyle["hz_line_type"] = 1
			elif n.name == snp and snplist[snp] == 1:
				nstyle["fgcolor"] = "#99FF66"
				nstyle["size"] = 15
				nstyle["vt_line_color"] = "#000000"
				nstyle["hz_line_color"] = "#000000"
				nstyle["vt_line_type"] = 0
				nstyle["hz_line_type"] = 0

		n.set_style(nstyle)
	ts = TreeStyle()
	ts.show_leaf_name = False  # Do not print(leaf names, they are added in layout)
	ts.show_scale = False  # Do not show the scale
	ts.layout_fn = self.CanSNPer_tree_layout  # Use the custom layout
	ts.optimal_scale_level = 'full'  # Fully expand the branches of the tree
	if config["dev"]:
		print("#[DEV] Tree file: %s" % tree_file_name)
	tree.render(tree_file_name, tree_style=ts, width=tree_depth * 500)
def tree2img(newick_tree, save_path):
    t = Tree(newick_tree, format=1)
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    def my_layout(node):
        F = TextFace(node.name, tight_text=True)
        add_face_to_node(F, node, column=0, position="branch-right")
    ts.layout_fn = my_layout
    ts.branch_vertical_margin = 10
    ts.rotation = 90
    t.render(save_path+'png', tree_style=ts)
    t.render(save_path+'svg', tree_style=ts)
Esempio n. 43
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)
Esempio n. 44
0
def get_example_tree():
    # Create a random tree and add to each leaf a random set of motifs
    # from the original set
    t = Tree()
    t.populate(10)
    # for l in t.iter_leaves():
    #     seq_motifs = [list(m) for m in motifs] #sample(motifs, randint(2, len(motifs)))

    #     seqFace = SeqMotifFace(seq, seq_motifs, intermotif_format="line",
    #                            seqtail_format="compactseq", scale_factor=1)
    #     seqFace.margin_bottom = 4
    #     f = l.add_face(seqFace, 0, "aligned")

    ts = TreeStyle()
    ts.layout_fn = layout
    return t, ts
Esempio n. 45
0
def draw_tree(tree_string):
    
    t = Tree(tree_string, format=8)
    
    def mylayout(node):
        #if node.name != 'L':
        file = 'tmp/%s.png' % node.name
        new_face = faces.ImgFace(file)
        new_face.rotable = True
        new_face.rotation = -90
        #new_face.margin_top = 50
        new_face.margin_left = 15
        faces.add_face_to_node(new_face, node, column=0 , position='branch-top')
        
    ts = TreeStyle()
    ts.rotation = 90
    ts.layout_fn = mylayout
    t.show(tree_style = ts)
    plt.clf()
Esempio n. 46
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)
Esempio n. 47
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)
Rangifer_tarandus,http://media.eol.org/content/2014/05/02/09/88803_98_68.jpg,109.09,herbivore
Cervus_elaphus,http://media.eol.org/content/2013/02/22/16/31998_98_68.jpg,240.87,herbivore
Bos_taurus,http://media.eol.org/content/2014/09/29/06/46535_98_68.jpg,618.64,herbivore
Ovis_orientalis,http://media.eol.org/content/2015/01/04/05/30107_98_68.jpg,39.1,herbivore
Suricata_suricatta,http://media.eol.org/content/2012/06/19/04/84840_98_68.jpg,0.73,carnivore
Mephitis_mephitis,http://media.eol.org/content/2012/08/30/16/23686_98_68.jpg,2.4,omnivore"""
tip2info = {}
for line in tip_info_csv.split('\n'):
    if line:
        name, url, mass, habit = map(str.strip, line.split(','))
        tip2info[name] = [url, mass, habit]


# Server configuration

ts = TreeStyle()
ts.layout_fn = custom_layout
ts.show_leaf_name = False

ts2 = TreeStyle()

actions = NodeActions()

actions.add_action('Root here', show_action_root, run_action_root, None)
actions.add_action('Highlight', show_action_highlight, run_action_highlight, None)
actions.add_action('Change style', show_action_change_style, run_action_change_style, None)
actions.add_action('EOL link', show_eol_link, None, eol_link)
actions.add_action('Change color', show_action_linecolor, None, change_linecolor)

start_server(node_actions=actions, tree_style=ts)
Esempio n. 49
0
    if "highlighted" in node.features:
        node.img_style["bgcolor"] = "LightCyan"

    if "improve" in node.features:
        color = "orange" if float(node.improve) < 0 else "green"
        if float(node.improve) == 0:
            color = "blue"

        support_face = faces.CircleFace(200, color)
        faces.add_face_to_node(support_face, node, 0, position="float-behind")

try:
    from ete3 import TreeStyle, NodeStyle, faces
    from ete3.treeview import random_color
    NPR_TREE_STYLE = TreeStyle()
    NPR_TREE_STYLE.layout_fn = npr_layout
    NPR_TREE_STYLE.show_leaf_name = False
except ImportError:
    TreeStyle, NodeStyle, faces, random_color = [None]*4
    NPR_TREE_STYLE = None



# CONVERT shell colors to the same curses palette
COLORS = {
    "wr": '\033[1;37;41m', # white on red
    "wo": '\033[1;37;43m', # white on orange
    "wm": '\033[1;37;45m', # white on magenta
    "wb": '\033[1;37;46m', # white on blue
    "bw": '\033[1;37;40m', # black on white
    "lblue": '\033[1;34m', # light blue
Esempio n. 50
0
    #
    # add names to all nodes (not just to leaf nodes)
    # ete3/test/test_treeview/face_rotation.py
    F = TextFace(node.name, tight_text=True)
    add_face_to_node(F, node, column=0, position="branch-right")
    #
    # add branch lengths
    # ete3/treeview/qt4_render.py
    if not node.is_root():
        bl_face = AttrFace("dist", fsize=8, ftype="Arial",
                fgcolor="black", formatter="%0.3g")
        #
        # This is a failed attempt to center the branch length text on the branch.
        #a = 1 # 0 left, 1 center, 2 right
        #bl_face.hz_align = a
        #bl_face.vt_align = a
        #add_face_to_node(bl_face, node, column=0, aligned=True, position="branch-top")
        add_face_to_node(bl_face, node, column=0, position="branch-top")
    #
    # I guess we also have to explicitly add the alignment column
    # if we are overriding the layout function.
    # ete3/treeview/layouts.py : phylogeny(node)
    if hasattr(node, 'sequence'):
        seq_face = SequenceFace(node.sequence, seqtype='nt', fsize=13)
        seq_face.margin_left = 4
        add_face_to_node(seq_face, node, column=1, aligned=True)

ts.layout_fn = my_layout

t.render('treefig.png', tree_style=ts)
# 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)
        concord_text = faces.TextFace(str(int(concord_dict[mynode.name]))+'   ',fsize=20)
        conflict_text = faces.TextFace(str(int(conflict_dict[mynode.name]))+'   ',fsize=20)
        
        faces.add_face_to_node(concord_text,mynode,0,position = "branch-top")
        faces.add_face_to_node(conflict_text,mynode,0,position="branch-bottom")
        
        
    else:
        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)
Esempio n. 53
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
Esempio n. 54
0
                           >Chimp
                           HARWLNEKLRCELRTLKKLGLDGYKAVSQYVKGRA
                           >Orangutan
                           DARWINEKLRCVSRTLKKLGLDGYKGVSQYVKGRP
                           >Human
                           DARWHNVKLRCELRTLKKLGLVGFKAVSQFVIRRA
                           """)
    nt_sequences = {"Human"    : "GACGCACGGTGGCACAACGTAAAATTAAGATGTGAATTGAGAACTCTGAAAAAATTGGGACTGGTCGGCTTCAAGGCAGTAAGTCAATTCGTAATACGTCGTGCG",
                    "Chimp"    : "CACGCCCGATGGCTCAACGAAAAGTTAAGATGCGAATTGAGAACTCTGAAAAAATTGGGACTGGACGGCTACAAGGCAGTAAGTCAGTACGTTAAAGGTCGTGCG",
                    "Orangutan": "GATGCACGCTGGATCAACGAAAAGTTAAGATGCGTATCGAGAACTCTGAAAAAATTGGGACTGGACGGCTACAAGGGAGTAAGTCAATACGTTAAAGGTCGTCCG"
                }
    for l in nt_sequences:
        (tree & l).nt_sequence = nt_sequences[l]
    tree.dist = 0
    ts = TreeStyle()
    ts.title.add_face(TextFace("Example for nucleotides...", fsize=15), column=0)
    ts.layout_fn = test_layout_evol
    tree.show(tree_style=ts)

    # Show very large algs
    tree = PhyloTree('(Orangutan,Human,Chimp);')
    tree.link_to_alignment(">Human\n"       + ''.join([_aabgcolors.keys()[int(random() * len (_aabgcolors))] for _ in xrange (5000)]) + \
                           "\n>Chimp\n"     + ''.join([_aabgcolors.keys()[int(random() * len (_aabgcolors))] for _ in xrange (5000)]) + \
                           "\n>Orangutan\n" + ''.join([_aabgcolors.keys()[int(random() * len (_aabgcolors))] for _ in xrange (5000)]))
    tree.dist = 0
    ts = TreeStyle()
    ts.title.add_face(TextFace("better not set interactivity if alg is very large", fsize=15), column=0)
    ts.layout_fn = test_layout_phylo_aa

    tree.show(tree_style=ts)
Esempio n. 55
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)
Esempio n. 56
0
    # If node is internal
    else:
        # If silhouette is good, creates a green bubble
        if node.silhouette>0:
            validationFace = TextFace("Silh=%0.2f" %node.silhouette,
                                      "Verdana", 10, "#056600")
            node.img_style["fgcolor"]="#056600"
        # Otherwise, use red bubbles
        else:
            validationFace = TextFace("Silh=%0.2f" %node.silhouette,
                                      "Verdana", 10, "#940000")
            node.img_style["fgcolor"]="#940000"

        # Sets node size proportional to the silhouette value.
        node.img_style["shape"]="sphere"
        if node.silhouette<=1 and node.silhouette>=-1:
            node.img_style["size"]= 15+int((abs(node.silhouette)*10)**2)

        # If node is very internal, draw also a bar diagram
        # with the average expression of the partition
        add_face_to_node(validationFace, node, 0)
        if len(node)>100:
            add_face_to_node(cbarsFace, node, 1)

# Use my layout to visualize the tree
ts = TreeStyle()
ts.layout_fn = mylayout
t.children[0].show(tree_style=ts)