Beispiel #1
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
Beispiel #2
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
Beispiel #3
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)
Beispiel #4
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
 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
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
Beispiel #7
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
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
Beispiel #9
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)
Beispiel #10
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
Beispiel #11
0
def drawTree(treeFile, ShowBool):
	"""
	Draw a tree from a phy file
	"""
	t = Tree(treeFile)
	imgFile = treeFile.replace(".tree", ".tree.png")

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

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

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


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

	# Applies the same static style to all nodes in the tree. Note that,
	# if "nstyle" is modified, changes will affect to all nodes
	for n in t.traverse():
		if n.is_leaf():
			if n.name.split("|")[-1] == "GI":
				n.set_style(nstyle)
			if n.name.split("|")[-1] == "plasmid":
				n.set_style(nstyle2)
			gi = n.name.split("|")[1]
			n.name = n.name.split("|")[0] #+ "   " + n.name.split("|")[1]
			n.name = n.name.replace("_tRNA_modification_GTPase_", "")
			n.name = n.name.replace("_DNA", "")
			n.name = " " + n.name + " "
			if n.name[-1] == "_": n.name.rstrip()
			
			taxon, color = taxonToColour(gi)
			n.add_face(TextFace(taxon, fgcolor = color, fsize = 8), column=1, position="branch-right")
			#n.img_style["bgcolor"] = color
			
	if ShowBool == True: #permet de flipper les braches pour avoir des topologies similaires
		t.show(tree_style=ts)
	t.render(imgFile, w=393, units="mm", tree_style=ts)
Beispiel #12
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
Beispiel #13
0
def argument(name):
    g.name = name
    argument_file = "static/inputs/%s.txt" % name
    g.argument_tree = "/static/outputs/%s.png" % name
    argument_tree = "static/outputs/%s.png" % name

    try:
        f = open(argument_file)  # open the file
    except:
        abort(404)

    g.premises = []
    g.conclusion = None

    for line in f:
        g.premises.append(line.strip())
    g.conclusion = g.premises[-1]
    g.premises = g.premises[:-1]

    stmt_set = main.open_argument(argument_file)
    print stmt_set
    g.sat, tree = satisfiable.satisfiable(stmt_set)

    existing = os.listdir("static/outputs")
    for f in existing:
        if f == name + ".png":
            return render_template("argument.html")

    # set teh tree style...
    ts = TreeStyle()
    # don't show the name of the leaf nodes (which are just a x/o for a open/closed branch) in the final graph
    ts.show_leaf_name = False

    for child in tree.traverse():
        # add a marker with the name of each node, at each node
        child.add_face(TextFace(child.name), column=0, position="branch-top")

    # render the file and save it
    tree.render(argument_tree, tree_style=ts, w=5000)

    # crop out the unwanted part of the image...
    im = Image.open(argument_tree)
    (x, y) = im.size

    draw = ImageDraw.Draw(im)
    draw.rectangle((0, y*.5, x*.25, y), fill="white")
    im.save(argument_tree, "PNG")

    return render_template("argument.html")
Beispiel #14
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
Beispiel #15
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)
Beispiel #16
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()
Beispiel #17
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
Beispiel #18
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
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
def get_tree_style():
    ts = TreeStyle()
    # ts.mode = 'c'
    ts.margin_top = 10
    ts.margin_bottom = 10
    ts.margin_left = 10
    ts.margin_right = 10
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.show_scale = False
    title = TextFace("     Tax Assignment Tree", fsize=10)
    title.hz_align = 2
    title.vt_align = 2
    ts.title.add_face(TextFace(" "), column=0)
    ts.title.add_face(TextFace(" "), column=0)
    ts.title.add_face(title, column=0)
    return ts
Beispiel #21
0
def newick_to_linkage(filePath):
    """ converts newick tree to scipy linkage matrix """
    tree                   = ClusterTree(filePath)
    leaves                 = tree.get_leaf_names()
    ts                     = TreeStyle()
    ts.show_leaf_name      = True
    ts.show_branch_length  = True
    ts.show_branch_support = True

    idx_dict = {}
    idx = 0
    for leaf in leaves:
        idx_dict[leaf] = idx
        idx += 1

    idx_labels = [idx_dict.keys()[idx_dict.values().index(i)] for i in range(len(idx_dict))]

    dmat = np.zeros((len(leaves), len(leaves))) # FIXME need to understand

    for leaf1, leaf2 in combinations(leaves, 2):
        d = tree.get_distance(leaf1, leaf2)
        dmat[idx_dict[leaf1], idx_dict[leaf2]] = dmat[idx_dict[leaf2], idx_dict[leaf1]] = d

    schlink = sch.linkage(scipy.spatial.distance.squareform(dmat),method='average',metric='euclidean')
