def render_tree(sk_tree, tip_hues, tip_lums, saturation=0.9, output_fp=None, supress_display=False): ete_tree = Tree(str(sk_tree)) tree_tips = [x.name for x in sk_tree.tips()] for ete_leaf in ete_tree.iter_leaves(): if (ete_leaf.name not in tree_tips) and (ete_leaf.name[1:-1] in tree_tips): ete_leaf.name = ete_leaf.name[1:-1] elif ete_leaf.name not in tree_tips: print 'leaf {0} in ete-parsed tree not found in skbio tree {1}'.format(ete_leaf.name,str(sk_tree.ascii_art())) raise KeyError for n in ete_tree.traverse(): if n.is_leaf(): hex_color = hls_to_rgb_hex(tip_hues[n.name], tip_lums[n.name], saturation) n.add_features(tip_color=hex_color) style = NodeStyle() style["size"] = 0 for l in ete_tree.traverse(): l.set_style(style) ts = TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False if output_fp: ete_tree.render(output_fp, tree_style = ts) if not supress_display: ete_tree.show(tree_style = ts) return
def draw_tree(tree, file): root = tree.get_midpoint_outgroup() try: tree.set_outgroup(root) except: pass root = tree.get_tree_root() root.dist = 0 add_sig(tree) ts = TreeStyle() ts.branch_vertical_margin = 1 #ts.scale = 1500 ts.show_leaf_name = False #ts.show_branch_support = True leg_file = path.join(path.expanduser('~'), 'Perl', 'Modules', 'TreeLegend.png') leg_face= ImgFace(img_file=leg_file) leg_face.margin_left, leg_face.margin_top = 5, 5 ts.legend.add_face(leg_face, column=1) ts.legend_position=1 title_face = TextFace(text=file.split('.')[0]) title_face.margin_left, title_face.margin_top = 10, 5 ts.title.add_face(title_face, column=1) (ts.margin_left, ts.margin_right) = (5,5) tree.render(file, tree_style=ts, w=6000, units='mm')
def showTreeInGrid(gid,biome,grid_level=14,taxonomic_level='sp'): """ Performs a selection, spatial filter and returns an image. grid_level is the grid layer. taxonomic_level is the taxonomic level to be shown. Options are: sp, gns, fam, ord, cls, phy, king """ mesh = initMesh(grid_level) try: cell = mesh.objects.get(id=id) except: logger.error("Selected id does not exist in selected grid") return None gb=GriddedTaxonomy(biome,cell,generate_tree_now=True) forest = gb.taxonomies[0].forest ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 forest[taxonomic_level].show(tree_style=ts) return 'Parece que se tiene que ver algo'
def render_annotate(newick_path, output_path): """Render the annotated tree, showing internal node names. The output_path should end in .PNG, .PDF or .SVG: this will determine the format. To aid in testing, if output_path is None, the tree is shown rather than rendered. """ tree = Tree(newick_path, format=1) ts = TreeStyle() ts.show_leaf_name = True ts.branch_vertical_margin = 15 ns = NodeStyle() ns["size"] = 1 edge = 0 for node in tree.traverse(): node.name = node.name.replace("'", "") node.name = node.name.replace("+", ",") if not node.is_leaf() and node.name != 'NoName': f = TextFace(node.name) f.margin_top = 5 f.margin_bottom = 5 f.margin_right = 10 f.margin_left = 10 edge += 1 node.add_face(f, column=0, position="branch-top") if output_path is None: tree.show(tree_style=ts) else: tree.render(output_path)
def showTreeWithPictures(tree = None, alignment=None, branchLengths=True, bootstrapSupport=True, tolabel=None): print("ShowTreeWithPictures",tree, alignment, branchLengths,bootstrapSupport, tolabel) if alignment: t = EvolTree(tree, alignment,alg_format="paml") t.link_to_alignment(alignment,alg_format="paml") else: t = EvolTree(tree) nsFG = NodeStyle() nsFG["fgcolor"] = "darkgreen" nsFG["size"] = 8 for node in t.traverse(): print(node.node_id) if tolabel: if str(node.node_id) in tolabel: node.set_style(nsFG) ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = branchLengths ts.show_branch_support = bootstrapSupport out = FILE if branchLengths: out+="_Len" if bootstrapSupport: out+="_Boot" t.render(out+"_tree.pdf",tree_style=ts) t.render(out+"_tree.png",tree_style=ts) if INTERACTIVE: t.show(tree_style=ts)
def generateImage(self, tree): ts = TreeStyle() ts.layout_fn = self.__layout__ ts.mode = "c" ts.show_leaf_name = False tree.render(self.treePNGFile, w=1000, tree_style = ts) tree.render(self.treeSVGFile, w=250, tree_style = ts)
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
def print_colored_host_tree(host_tree_fp, host_colors, output_fp, treefmt=5): with open(host_tree_fp) as tree_f: treestring = remove_newick_node_labels(tree_f.readline().strip()) tree = Tree(newick=treestring, format=treefmt) for host in host_colors: if tree.get_leaves_by_name(host) == []: tip = "'%s'" % host else: tip = host node = tree.get_leaves_by_name(tip)[0] node.add_face(AttrFace("name", fsize=14, fgcolor=host_colors[host]), 0) # remove stupid blue circles on nodes style = NodeStyle() style["size"] = 0 for l in tree.traverse(): l.set_style(style) # get rid of default rendered leaf labels ts = TreeStyle() ts.show_leaf_name = False tree.render(output_fp, tree_style = ts) return
def render_annotate(newick_path, output_path): """Render the annotated tree, showing internal node names. The output_path should end in .PNG, .PDF or .SVG: this will determine the format. To aid in testing, if output_path is None, the tree is shown rather than rendered. """ tree = Tree(newick_path, format=1) ts = TreeStyle() ts.show_leaf_name = True ts.branch_vertical_margin = 15 ns = NodeStyle() ns["size"] = 1 edge = 0 for node in tree.traverse(): node.name = node.name.replace("'", "") node.name = node.name.replace("+", ",") if not node.is_leaf() and node.name != "NoName": f = TextFace(node.name) f.margin_top = 5 f.margin_bottom = 5 f.margin_right = 10 f.margin_left = 10 edge += 1 node.add_face(f, column=0, position="branch-top") if output_path is None: tree.show(tree_style=ts) else: tree.render(output_path)
def print_colored_host_tree(host_tree_fp, host_colors, output_fp): tree = Tree(host_tree_fp) for host in host_colors: if tree.get_leaves_by_name(host) == []: tip = "'%s'" % host else: tip = host node = tree.get_leaves_by_name(tip)[0] node.add_face(AttrFace("name", fsize=14, fgcolor=host_colors[host]), 0) # remove stupid blue circles on nodes style = NodeStyle() style["size"] = 0 for l in tree.traverse(): l.set_style(style) # get rid of default rendered leaf labels ts = TreeStyle() ts.show_leaf_name = False tree.render(output_fp, tree_style = ts) return
def visualizeTree(sTreePath, pathToSfamilies, bootValue, width, height): # Random tree stree = Tree() stree = readTreeFromFile(sTreePath) snodesStatDic={} snodesStatDic= getFamiliesStatisticsForEachNode(pathToSfamilies, bootValue) #print snodesStatDic # Some random features in all nodes for n in stree.traverse(): if n.name in snodesStatDic.keys(): total= reduce(lambda x,y: x+y, snodesStatDic[n.name]) #norm= [(x*100)/total for x in snodesStatDic[n.name]] norm= [x for x in snodesStatDic[n.name]] n.add_features(pie_data=norm) # Create an empty TreeStyle ts = TreeStyle() # Set our custom layout function ts.layout_fn=layout # Draw a tree ts.mode = "r" #ts.force_topology= False ts.complete_branch_lines_when_necessary= True # 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 stree, ts
def make_tree(treefile, image_file, clone_info): colour_list = ['MidnightBlue','RoyalBlue', 'LightSkyBlue', 'Aquamarine', 'SpringGreen', 'GreenYellow',\ 'Gold','DarkOrange'] weeks = ['16', '30', '38', '48', '59', '119', '176', '206'] weeks = ['6', '14', '53', '92','144'] t = Tree(treefile,format = 1) ts = TreeStyle() for i in range(5): ts.legend.add_face(CircleFace(20, colour_list[i]), column=0) ts.legend.add_face(TextFace('week' + weeks[i]), column=1) ts.legend_position = 2 ts.show_leaf_name = True ts.branch_vertical_margin = 15 ts.rotation = 90 ns = NodeStyle() ns["size"] = 1 ns.hz_line_width = 10 ns.vt_line_width = 10 edge = 0 for node in t.traverse(): node.name = node.name.replace("'", "") node.name = node.name.replace(".", ",") name = node.name.split(' ')[0] print name if name in clone_info.keys(): style_node(node, colour_list[int(clone_info[name][0])-1], int(int(clone_info[name][1])/10)+5) if not node.is_leaf() and node.name != 'NoName': f = TextFace(node.name) f.margin_top = 2.5 f.margin_bottom = 2.5 f.margin_right = 2.5 f.margin_left = 2.5 node.add_face(f, column=0, position="branch-top") t.render(image_file, tree_style = ts)
def ETETree(seqs, ref, metric): """Tree showing bola alleles covered by tepitope""" from ete2 import Tree,PhyloTree,TreeStyle,NodeStyle aln = Genome.clustalAlignment(seqs=seqs) t = Tree('temp.dnd') #t.set_outgroup(t&ref) ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 ts.arc_span = 180 cutoff=0.25 def func(node): if node.name=='NoName' or not node.name in metric: return False if metric[node.name]<=cutoff: return True matches = filter(func, t.traverse()) print len(matches), "nodes have distance <=%s" %cutoff nst1 = NodeStyle() nst1["bgcolor"] = "Yellow" for n in matches: n.set_style(nst1) nst2 = NodeStyle() nst2["bgcolor"] = "LightGreen" hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles] for n in hlanodes: n.set_style(nst2) t.show(tree_style=ts) return
def show(self, i=0): t = Tree(str(self)+";") ts = TreeStyle() ts.show_leaf_name = True ts.rotation = 90 t.render("mytree-{0}.png".format(i), w=183, units="mm", tree_style=ts) t.show(tree_style=ts)
def print_colored_host_tree(host_tree_fp, host_colors, output_fp, treefmt=5): with open(host_tree_fp) as tree_f: treestring = remove_newick_node_labels(tree_f.readline().strip()) tree = Tree(newick=treestring, format=treefmt) for host in host_colors: if tree.get_leaves_by_name(host) == []: tip = "'%s'" % host else: tip = host node = tree.get_leaves_by_name(tip)[0] node.add_face(AttrFace("name", fsize=14, fgcolor=host_colors[host]), 0) # remove stupid blue circles on nodes style = NodeStyle() style["size"] = 0 for l in tree.traverse(): l.set_style(style) # get rid of default rendered leaf labels ts = TreeStyle() ts.show_leaf_name = False tree.render(output_fp, tree_style=ts) return
def generateImage(self, tree): ts = TreeStyle() ts.layout_fn = self.__layout__ ts.mode = "c" ts.show_leaf_name = False tree.render(self.treePNGFile, w=1000, tree_style=ts) tree.render(self.treeSVGFile, w=250, tree_style=ts)
def build_vis(): ts = TreeStyle() ts.mode = "c" ts.arc_start = 0 # 0 degrees = 3 o'clock ts.arc_span = 360 ts.layout_fn = my_layout # Use custom layout return ts
def print_colored_host_tree(host_tree_fp, host_colors, output_fp): tree = Tree(host_tree_fp) for host in host_colors: if tree.get_leaves_by_name(host) == []: tip = "'%s'" % host else: tip = host node = tree.get_leaves_by_name(tip)[0] node.add_face(AttrFace("name", fsize=14, fgcolor=host_colors[host]), 0) # remove stupid blue circles on nodes style = NodeStyle() style["size"] = 0 for l in tree.traverse(): l.set_style(style) # get rid of default rendered leaf labels ts = TreeStyle() ts.show_leaf_name = False tree.render(output_fp, tree_style=ts) return
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
def constructing_final_tree(distance_matrix, protein_labels): v = str(upgma(distance_matrix, protein_labels)) + ";" t = Tree(v) ts = TreeStyle() ts.show_leaf_name = True t.convert_to_ultrametric() ts.scale = 120 t.show(tree_style=ts)
def constructing_final_tree(distance_matrix, protein_labels): v = str(neighbor_joining(distance_matrix, protein_labels)) + ";" t = Tree(v) t.dist = 0 ts = TreeStyle() ts.mode = "c" ts.show_leaf_name = True ts.layout_fn = my_layout t.show(tree_style=ts)
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() 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
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
def showTreeWithPictures(tree = None, alignment=None, branchLengths=True, bootstrapSupport=True, tolabel=None,showZScores=False,showLogs=False ): print(PICS) print("ShowTreeWithPictures",tree, alignment, branchLengths,bootstrapSupport, tolabel,showZScores,showLogs ) if not alignment: nsFG = NodeStyle() nsFG["fgcolor"] = "darkgreen" nsFG["size"] = 8 t = EvolTree(tree) #todo:label # for node in t.traverse(): print(node.node_id) if tolabel: if str(node.node_id) in tolabel: node.set_style(nsFG) #q'n'd if (node.name.split("_")[0]+".png" in PICS): print(node.name.split("_")[0]+".png") node.add_face(ImgFace(PICDIR+os.sep+node.name.split("_")[0]+".png", height=50), column=1, position="aligned") #non GRZM identifier elif (node.name+".png" in PICS): print(node.name+".png") node.add_face(ImgFace(PICDIR+os.sep+node.name+".png", height=50), column=1, position="aligned") ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = branchLengths ts.show_branch_support = bootstrapSupport out = FILE if branchLengths: out+="_Len" if bootstrapSupport: out+="_Boot" if Z: out+="_Z" if L: out+="_L" t.render(out+"_tree.pdf",tree_style=ts) t.render(out+"_tree.png",tree_style=ts) if INTERACTIVE: t.show(tree_style=ts) else: t = EvolTree(tree, alignment,alg_format="paml") t.link_to_alignment(alignment,alg_format="paml") #todo label #todo check treestyle #ts = TreeStyle() #ts.show_leaf_name = True #ts.show_branch_length = branchLength #ts.show_branch_support = bootstrapSupport t.show()
def draw_tree(tree, file): ts = TreeStyle() ts.branch_vertical_margin = 1 ts.show_leaf_name = False if '.svg' in file: ts.scale = 3000 tree.render(file, tree_style=ts, h=300, units='mm') else: ts.scale = 1500 tree.render(file, tree_style=ts, w=3000, units='mm')
def main(argv): print argv br = mechanize.Browser() directoryhtml = br.open(argv) t_soup = BeautifulSoup(directoryhtml.read()) t_tables = t_soup.findAll('table',{"id":"people"}) t_tbody = t_tables[0].findAll('tbody') t_trs = t_tbody[0].findAll('tr') for t_tr in t_trs: t_tds = t_tr.findAll('td') username = t_tds[0].find('a').find(text=True) email = t_tds[1].find('p').find(text=True) department = t_tds[2].find('p').find(text=True) title = t_tds[3].find('p').find(text=True) manager = t_tds[4].find('p').find(text=True) skypeid = t_tds[5].find('p').find(text=True) username_list.append(username) email_list.append(email[:email.find("@")]) manager_list.append(manager) #Get the root manager rootname = getRootName() #Make the tree variable treeStr = getTree(rootname, "(", ")" + rootname + ";") treeStr = treeStr.replace("(,", "(") treeStr = treeStr.replace(",)", ")") treeStr = treeStr.replace(",,", ",") ts = TreeStyle() # Do not add leaf names automatically ts.show_leaf_name = False ts.show_branch_length = False ts.show_scale = False # Use my custom layout ts.layout_fn = my_layout t = Tree(treeStr, format=8) for n in t.traverse(): nstyle = NodeStyle() nstyle["fgcolor"] = "red" nstyle["size"] = 15 n.set_style(nstyle) count = 0 addNodeCount(t, 0) #t.add_face(TextFace(str(addNodeCount(t, 0))), column=1, position = "branch-bottom") # Tell ETE to use your custom Tree Style t.show(tree_style=ts) t.render("tree_structure.png", w=183, units="mm")
def _on_Button2_ButRel_1(self,Event=None): from ete2 import Tree from ete2 import TreeStyle players = int(float(self._Entry2.get())) timer = int(float(self._Entry1.get())) tree = MinMax(players, timer) ts = TreeStyle() ts.rotation=270 ts.show_leaf_name=True t = Tree(newick='('+tree.head.getKids('Start')+');', format=0) t.render(file_name="MysteryBox.svg",tree_style=ts)
def taxo_msa(outfile='taxo_msa.svg',taxids=[],annotation='',msa=[],title='',width=2000): """ Visualize MSA together with a taxonomy tree taxids - list of taxids in the same order as seqs in msa """ # taxid2gi={f_df.loc[f_df.gi==int(gi),'taxid'].values[0]:gi for gi in list(f_df['gi'])} # gi2variant={gi:f_df.loc[f_df.gi==int(gi),'hist_var'].values[0] for gi in list(f_df['gi'])} # msa_dict={i.id:i.seq for i in msa_tr} ncbi = NCBITaxa() taxids=map(int,taxids) t = ncbi.get_topology(taxids,intermediate_nodes=False) a=t.add_child(name='annotation') a.add_feature('sci_name','annotation') t.sort_descendants(attr='sci_name') ts = TreeStyle() def layout(node): # print node.rank # print node.sci_name if getattr(node, "rank", None): if(node.rank in ['order','class','phylum','kingdom']): rank_face = AttrFace("sci_name", fsize=7, fgcolor="indianred") node.add_face(rank_face, column=0, position="branch-top") if node.is_leaf(): sciname_face = AttrFace("sci_name", fsize=9, fgcolor="steelblue") node.add_face(sciname_face, column=0, position="branch-right") if node.is_leaf() and not node.name=='annotation': s=str(msa[taxids.index(int(node.name))].seq) seqFace = SeqMotifFace(s,[[0,len(s), "seq", 10, 10, None, None, None]],scale_factor=1) add_face_to_node(seqFace, node, 0, position="aligned") # gi=taxid2gi[int(node.name)] add_face_to_node(TextFace(' '+msa[taxids.index(int(node.name))].id),node,column=1, position = "aligned") # add_face_to_node(TextFace(' '+str(int(node.name))+' '),node,column=2, position = "aligned") # add_face_to_node(TextFace(' '+str(gi2variant[gi])+' '),node,column=3, position = "aligned") if node.is_leaf() and node.name=='annotation': if(annotation): s=annotation # get_hist_ss_in_aln_as_string(msa_tr) else: s=' '*len(msa[0].seq) seqFace = SeqMotifFace(s,[[0,len(s), "seq", 10, 10, None, None, None]],scale_factor=1) add_face_to_node(seqFace, node, 0, position="aligned") add_face_to_node(TextFace(' '+'SEQ_ID'),node,column=1, position = "aligned") # add_face_to_node(TextFace(' '+'NCBI_TAXID'+' '),node,column=2, position = "aligned") # add_face_to_node(TextFace(' '+'Variant'+' '),node,column=3, position = "aligned") ts.layout_fn = layout ts.show_leaf_name = False ts.title.add_face(TextFace(title, fsize=20), column=0) t.render(outfile, w=width, dpi=300, tree_style=ts)
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
def prettifyTree(ete_tree, leaf_font_size=32, branch_support_size=20, show_bootstraps=True, title=None, ts=None): ''' Perform standardized functions to make the ETE trees easier to read: - Make the branch support bigger - Make the leaf fonts bigger - Turn off elongating branches for visualization purposes (i.e. make sure the real branch lengths are represented) - Change both to standard font (Times) - Standardize the tree's width (calculate based on the maximum length from the root to a tip) - (optional) add title to tree ''' for node in ete_tree.traverse(): if node.is_leaf(): # Make text faces with name = the existing node name but with big font. # A side effect of this is that we also get the annotations lined up F = faces.TextFace(node.name, ftype="Times", fsize=leaf_font_size) node.add_face(F, 0, position="aligned") else: if show_bootstraps: # Make branch support bigger F = faces.TextFace(node._support, ftype="Times", fsize=branch_support_size) node.add_face(F, 0, position="branch-top") #correct the long root node bug (fixed in next release) ete_tree.dist = 0 # Optionally create a new TreeStyle if we are not passing in an old one. if ts is None: ts = TreeStyle() # This "fixes" the dashed line issue but makes the tree look terrible. # There may be no way around this (and it's likely other tree viewers do the same thing # but just don't tell you). #ts.optimal_scale_level = "full" # We made these bigger so lets turn off the default ones too. ts.show_branch_support = False ts.show_leaf_name = False if title is not None: ts.title.clear() title = TextFace(title) title.hz_align = True title.fsize = 52 ts.title.add_face(title, 0) return ete_tree, ts
def load_tree(f_tree, f_align): # Tree style ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = True ts.show_branch_support = True ts.branch_vertical_margin = 10 # Load phylogenetic tree tree = PhyloTree(f_tree.read()) if f_align is not None: tree.link_to_alignment(f_align.read()) return tree, ts
def drawTree(nwfile, outfile): from ete2 import Tree, TreeStyle, TextFace ts = TreeStyle() ts.show_leaf_name = False ts.layout_fn = my_layout ts.branch_vertical_margin = 12.75 ts.orientation = 1 titleFace = TextFace("Phylogenetic Tree", fsize=18, fgcolor="white") titleFace.margin_top = 15 ts.title.add_face(titleFace, column=1) t = Tree(nwfile) t.render(outfile, tree_style=ts)
def draw_ete2_tree(organism, snplist, tree_file_name, config, c): '''Draws a phylogenetic tree using ETE2 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 for snp in snplist: if n.name == snp[0]: if snp[1] == snp[3]: # If the SNP is Derived in snplist, # change appearance of node 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 elif snp[3] == "-": # 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 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 = 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, w=tree_depth * 500)
def ete_tree(self, labels=None): if sys.version_info[0] == 2: from ete2 import Tree, NodeStyle, TreeStyle elif sys.version_info[0] == 3: from ete3 import Tree, NodeStyle, TreeStyle else: raise ValueError('Your version of Python is not supported.') from scipy.cluster.hierarchy import to_tree T = to_tree(self.to_linkage_matrix()) root = Tree() root.dist = 0 root.name = "root" item2node = {T: root} to_visit = [T] while to_visit: node = to_visit.pop() cl_dist = node.dist / 2.0 for ch_node in [node.left, node.right]: if ch_node: ch = Tree() ch.dist = cl_dist ch.name = str(ch_node.id) item2node[node].add_child(ch) item2node[ch_node] = ch to_visit.append(ch_node) if labels != None: for leaf in root.get_leaves(): leaf.name = str(labels[int(leaf.name)]) ts = TreeStyle() ts.show_leaf_name = True # Draws nodes as small red spheres of diameter equal to 10 pixels nstyle = NodeStyle() nstyle["shape"] = None nstyle["size"] = 0 # 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 root.traverse(): n.set_style(nstyle) return root
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
def saveTree(inFile, fileSave, formatFile='svg', ladderize=False): """ Given a file containing a tree in newick format, the function save an imagen of such tree. Module required: - Tree (from ete2) - TreeStyle (from ete2) Usage: <inFile> <path/name to save> <formatFile (default='svg')> <ladderize (default=False)> """ tree = Tree(inFile) if ladderize: tree.ladderize() ts = TreeStyle() ts.show_branch_support = True tree.render(fileSave+'.'+formatFile, tree_style=ts)
def __init__(self): init_balances = {} for i in xrange(Parameters.num_peers): init_balances["P_" + str(i)] = Parameters.start_balance self.gen_block = Block("B_-1", 0, init_balances, {}, {}, "None") self.nodes = [Peer("P_" + str(i), self.get_delay, self.gen_block) for i in xrange(Parameters.num_peers)] self.node_is_slow = dict() self.network_graph = self.generate_graph() self.assign_neighbours() for i in xrange(Parameters.num_peers): pid = "P_" + str(i) self.node_is_slow[pid] = (random.random() < Parameters.z) # testing str of peers. t = threading.Timer(5, self.nodes[0].write_to_file) t.start() #for tree generation if _ete2_import: self.nst = [NodeStyle() for i in xrange(Parameters.num_peers)] self.fnst = [NodeStyle() for i in xrange(Parameters.num_peers)] for i in xrange(Parameters.num_peers): self.nst[i]["bgcolor"] = "#" + str(hex(random.randint(128,255)))[2:] + str(hex(random.randint(128,255)))[2:] + str(hex(random.randint(128,255)))[2:] for i in xrange(Parameters.num_peers): self.fnst[i]["size"] = 15 self.fnst[i]["fgcolor"] = self.nst[i]["bgcolor"] self.ts = TreeStyle() # self.ts.mode = "c" #circle self.ts.show_leaf_name = False def my_layout(node): F = TextFace(node.name, tight_text=True) add_face_to_node(F, node, column=0, position="branch-right") self.ts.layout_fn = my_layout
def main(): args = parser.parse_args() beta_metrics = args.beta_metrics.split(',') otu_widths = args.otu_widths.split(',') input_dir = args.input_dir output_fp = args.output_fp tree_fp = args.tree_fp nrows = len(beta_metrics) ncols = len(otu_widths) results_dict, labels_list = load_rug_dict(input_dir, beta_metrics, otu_widths) try: tree = Tree(tree_fp, format=3) except: tree = add_tip_branches(tree_fp) annotate_tree_with_rugs(tree, results_dict, labels_list) ts = TreeStyle() for row in range(len(labels_list)): for col in range(len(labels_list[row])): ts.legend.add_face(TextFace(labels_list[row][col], fsize=20), column=col) tree.render(output_fp, tree_style=ts) tree.show(tree_style=ts)
def build_tree_style(tree): # use our simple TSS cascade to prepare an ETE TreeStyle object sheets = gather_tss_stylesheets(tree) if len(sheets) == 0: return None # Some styles can be applied to the entire tree ts = TreeStyle() # For nodes (and other elements?), build an ordered set of TSS rules # to apply to each element in our layout function node_rules = [] for s in sheets: ts, tss_cascade = apply_stylesheet( stylesheet=s, tree_style=ts, node_rules=node_rules) otu_collections = tree.nexml_project.get_otus() # Use a layout function to test each node against TSS selectors? def apply_tss(node): node_style = NodeStyle() # gather label text and styles separately; we'll need to add this # using a TextFace after all styles have been considered label_specs = {} label_specs['text'] = get_proper_node_label(node, otu_collections) for rule in node_rules: # Test this node against each selector if test_node_against_selector(node, rule.selector): node_style, node = apply_node_rule(rule, node_style, node, label_specs) node.set_style(node_style); # assign the final label with appropriate style if node.is_leaf(): label_face = TextFace(**label_specs) node.add_face(label_face, 0) return node # apply this layout function to each node as it's rendered ts.layout_fn = apply_tss # suppress default node-labeling behavior (so we can style labels!) ts.show_leaf_name = False return ts
def add_taxonomy_label(cotu_tree, potu_table): ts = TreeStyle() for row in range(len(labels_list)): for col in range(len(labels_list[row])): ts.legend.add_face(TextFace(labels_list[row][col], fsize=20), column=col)
def main(args): if args.ofn == None: args.ofn = args.ifn + '.png' ts = TreeStyle() ts.show_leaf_name = True nstyle = NodeStyle() #nstyle["shape"] = "sphere" nstyle["size"] = 5 #nstyle["fgcolor"] = "darkred" nstyle["vt_line_width"] = 2 nstyle["hz_line_width"] = 2 #ts.mode = "c" tree = Tree(args.ifn) for n in tree.traverse(): n.set_style(nstyle) tree.render(args.ofn, tree_style=ts, dpi=300, units='in') #, h=20, w=20)
def draw_ete_tree(self, corpus, fontsize=5, color_leafs=False, save_newick=True, mode='c', outputfile=None, return_svg=True, show=False, save=False): root = self.to_ete(labels=corpus.titles) def layout(node): if node.is_leaf(): N = AttrFace("name", fsize=7) faces.add_face_to_node(faces.AttrFace("name", "Arial", 10, None), node, 0, position='branch-right') # problems: aligment of labels to branch, left padding of labels ts = TreeStyle() ts.mode = mode ts.show_leaf_name = False ts.scale = 120 ts.show_scale = False ts.branch_vertical_margin = 10 nstyle = NodeStyle() nstyle["fgcolor"] = "#0f0f0f" nstyle["size"] = 0 nstyle["vt_line_color"] = "#0f0f0f" nstyle["hz_line_color"] = "#0f0f0f" nstyle["vt_line_width"] = 1 nstyle["hz_line_width"] = 1 nstyle["vt_line_type"] = 0 nstyle["hz_line_type"] = 0 for n in root.traverse(): n.set_style(nstyle) ts.layout_fn = layout if outputfile: outputfile = os.path.expanduser(outputfile) if save_newick: # save tree in newick format for later manipulation in e.g. FigTree: root.write(outfile=os.path.splitext(outputfile)[0] + '.newick') if save: root.render(outputfile, tree_style=ts) if show: root.show(tree_style=ts) if return_svg: # return the SVG as a string return root.render("%%return")[0]
def setUp(self): tree = Tree() root = tree.get_tree_root() root.dist = 0 root.name = "root" node = root.add_child(name="Left") node.add_child(name="Alpha") node.add_child(name="Beta") node = root.add_child(name="Right") node.add_child(name="Gamma") node.add_child(name="Delta") for desc in tree.iter_descendants(): desc.dist = 0 ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = False ts.mode = "c" ts.arc_start = 0 ts.arc_span = 360 self.circular_style = ts self.exampleTree = tree self.alignment = MultipleSeqAlignment([ SeqRecord(Seq("AAG", generic_dna), id="Alpha"), SeqRecord(Seq("AGA", generic_dna), id="Beta"), SeqRecord(Seq("AAA", generic_dna), id="Gamma"), SeqRecord(Seq("GGA", generic_dna), id="Delta"), ])
def get_example_tree(): # Performs a tree reconciliation analysis gene_tree_nw = '((Dme_001,Dme_002),(((Cfa_001,Mms_001),((Hsa_001,Ptr_001),Mmu_001)),(Ptr_002,(Hsa_002,Mmu_002))));' species_tree_nw = "((((Hsa, Ptr), Mmu), (Mms, Cfa)), Dme);" genetree = PhyloTree(gene_tree_nw) sptree = PhyloTree(species_tree_nw) recon_tree, events = genetree.reconcile(sptree) recon_tree.link_to_alignment(alg) return recon_tree, TreeStyle()
def draw(self, out_file_prefix, w=140, units="mm"): def layout(node, feature): if node.up is not None or feature == "id": attr = AttrFace(feature, fsize=5, fgcolor="green") faces.add_face_to_node(attr, node, 0, position="branch-top") for feature in self.tree.features - set(["support", "name"]): if feature[0] == "_": continue # skip _nid feature and other technical features of tree def layout_arg(node): return layout(node, feature) ts = TreeStyle() ts.layout_fn = layout_arg self.tree.render("%s_%s.png" % (out_file_prefix, feature), w=w, units=units, tree_style=ts)
def main(argv): inputfile = '' outgroup = '' outputfile = '' ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_length = False ts.show_branch_support = True ns = NodeStyle() ns["size"] = 0 ns["vt_line_width"] = 2 ns["hz_line_width"] = 2 try: opts, args = getopt.getopt(argv, "hi:o:p:", ["input=", "outgroup=", "-prefix-svg="]) except getopt.GetoptError: print 'print-single-nwk.py -i <inputfile> -o <outgroup> -p <prefixsvg>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'print-single-nwk.py -i <inputfile> -o <outgroup> -p <prefixsvg>' sys.exit() elif opt in ("-i", "--input"): inputfile = arg elif opt in ("-o", "--outgroup"): outgroup = arg elif opt in ("-p", "--prefix-svg"): outputfile = arg # read tree t = Tree(inputfile) t.set_outgroup(outgroup) t.ladderize(1) for node in t.traverse(): node.set_style(ns) # print final tree t.render(outputfile + ".svg", tree_style=ts)
def showTreeInGrid(gid, biome, grid_level=14, taxonomic_level='sp'): """ Performs a selection, spatial filter and returns an image. grid_level is the grid layer. taxonomic_level is the taxonomic level to be shown. Options are: sp, gns, fam, ord, cls, phy, king """ mesh = initMesh(grid_level) try: cell = mesh.objects.get(id=id) except: logger.error("Selected id does not exist in selected grid") return None gb = GriddedTaxonomy(biome, cell, generate_tree_now=True) forest = gb.taxonomies[0].forest ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 forest[taxonomic_level].show(tree_style=ts) return 'Parece que se tiene que ver algo'
def render(self, fname, layout=None, tree_style=None, palette=None): """ Renders the locus tree and writes the image to file. :param fname: str Output file path :param layout: :param tree_style: :param palette: :return: None """ if not palette: palette = ['#1F77B4', '#AEC7E8', '#FF7F0E', '#FFBB78', '#2CA02C', '#98DF8A', '#D62728', '#FF9896', '#9467BD', '#C5B0D5', '#8C564B', '#C49C94', '#E377C2', '#F7B6D2', '#7F7F7F', '#C7C7C7', '#BCBD22', '#DBDB8D', '#17BECF', '#9EDAE5'] if not self.colorized: self._colorize(palette) self.colorized = True if not tree_style: from ete2 import TreeStyle tree_style = TreeStyle() # imported during colorizing tree # tstyle.show_leaf_name = False tree_style.scale = 28 tree_style.branch_vertical_margin = 6 tree_style.show_branch_length = False # tstyle.show_branch_support = True tree_style.show_scale = False self.L.convert_to_ultrametric() self.L.render(file_name=fname, tree_style=tree_style)
def ete_tree(aln): """Tree showing alleles""" from ete2 import Tree, PhyloTree, TreeStyle, NodeStyle t = Tree('temp.dnd') ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 ts.arc_span = 180 cutoff = 0.25 def func(node): if node.name == 'NoName': #or not node.name in metric: return False #if metric[node.name]<=cutoff: # return True matches = filter(func, t.traverse()) print(len(matches), "nodes have distance <=%s" % cutoff) nst1 = NodeStyle() nst1["bgcolor"] = "Yellow" for n in matches: n.set_style(nst1) nst2 = NodeStyle() nst2["bgcolor"] = "LightGreen" #hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles] #for n in hlanodes: # n.set_style(nst2) t.show(tree_style=ts) return
def show(self, tree_style=None, palette=None): """ Starts an interactive session to visualize the decomposition. :return: None """ if not palette: palette = ['#1F77B4', '#AEC7E8', '#FF7F0E', '#FFBB78', '#2CA02C', '#98DF8A', '#D62728', '#FF9896', '#9467BD', '#C5B0D5', '#8C564B', '#C49C94', '#E377C2', '#F7B6D2', '#7F7F7F', '#C7C7C7', '#BCBD22', '#DBDB8D', '#17BECF', '#9EDAE5'] if not self.colorized: self._colorize(palette) self.colorized = True if not tree_style: from ete2 import TreeStyle tree_style = TreeStyle() # tstyle.show_leaf_name = False tree_style.scale = 28 tree_style.branch_vertical_margin = 6 tree_style.show_branch_length = False # tstyle.show_branch_support = True tree_style.show_scale = False self.L.convert_to_ultrametric() self.L.show(tree_style=tree_style)
def ETETree(seqs, ref, metric): """Tree showing bola alleles covered by tepitope""" from ete2 import Tree, PhyloTree, TreeStyle, NodeStyle aln = Genome.clustalAlignment(seqs=seqs) t = Tree('temp.dnd') #t.set_outgroup(t&ref) ts = TreeStyle() ts.show_leaf_name = True ts.mode = "c" ts.arc_start = -180 ts.arc_span = 180 cutoff = 0.25 def func(node): if node.name == 'NoName' or not node.name in metric: return False if metric[node.name] <= cutoff: return True matches = filter(func, t.traverse()) print len(matches), "nodes have distance <=%s" % cutoff nst1 = NodeStyle() nst1["bgcolor"] = "Yellow" for n in matches: n.set_style(nst1) nst2 = NodeStyle() nst2["bgcolor"] = "LightGreen" hlanodes = [t.get_leaves_by_name(name=r)[0] for r in refalleles] for n in hlanodes: n.set_style(nst2) t.show(tree_style=ts) return
def render_tree(sk_tree, tip_hues, tip_lums, saturation=0.9, output_fp=None, supress_display=False): ete_tree = Tree(str(sk_tree)) tree_tips = [x.name for x in sk_tree.tips()] for ete_leaf in ete_tree.iter_leaves(): if (ete_leaf.name not in tree_tips) and (ete_leaf.name[1:-1] in tree_tips): ete_leaf.name = ete_leaf.name[1:-1] elif ete_leaf.name not in tree_tips: print 'leaf {0} in ete-parsed tree not found in skbio tree {1}'.format( ete_leaf.name, str(sk_tree.ascii_art())) raise KeyError for n in ete_tree.traverse(): if n.is_leaf(): hex_color = hls_to_rgb_hex(tip_hues[n.name], tip_lums[n.name], saturation) n.add_features(tip_color=hex_color) style = NodeStyle() style["size"] = 0 for l in ete_tree.traverse(): l.set_style(style) ts = TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False if output_fp: ete_tree.render(output_fp, tree_style=ts) if not supress_display: ete_tree.show(tree_style=ts) return
def render_symbiont_tree(symbiont_tree, output_fp, ts=TreeStyle()): ts.show_leaf_name = True # ts.scale = 300 # 120 pixels per branch length unit # ts.mode = "c" nstyle = NodeStyle() nstyle["shape"] = "circle" nstyle["size"] = 0 for n in symbiont_tree.traverse(): n.set_style(nstyle) print 'rendering tree' symbiont_tree.render(output_fp, tree_style=ts)
def give_tree_layout(t): # Some random features in all nodes for n in t.traverse(): n.add_features(weight=n.dist*20) # Create an empty TreeStyle ts = TreeStyle() # Set our custom layout function ts.layout_fn = layout # Draw a tree #ts.mode = "c" #ts.arc_start = -180 #ts.arc_span = 180 # 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
def __init__(self, tree, options): self._tree = tree self._options = options self._formatingMethods = [] self._storageDir = None self._filePrefix = None self._style = TreeStyle() self._style.show_leaf_name = True self._style.show_branch_length = False self._style.scale = 80 self._style.branch_vertical_margin = 15 self._style.rotation = 90 self._style.arc_start = -180 self._style.arc_span = 180 self.parseOptions(options)
def get_tree_style(scale=None, vertical_margin=None): """Setups the tree-style used when rendering the tree""" style = TreeStyle() style.show_leaf_name = False if scale: style.scale = scale style.show_border = True if vertical_margin: style.branch_vertical_margin = vertical_margin return style
def main(): args = parser.parse_args() symbiont_tree_fp = args.symbiont_tree_fp host_tree_fp = args.host_tree_fp biom_fp = args.biom_fp output_fp = args.output_fp host_tree_output_fp = args.host_tree_output_fp normalize = args.normalize pies = args.pies labels = args.labels output_format = args.output_format force = args.force host_colors = get_host_colors_from_tree(host_tree_fp) if host_tree_output_fp: print_colored_host_tree(host_tree_fp, host_colors, host_tree_output_fp) with open(symbiont_tree_fp, 'r') as s_f: s_tree = s_f.readlines()[0].strip() symbiont_tree = Tree(remove_newick_node_labels(s_tree)) otu_table = load_table(biom_fp) if normalize: otu_table.norm(inplace=True) if pies: add_host_pies(symbiont_tree, otu_table, host_colors) if labels: add_colored_host_label(symbiont_tree, otu_table, host_colors) ts = TreeStyle() render_symbiont_tree(symbiont_tree, output_fp, ts)