Beispiel #22
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)	
Beispiel #23
0
def runcode():

    stringArray = [
        "CGTGAATTCAT", "GACTTAC", "GATAGCTACTTAC", "GACCCTTTATAC", "GACTTGGGAC"
    ]

    sM = similarityMatrix(stringArray)

    score = getSimilarity(sM, 2, 3)
    #matrix2CSV( sM, "similarityMatrix.csv")

    print score

    #t = Tree( "((a,b),c);" )
    #t = Tree("(Bovine:0.69395,(Gibbon:0.36079,(Orang:0.33636,(Gorilla:0.17147,(Chimp:0.19268, Human:0.11927):0.08386):0.06124):0.15057):0.54939,Mouse:1.21460):0.10;")
    ourStr = mytest()
    ourStr += ";"

    t = Tree(ourStr)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = True
    #ts.show_branch_support = True
    t.show(tree_style=ts)
def make_png(t, bad_nodes, png_name, outgroups=None):
    for n in t.traverse():
        n.img_style["size"] = 0
        if n in bad_nodes:
            nstyle = NodeStyle()
            nstyle["hz_line_color"] = "red"
            nstyle["hz_line_width"] = 3
            n.set_style(nstyle)
        if n.is_leaf():
            if outgroups:
                if n.name in outgroups:
                    name_face = TextFace(n.name, fgcolor="blue")
                else:
                    name_face = TextFace(n.name, fgcolor="black")
            else:
                name_face = TextFace(n.name, fgcolor="black")
            n.add_face(name_face, 0, "branch-right")

    if len(bad_nodes) > 0:
        ts = TreeStyle()
        ts.show_leaf_name = False
        gene_name = png_name
        ts.title.add_face(TextFace(gene_name, fsize=15, bold=True), 0)
        my_png = t.render(png_name, tree_style=ts)
Beispiel #25
0
def render_tree(T, out):
    from ete3 import TreeStyle

    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)
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
Beispiel #27
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
Beispiel #28
0
def CreatePhyloGeneticTree(inputfile, outputfile, size):
    f = open(inputfile, "r")
    data = f.readlines()[0]
    f.close()
    tree = Tree(data)
    tree.set_outgroup(tree.get_midpoint_outgroup())
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = False
    ts.show_branch_support = False
    ts.optimal_scale_level = "mid"
    t = tree.render(str(outputfile), w=size, units="px", tree_style=None)
Beispiel #29
0
def main(argv):  

    
    
    t = Tree(argv[1])
    save=int(argv[2])
    ts=TreeStyle()
    
    # ts.tree_width = 50
    #t.show(tree_style=ts)
    if(save==1):
        if os.path.exists("crud/static/crud/Tree1.png"):
             os.remove("crud/static/crud/Tree1.png")
        t.render("crud/static/crud/Tree1.png", tree_style=ts)
    else:
        if os.path.exists("crud/static/crud/Tree2.png"):
             os.remove("crud/static/crud/Tree2.png")
        t.render("crud/static/crud/Tree2.png", tree_style=ts)
Beispiel #30
0
def make_tree_figure(nw_file):
    ## build tree ##
    nw_format = open(nw_file)
    nw_read = nw_format.read()
    nw_format.close()
    print(nw_read)
    t = Tree(nw_read, format=1)
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_scale = False
    ts.show_leaf_name = False
    ts.show_scale = False
    t.render("label_tree.png", my_layout, tree_style=ts, dpi=150, w=600)
 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
Beispiel #32
0
 def on_actionOpen_triggered(self):
     d = QtGui.QFileDialog()
     d._conf = _open_newick.Ui_OpenNewick()
     d._conf.setupUi(d)
     d.exec_()
     return
     fname = QtGui.QFileDialog.getOpenFileName(
         self,
         "Open File",
         "/home",
     )
     try:
         t = Tree(str(fname))
     except Exception as e:
         print(e)
     else:
         self.scene.tree = t
         self.img = TreeStyle()
         self.redraw()
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)
Beispiel #34
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)
Beispiel #35
0
def get_example_tree():
    t = Tree("((a,b),c);")

    right_c0_r0 = TextFace("right_col0_row0")
    right_c0_r1 = TextFace("right_col0_row1")
    right_c1_r0 = TextFace("right_col1_row0")
    right_c1_r1 = TextFace("right_col1_row1")
    right_c1_r2 = TextFace("right_col1_row2")

    top_c0_r0 = TextFace("top_col0_row0")
    top_c0_r1 = TextFace("top_col0_row1")

    bottom_c0_r0 = TextFace("bottom_col0_row0")
    bottom_c1_r0 = TextFace("bottom_col1_row0")

    aligned_c0_r0 = TextFace("aligned_col0_row0")
    aligned_c0_r1 = TextFace("aligned_col0_row1")

    aligned_c1_r0 = TextFace("aligned_col1_row0")
    aligned_c1_r1 = TextFace("aligned_col1_row1")

    t.add_face(right_c0_r1, column=1, position="branch-right")
    t.add_face(right_c0_r0, column=0, position="branch-right")

    t.add_face(right_c1_r2, column=2, position="branch-right")
    t.add_face(right_c1_r1, column=1, position="branch-right")
    t.add_face(right_c1_r0, column=0, position="branch-right")

    t.add_face(top_c0_r1, column=1, position="branch-top")
    t.add_face(top_c0_r0, column=0, position="branch-top")

    t.add_face(bottom_c0_r0, column=0, position="branch-bottom")
    t.add_face(bottom_c1_r0, column=1, position="branch-bottom")

    for leaf in t.iter_leaves():
        leaf.add_face(aligned_c0_r1, 0, "aligned")
        leaf.add_face(aligned_c0_r0, 0, "aligned")
        leaf.add_face(aligned_c1_r1, 0, "aligned")
        leaf.add_face(aligned_c1_r0, 0, "aligned")

    return t, TreeStyle()
Beispiel #36
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)
Beispiel #37
0
def network_size_view(tree, orthologous_groups, save_dir):
    # Set the size of each node
    for node in tree.traverse():
        # Count the number of genes likely to be regulated in this node
        num_regulated = len([
            grp for grp in orthologous_groups
            if grp.most_likely_state_at(node.name) == '1'
        ])
        nstyle = NodeStyle()
        nstyle['size'] = 0
        node.set_style(nstyle)
        circle_face = CircleFace(radius=num_regulated,
                                 color='green',
                                 style='sphere',
                                 label={
                                     'text': str(num_regulated),
                                     'color': 'black'
                                 })
        node.add_face(circle_face, column=2)
    ts = TreeStyle()
    tree.render(os.path.join(save_dir, 'network_size.svg'), tree_style=ts)
Beispiel #38
0
def view_by_gene(tree, orthologous_grp, save_file):
    # Make a copy of the tree
    tree = copy.deepcopy(tree)
    for node in tree.traverse():
        percents = [orthologous_grp.regulation_states[(node.name, s)] * 100
                    for s in ['1', '0', 'A']]
        stacked_bar_face = StackedBarFace(percents, width=30, height=15,
                                          colors=['green', 'red', 'blue'])
        stacked_bar_face.margin_left = 5
        stacked_bar_face.margin_right = 5
        node.add_face(stacked_bar_face, column=1)
        # Add locus tag if the genome has the gene from this orthologous group
        if node.is_leaf():
            # Check if the orthologous group contains any gene of the genome
            gene = orthologous_grp.member_from_genome(node.name)
            if gene:
                node.add_face(TextFace(text='[%s]' % gene.locus_tag), column=2)

    ts = TreeStyle()
    ts.title.add_face(TextFace(text=orthologous_grp.description), column=1)
    tree.render(save_file, tree_style=ts)
Beispiel #39
0
def get_tree_shape(newick, graph, lower_threshold, higher_threshold):
    t = Tree(newick, format=8)
    for n in t.traverse():
        nstyle = NodeStyle()
        nstyle["fgcolor"] = "yellow"
        name = newick_to_name(n.name)
        if name != '':
            if graph.nodes[name]["val"] > higher_threshold:
                nstyle["fgcolor"] = "green"
            elif graph.nodes[name]["val"] < lower_threshold:
                nstyle["fgcolor"] = "red"
        nstyle["size"] = 5
        n.set_style(nstyle)
    ts = TreeStyle()
    ts.show_leaf_name = True
    ts.show_branch_length = False
    ts.min_leaf_separation = 0.5
    ts.mode = "c"
    ts.root_opening_factor = 0.75
    return t, ts
Beispiel #40
0
def writeTrees(trees, label):
    """
    Now that we have branch lengths, write out new Newick trees with the
    branch lengths included.  Note that ete3 does not seem to write out
    the length of the root automatically, so we add it in by hand.
    """
    ts = TreeStyle()
    ts.show_leaf_name = False
    ts.show_branch_length = False
    ts.branch_vertical_margin = 20
    ts.scale = 0.05
    outtrees = open(lengthdir + label + ".newick", "w")
    for index, tree in enumerate(trees):
        #print(tree)
        #If needed:  round the branch lengths
        #        for branch in tree.traverse():
        #            branch.dist = round(branch.dist)
        line = tree.write(format=1)
        rootlen = round(tree.get_tree_root().dist)
        line = line[:-1] + ":" + str(rootlen) + ";"
        outtrees.write(line + "\n")
        if (showTrees):
            for branch in tree.traverse():
                if branch.name != "":
                    name_face = AttrFace("name", fsize=30)
                    branch.add_face(name_face,
                                    column=0,
                                    position="branch-right")
                if branch.dist != 0:
                    if branch.name == "":
                        text_face = TextFace(str(round(branch.dist, 2)),
                                             fsize=30)
                        branch.add_face(text_face,
                                        column=1,
                                        position="branch-top")
                else:
                    print("Branch found of length zero but not a tip in tree",
                          label)
                    print(branch)
            filename = label
            if len(trees) > 1:
                filename += "_" + str(index)
            filename += ".png"
            tree.render(lengthdir + filename, tree_style=ts)
            #foo()
    outtrees.close()
Beispiel #41
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
def set_tree_style():
    ts = TreeStyle()
    ts.legend.add_face(CircleFace(10, "red"), column=0)
    ts.legend.add_face(CircleFace(10, "lime"), column=0)
    ts.legend.add_face(CircleFace(10, "cyan"), column=0)
    ts.legend.add_face(CircleFace(10, "plum"), column=0)
    ts.legend.add_face(CircleFace(10, "lightsalmon"), column=0)
    ts.legend.add_face(CircleFace(10, "indigo"), column=0)
    ts.legend.add_face(CircleFace(10, "royalblue"), column=0)
    ts.legend.add_face(CircleFace(10, "olive"), column=0)

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

    return ts
Beispiel #43
0
    def __init__(self, root_text):
        # Inicializa la estructura árbol
        tree = Tree()

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

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

        # Almacenamos la raíz del árbol como nodo actual
        self.curr_node = self.tree
    def draw(self,
             file,
             colors,
             color_internal_nodes=True,
             legend_labels=(),
             show_branch_support=True,
             show_scale=True,
             legend_scale=1,
             mode="c"):
        max_color = len(colors)

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

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

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

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

        # self.tree.render("ete_tree.pdf", dpi=300, tree_style=ts)
        self.tree.render(file, w=1000, tree_style=ts)
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
Beispiel #46
0
    def treeLayout(self):
        # Add a tree style and a legend

        self.ts = TreeStyle()
        self.ts.show_scale = False
        self.ts.show_leaf_name = False
        self.ts.extra_branch_line_type = 0
        self.ts.extra_branch_line_color = 'black'
        self.ts.layout_fn = self.layout
        self.ts.branch_vertical_margin = -10

        self.ts.legend_position = 4

        self.ts.legend.add_face(TextFace(
            datetime.now().strftime('%a, %d.%m.%Y; %H:%M:%S'), fsize=8),
                                column=1)
        self.ts.legend.add_face(TextFace('Tree: ' + self.treefile, fsize=8),
                                column=1)
        self.ts.legend.add_face(TextFace('Pruning: ' + self.prune, fsize=8),
                                column=1)

        # Order the graphical tree output from highly branched nodes on top and less branched nodes to the bottom
        self.t.ladderize(1)
Beispiel #47
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)
Beispiel #48
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)
Beispiel #49
0
    def treeLayout(self):
        # Add a tree style and a legend

        self.ts = TreeStyle()
        self.ts.show_scale = False
        self.ts.show_leaf_name = False
        self.ts.extra_branch_line_type = 0
        self.ts.extra_branch_line_color = 'black'
        self.ts.layout_fn = self.layout
        self.ts.branch_vertical_margin = -10

        self.ts.legend_position = 4

        for feature, color in zip(sorted(self.featurenames.keys()),
                                  self.colors):
            self.ts.legend.add_face(CircleFace(10, color), column=0)
            self.ts.legend.add_face(TextFace(self.featurenames[feature]),
                                    column=1)

        if self.empty:
            self.ts.legend.add_face(CircleFace(10, self.colors[-1]), column=0)
            self.ts.legend.add_face(TextFace('none'), column=1)

        self.ts.legend.add_face(TextFace(
            datetime.now().strftime('%a, %d.%m.%Y; %H:%M:%S'), fsize=8),
                                column=1)
        self.ts.legend.add_face(TextFace('Tree: ' + self.treefile, fsize=8),
                                column=1)
        self.ts.legend.add_face(TextFace('Clusters: ' + self.loadfile,
                                         fsize=8),
                                column=1)
        self.ts.legend.add_face(TextFace('Pruning: ' + self.prune, fsize=8),
                                column=1)

        # Order the graphical tree output from highly branched nodes on top and less branched nodes to the bottom
        self.t.ladderize(1)
Beispiel #50
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)
def tree_layout(tree_file, ps_node_list):
    t = EvolTree(tree_file, format=0)
    style_other = NodeStyle()
    style_other['size'] = 6
    style_ps = NodeStyle()
    style_ps['fgcolor'] = '#ff0000'
    style_ps['size'] = 6
    for node in t.iter_descendants():
        descendant = t.get_descendant_by_node_id(node.node_id)
        if node.node_id in ps_node_list:
            descendant.img_style = style_ps
        else:
            descendant.img_style = style_other
    ts = TreeStyle()
    ts.layout_fn = layout
    ts.show_branch_support = False
    ts.show_branch_length = False
    ts.show_leaf_name = False
    result_picture = os.path.join(output_dir, 'positive_selection_tree.png')
    t.render(result_picture, tree_style=ts)
Beispiel #52
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
Beispiel #53
0
metadata = get_meta_new(metadata, big_tree)
colourDict = get_colours(clusters, big_tree, colours)

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

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

# add legend
for each in colourDict.keys():
    ts.legend.add_face(CircleFace(radius=size[mode] / 2, color=colourDict[each]), column=0)
    ts.legend.add_face(TextFace(each, ftype="Helvetica", fsize=size[mode]), column=1)
ts.legend.add_face(CircleFace(radius=size[mode] / 2, color="#F1F1F1"), column=0)
ts.legend.add_face(TextFace("Guinea", ftype="Helvetica", fsize=size[mode]), column=1)
ts.legend.add_face(RectFace(width=size[mode], height=size[mode], bgcolor="#D3D3D3", fgcolor="#FFFFFF"), column=0)
ts.legend.add_face(TextFace("Sierra Leone", ftype="Helvetica", fsize=size[mode]), column=1)
ts.legend.add_face(
Beispiel #54
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)
from ete3 import Tree,TreeStyle,NodeStyle
import os
for tree in [file for file in os.listdir('.') if file and file.endswith('_phyml_tree.txt')]:
    #print tree
    try:
        with open( tree, 'r') as f:  # FIXME boot_trees verus phyml_tree
            t = Tree(open(tree,'r').read())
            ts = TreeStyle()
            ns = NodeStyle()
            ns['size']=0
            ts.show_leaf_name = True
            ts.show_branch_length = False
            ts.show_branch_support = True
            for n in t.traverse():
                n.set_style(ns)
            #t.show(tree_style=ts)
            t.render( os.getcwd()+'/'+tree.replace('_phyml_tree.txt', '.png'),tree_style = ts)
    except:
        pass
Beispiel #56
0
#!/usr/bin/python
#figure IES loss
from __future__ import print_function
from ete3 import Tree, NodeStyle, TreeStyle
from pyies.userOptions import basePath
import os.path
import string

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

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

# for leaf in t:
#     geneId = leaf.name
#     seq = seqs.get_seq(geneId)
#     seq = seq.translate(None, string.ascii_lowercase) # keep only CDS
#     #iesmotif = [[1, len(seq), "line", 2, 5, None, None, None]]
#     #seqFace = SeqMotifFace(seq = seq, gap_format = "blank", seq_format = "line")
#     seqFace = SequenceFace(seq, seqtype = 'dna')
Beispiel #57
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)
Beispiel #58
0
                        [6,5,7,3],
                        [7,5,7,3]], 
                        dtype=np.int16)
                        

#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
#######################'''
@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():
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)