def get_example_tree(): # Set dashed blue lines in all leaves nst1 = NodeStyle() nst1["bgcolor"] = "LightSteelBlue" nst2 = NodeStyle() nst2["bgcolor"] = "Moccasin" nst3 = NodeStyle() nst3["bgcolor"] = "DarkSeaGreen" nst4 = NodeStyle() nst4["bgcolor"] = "Khaki" t = Tree("( 🌲,( 🥑,(( 🌷, ( 🌴, ( 🍌, ( 🍍, ( 🌽, ( 🎋, 🌾 )))))),(( 🍇, ((( 🥜, ☘️), ((( 🌹, 🍓 ), (( 🍎, 🍐 ), ( 🍑, (🌸, 🍒) ))), ( 🌰, ( 🎃, ( 🍉, ( 🥒, 🍈)))))), (( 🌺, 🥦 ), (( 🍊, 🍋 ), ( 🍁, 🥭))))),( 🌵, ( 🥝, (( 🍠, ( 🌶️, (🍆, ( 🥔, 🍅)))), ( 🥕,( 🥬, ( 🌻, 🌼)))))))));") for n in t.traverse(): n.dist = 0 n1 = t.get_common_ancestor("a1", "a2", "a3") n1.set_style(nst1) n2 = t.get_common_ancestor("b1", "b2", "b3", "b4") n2.set_style(nst2) n3 = t.get_common_ancestor("c1", "c2", "c3") n3.set_style(nst3) n4 = t.get_common_ancestor("b3", "b4") n4.set_style(nst4) ts = TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False ts.mode = "c" ts.root_opening_factor = 1 return t, ts
def generateColoredPDF(tree): out_tree = os.path.splitext(os.path.basename(sys.argv[1]))[0] + ".pdf" ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_support = True ts.show_branch_length = False for n in tree.traverse(): if n.name in eukaryote_seqs: nstyle = NodeStyle() nstyle["fgcolor"] = "red" nstyle["size"] = 15 n.set_style(nstyle) n.name = name2tax.get(n.name) elif n.name in bacteria_seqs: nstyle = NodeStyle() nstyle["fgcolor"] = "blue" nstyle["size"] = 13 n.set_style(nstyle) n.name = name2tax.get(n.name) elif n.name in archaea_seqs: nstyle = NodeStyle() nstyle["fgcolor"] = "green" nstyle["size"] = 13 n.set_style(nstyle) n.name = name2tax.get(n.name) elif n.name in other_seqs: nstyle = NodeStyle() nstyle["fgcolor"] = "grey" nstyle["size"] = 13 n.set_style(nstyle) n.name = name2tax.get(n.name) tree.render(out_tree, 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 plot_trees(tree_fn, output_fn): """ Plot a tree """ os.environ['QT_QPA_PLATFORM'] = 'offscreen' style = TreeStyle() style.mode = "c" style.show_leaf_name = True # Set Node Styles rstyle = NodeStyle() rstyle["shape"] = "sphere" rstyle["size"] = 15 rstyle["fgcolor"] = "blue" nstyle = NodeStyle() nstyle["shape"] = "sphere" nstyle["size"] = 0 sstyle = NodeStyle() sstyle["shape"] = "sphere" sstyle["size"] = 15 sstyle["fgcolor"] = "red" #Create the tree object ct = Tree(tree_fn) for n in ct.traverse(): if n.name == "Wuhan" or n.name == "Wuhan|402124": n.set_style(rstyle) elif n.name == "Sample": n.set_style(sstyle) elif not n.is_leaf(): n.set_style(nstyle) #Draw the tree and write to a file ct.render(output_fn, tree_style=style)
def main(argv): start = time.time() 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 style2 = NodeStyle() style2["fgcolor"] = "#0f0f0f" style2["size"] = 0 style2["vt_line_color"] = "#ff0000" #style2["hz_line_color"] = "#ff0000" style2["vt_line_width"] = 2 #style2["hz_line_width"] = 2 style2["vt_line_type"] = 2 # 0 solid, 1 dashed, 2 dotted #style2["hz_line_type"] = 2 tree1 = Tree(str(argv[1])) save = int(argv[3]) leafs = argv[2] leafs = leafs.replace("(", "") leafs = leafs.replace(")", "") leafs = leafs.replace("'", "") leafs = leafs.replace(" ", "") q = leafs.split(',') #tree2 = _Tree(str(arg2)) se = tree1.get_common_ancestor(q) for n in q: print(n) node = tree1 & n while (node.up != se): node.img_style = style1 node = node.up #n.img_style = style2 node.img_style = style1 ts = TreeStyle() ts.show_leaf_name = True if (save == 1): if os.path.exists("crud/static/crud/Tree1.png"): os.remove("crud/static/crud/Tree1.png") tree1.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") tree1.render("crud/static/crud/Tree2.png", tree_style=ts) return True
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 drawTree(treeFile, ShowBool): """ Draw a tree from a phy file """ t = Tree(treeFile) imgFile = treeFile.replace(".tree", ".tree.pdf") # Basic tree style ts = TreeStyle() ts.show_leaf_name = True ts.show_branch_support = True ts.scale = 50 # Draws nodes as small red spheres of diameter equal to 10 pixels nstyle = NodeStyle() nstyle["shape"] = "sphere" nstyle["size"] = 10 nstyle["fgcolor"] = "darkred" #nstyle["faces_bgcolor"] = "pink" nstyle2 = NodeStyle() nstyle2["shape"] = "sphere" nstyle2["size"] = 10 nstyle2["fgcolor"] = "darkblue" # Gray dashed branch lines nstyle["hz_line_type"] = 1 nstyle["hz_line_color"] = "#cccccc" # Applies the same static style to all nodes in the tree. Note that, # if "nstyle" is modified, changes will affect to all nodes for n in t.traverse(): if n.is_leaf(): if n.name.split("|")[-1] == "GI": n.set_style(nstyle) if n.name.split("|")[-1] == "plasmid": n.set_style(nstyle2) gi = n.name.split("|")[1] n.name = n.name.split("|")[0] #+ " " + n.name.split("|")[1] n.name = n.name.replace("_tRNA_modification_GTPase_", "") n.name = n.name.replace("_DNA", "") n.name = " " + n.name + " " if n.name[-1] == "_": n.name.rstrip() taxon, color = taxonToColour(gi) n.add_face(TextFace(taxon, fgcolor=color, fsize=8), column=1, position="branch-right") #n.img_style["bgcolor"] = color if ShowBool == True: #permet de flipper les braches pour avoir des topologies similaires t.show(tree_style=ts) t.render(imgFile, w=1024, units="mm", tree_style=ts)
def get_species(self): sp_list = [] for sp in self.species_list: spe = [] for taxa in sp: spe.append(taxa.name) sp_list.append(spe) all_taxa_name = [] for leaf in self.tree.get_leaves(): all_taxa_name.append(leaf.name) style0 = NodeStyle() style0["fgcolor"] = "#000000" style0["vt_line_color"] = "#0000aa" style0["hz_line_color"] = "#0000aa" style0["vt_line_width"] = 2 style0["hz_line_width"] = 2 style0["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted style0["hz_line_type"] = 0 style0["size"] = 0 for node in self.tree.get_descendants(): node.set_style(style0) node.img_style["size"] = 0 self.tree.set_style(style0) self.tree.img_style["size"] = 0 style1 = NodeStyle() style1["fgcolor"] = "#000000" style1["vt_line_color"] = "#ff0000" style1["hz_line_color"] = "#0000aa" style1["vt_line_width"] = 2 style1["hz_line_width"] = 2 style1["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted style1["hz_line_type"] = 0 style1["size"] = 0 style2 = NodeStyle() style2["fgcolor"] = "#0f0f0f" style2["vt_line_color"] = "#ff0000" style2["hz_line_color"] = "#ff0000" style2["vt_line_width"] = 2 style2["hz_line_width"] = 2 style2["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted style2["hz_line_type"] = 0 style2["size"] = 0 for node in self.coa_roots: node.set_style(style1) node.img_style["size"] = 0 for des in node.get_descendants(): des.set_style(style2) des.img_style["size"] = 0 return [all_taxa_name], sp_list
def draw_tree(self, iters=10): """This method generates an interactive phylogenetic tree from a super alignement file. It calculates a newick tree with RAxML and then visualizes it using ETEtoolkit. Parameters ------- iters : int, optional Number of repetitions for bootstrap. The default is 10. """ bootstrap_tree = Clusterizer.tree_generator(self.super_alignement, bootstrap=iters) t = Tree('../data/phylogeny/%s' % bootstrap_tree) ts = TreeStyle() ts.show_leaf_name = True nstyle = NodeStyle() nstyle["shape"] = "sphere" nstyle["size"] = 10 nstyle["fgcolor"] = "darkred" nstyle["hz_line_type"] = 1 nstyle["hz_line_color"] = "#cccccc" for n in t.traverse(): n.set_style(nstyle) t.show(tree_style=ts)
def layout_raw(node: TreeNode, tight_mode: bool = True) -> None: """Layout implementation for a tree node Parameters ---------- node : TreeNode the root of the taxonomy tree / sub-tree tight_mode : bool, default=True a mode to print node names more tightly Returns ------- None """ if tight_mode: name_segments = node.name.split(' ') for i, name_segment in enumerate(name_segments): name_face = TextFace(name_segment, tight_text=True) name_face.rotation = 270 node.add_face(name_face, column=i, position="branch-right") else: name_face = TextFace(node.name, tight_text=True) name_face.rotation = 270 node.add_face(name_face, column=0, position="branch-right") nst = NodeStyle() nst["fgcolor"] = "black" nst["size"] = 20 nst["shape"] = "circle" node.set_style(nst)
def rendertree(infile, width=800, spname=False): fntfile = os.path.join( os.path.split(os.path.realpath(__file__))[0], "fonts", "roboto.ttf") if infile and os.path.exists(infile): T = Tree(infile) if app.config.get("DISABLE_PYQT", False): printpng(infile + ".png", str(T), spname, fntfile, 16, offset=10) return True else: try: if spname: for node in T: if "OUTGROUP" in node.name: T.set_outgroup(node) T.ladderize() if spname in node.name: #Use styles if availible (PyQT) otherwise use TEXT from ete3 import NodeStyle nstyle = NodeStyle() nstyle["bgcolor"] = "#00CC00" nstyle["size"] = 10 node.set_style(nstyle) T.render(infile + ".png", w=width, units="px") return True except ImportError: printpng(infile + ".png", str(T), spname, fntfile, 16, offset=10) return True else: return False
def color_subtypes(node): node_style = NodeStyle() node_style["hz_line_width"] = 2 node_style["vt_line_width"] = 2 if hasattr(node, "bootstrap"): if node.bootstrap >= bootstrap_cutoff: node_style["fgcolor"] = "black" else: node_style["fgcolor"] = "grey" else: node_style["fgcolor"] = "black" if hasattr(node, "subtype") and node.subtype in subtype_color_dict: node_style["hz_line_color"] = subtype_color_dict[node.subtype] else: # check for subtype monophyly and color if true subtypes = set() for leaf in node.get_leaves(): subtypes.add(leaf.subtype) if len(subtypes) > 1: break subtype = subtypes.pop() if len(subtypes) == 0 and subtype in subtype_color_dict: node_style["vt_line_color"] = subtype_color_dict[subtype] node_style["hz_line_color"] = subtype_color_dict[subtype] return node_style
def make_tree(t): ts = TreeStyle() ## make the tree in to a cladogram most_distant_leaf, tree_length = t.get_farthest_leaf() current_dist = 0 for postorder, node in t.iter_prepostorder(): if postorder: current_dist -= node.dist else: if node.is_leaf(): node.dist += tree_length - (current_dist + node.dist) elif node.up: # node is internal current_dist += node.dist ## Rotate and color the lables def rotation_layout(node): if node.is_leaf(): if node.name == 'X': F = TextFace(node.name, tight_text=True, fgcolor='Blue') F.rotation = 90 add_face_to_node(F, node, column=0, position="branch-right") elif node.name == 'Y': F = TextFace(node.name, tight_text=True, fgcolor='Red') F.rotation = 90 add_face_to_node(F, node, column=0, position="branch-right") elif node.name == 'A': F = TextFace("") add_face_to_node(F, node, column=0, position="branch-right") else: F = TextFace(node.name, tight_text=True, fgcolor='Green') F.rotation = 90 add_face_to_node(F, node, column=0, position="branch-right") ## Format the tree image nstyle = NodeStyle() nstyle["hz_line_type"] = 0 nstyle["vt_line_color"] = "#ffffff" nstyle["hz_line_color"] = "#ffffff" nstyle["vt_line_width"] = 4 nstyle["hz_line_width"] = 4 nstyle["size"] = 0 for n in t.traverse(): n.set_style(nstyle) ## Set background t.img_style["bgcolor"] = "#2e3440" ## Tree 'shape' ts.min_leaf_separation = 20 ts.show_leaf_name = False ts.layout_fn = rotation_layout ts.rotation = -90 ts.show_scale = False #t.show(tree_style=ts) t.render(f"{t.name}.svg", tree_style=ts, dpi=900)
def customize_node_styles_for_visualization(t): """Take an ete3 tree object , and modify the node styles for better visualization. """ # Remove blue dots before leaf names. nstyle = NodeStyle() nstyle["shape"] = "sphere" nstyle["size"] = 0 # Gray dashed branch lines #nstyle["hz_line_type"] = 1 #nstyle["hz_line_color"] = "#cccccc" #nstyle["fgcolor"] = "#0f0f0f" nstyle["vt_line_color"] = "#000000" nstyle["hz_line_color"] = "#000000" nstyle["vt_line_width"] = 1.5 nstyle["hz_line_width"] = 1.5 nstyle["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted nstyle["hz_line_type"] = 0 # Applies the same static style to all nodes in the tree. Note that, # if "nstyle" is modified, changes will affect to all nodes for n in t.traverse(): n.set_style(nstyle) if n.is_leaf(): # Set font size for leaf/taxon labels. name_face = TextFace(n.name, fgcolor="black", fsize=5) n.add_face(name_face, column=0, position='branch-right')
def plot_variance(tree,path,aa): #cycle through the nodes and add a variance attribute to each node postorder, so we start with the #children that have W attribute and recursively create this attribute as we are traversing through the tree all_means=[] for node in tree.traverse(strategy="postorder"): if not(node.is_leaf()): children=node.children variance=[] for i in range(len(children)): aa_feat = getattr(children[i], aa) variance.append(aa_feat) # variance requires at least two data points, in case there is only one sequence or node if len(variance)==1: node.add_feature(aa+"_var",0) node.add_feature(aa+"", np.mean(variance)) else: node.add_feature(aa+"_var",statistics.variance(variance)) node.add_feature(aa+"", np.mean(variance)) all_means.append(getattr(node, aa+"")) #plot without sequences (create new tree with cut leave and ) new_tree=tree.copy() maximum=max(all_means) minimum=min(all_means) #for node in new_tree.traverse(strategy="preorder"): ts = TreeStyle() ts.mode="c" for node in new_tree.traverse(): if node.is_leaf(): node.detach() else: nstyle = NodeStyle() nstyle["bgcolor"]="#"+rgb_to_hex(red_gradient(minimum,maximum,(getattr(node, aa+"")))) node.add_face(TextFace(getattr(node,aa+"")), column=0, position = "branch-right") node.set_style(nstyle) new_tree.render(path, w=1400, units="mm", tree_style=ts)
def mylayout(node): # Internal Node formatting nstyle = NodeStyle() nstyle["size"] = 0 nstyle["vt_line_width"] = 2 nstyle["hz_line_width"] = 2 if node.is_leaf(): circle_face = CircleFace(10, color_dict[node.name], style='circle') faces.add_face_to_node(circle_face, node, position="branch-right", column=0) text_face = TextFace(meta_dict[node.name][0]) text_face.fgcolor = color_dict[node.name] faces.add_face_to_node(text_face, node, position="branch-right", column=1) node.set_style(nstyle) elif node.is_root(): node.dist = 0 node.set_style(nstyle) else: node.set_style(nstyle)
def phylo_annotate_v1(): # SNP_time_plot('final_ny_aligned.txt', 610) # plt.title("Frequency Plot for Locus 610+449") # plt.show() seqdict = {} ny_aligned = list(SeqIO.parse('final_ny_aligned.txt', "fasta")) for record in ny_aligned: new = str(record.description).split(' ') # print(record.description) new = new[0] + '_' + new[1] new = new.replace('|', '_') seqdict[new] = str(record.seq) t = Tree("final_ny_aligned_newick.nh") for n in t.traverse(): if n.name != '': names = n.name.split('_', 1) new_name = names[1] if seqdict[new_name][28432] == 'A': nstyle = NodeStyle() nstyle["fgcolor"] = "red" nstyle["size"] = 15 n.set_style(nstyle) # for n in t.traverse(): # print(n.name) t.show()
def colorNodes(t, numbered): """ Add styling to nodes of a PHYLDOG tree t: tree cp: list of colors (hex) corresponding to speciation events numbered: if true print also speciation numbers on nodes """ cp = readPalette() for node in t.traverse(): nstyle = NodeStyle() nstyle["size"] = 10 if node.Ev == 'S': nstyle["fgcolor"] = cp[int(node.S) - 1] nstyle["shape"] = "circle" if numbered: node.add_face(TextFace(node.S), column=0, position="branch-right") elif node.Ev == 'D': nstyle["fgcolor"] = "black" #cblue4 nstyle["shape"] = "square" else: quit() node.set_style(nstyle) return t
def traitTreeMinimal(traits, mapper): ### Take dict of traits and [R,G,B]-returning function ### Draw a tree with the continuous trait painted on via a colormapping function def rgb2hex(r, g, b): hex = "#{:02x}{:02x}{:02x}".format(r, g, b) return hex ts = TreeStyle() ts.show_leaf_name = False ts.rotation = 270 ts.complete_branch_lines_when_necessary = False #ts.optimal_scale_level = "full" ts.scale = 800 # default NodeStyle nstyle = NodeStyle() nstyle["size"] = 0 nstyle["hz_line_color"] = "grey" nstyle["vt_line_color"] = "grey" nstyle["hz_line_width"] = 3 nstyle["vt_line_width"] = 3 for n in tree.traverse(): chroma = rgb2hex(*[ int(val) for val in mapper(traits[n.ND], gamma=0.8, scaleMax=255) ]) # setup for wl2RGB nf = CircleFace(radius=10, color='none', style='circle', label=None) n.set_style(nstyle) n.add_face(nf, column=0, position='branch-top') outFile = args.output + "/test_trees/cont_trait.pdf" tree.render(outFile, tree_style=ts) print >> sys.stderr, outFile
def render_tree(species_tree, bipart1, num_alt, png_fn, replace_taxon=None): color1 = "blue" color2 = "black" ts = TreeStyle() ts.show_leaf_name = False ts.show_scale = False nstyle = NodeStyle() nstyle["size"] = 0 ts.title.add_face( TextFace("{} bipartition in {} gene trees".format(png_fn, num_alt), fsize=15, bold=True), 0) plot_tree = species_tree for node in plot_tree.traverse(): node.set_style(nstyle) if node.name in bipart1: name_face = TextFace(node.name, fgcolor=color1) else: name_face = TextFace(node.name, fgcolor=color2) node.add_face(name_face, 0, 'branch-right') if replace_taxon: for leaf in plot_tree.get_leaves: try: leaf.name = taxon_subst[leaf.name] except KeyError: continue plot_tree.convert_to_ultrametric() plot_tree.render(png_fn, tree_style=ts, w=600)
def diamond_layout(node): # Run the layout passed in first before # filling in the heatmap layout(node) N = AttrFace("name", fsize=label_size, fgcolor=labelcolor) # background colors c, found = _get_node_color(bgcolors, node, "") if found: nst = NodeStyle() nst["bgcolor"] = c node.set_style(nst) if node.name in collapsed_nodes: # scaling factor for approximating subtree depth depth = node.get_farthest_leaf(topology_only=True) w = depth[1] * depth_scaling # scaling factor for approximating for subtree width h = len(node) * breadth_scaling c, _ = _get_node_color(cladecolors, node, "#0000FF") C = CollapsedDiamondFace(width=w, height=h, color=c) node.img_style['draw_descendants'] = False # And place as a float face over the tree faces.add_face_to_node(C, node, 0, position="float") faces.add_face_to_node(N, node, 1, position="float") else: faces.add_face_to_node(N, node, 0)
def set_node_style(tree, node_dict): root_node = tree & 'root' for node in tree.traverse(): if node is root_node: node.set_style(NodeStyle(size=0)) continue node.set_style(node_dict[node.name].style)
def my_layout(node): style = NodeStyle() style["size"] = 0 style["vt_line_color"] = "#A0A0A0" style["hz_line_color"] = "#A0A0A0" style["vt_line_type"] = 0 # 0 solid, 1 dashed, 2 dotted style["hz_line_type"] = 0 node.set_style(style) if node.is_leaf(): name_face = AttrFace("name", fsize=8, ftype="Times") else: name_face = TextFace(node.name, fsize=18, ftype="Times") if node.node_type == Sum: for child in node.children: label = TextFace(round(child.support, 3), fsize=6) child.add_face(label, column=1, position="branch-bottom") if show_ids: node.add_face(AttrFace("id", fsize=6), column=1, position="branch-top") faces.add_face_to_node(name_face, node, column=1, position="branch-right")
def layout(node): # Make node name empty for particular nodes # if node.name in ('information retrieval', 'information systems'): # node.name = '' # x = 0 # # if node.name == '3 items': # node.name = '' # Some long name war here try: print_label = int( node.e ) < 3 or node.Hd == '1' or node.Of == '1' or node.Gap == '1' or node.ForceLabel == '1' if print_label: name_split = node.name.split('|') column = 0 for line in name_split: tw = textwrap.TextWrapper(width=20) names = tw.wrap(line) for n in names: short_name = TextFace(n, tight_text=True) short_name.rotation = 270 node.add_face(short_name, column=column, position="branch-right") column += 1 # Create and apply node style nst = NodeStyle() if .4 >= float(node.u) > 0: nst["fgcolor"] = "#90ee90" elif .6 >= float(node.u) > .4: nst["fgcolor"] = "green" elif float(node.u) > .6: nst["fgcolor"] = "#004000" elif node.Gap == '1': nst["fgcolor"] = "red" else: nst["fgcolor"] = NO_SUPPORT_COLOR if node.Hd == '1' or node.Of == '1': nst["size"] = 40 nst["shape"] = 'square' else: nst["size"] = 20 nst["shape"] = 'circle' # if node.Sq == '1' and float(node.u) > 0: # nst["shape"] = 'square' node.set_style(nst) except: print(f'Exception at {node}')
def death( tree, node ): #died is a set for the dead, setpop is the set where the victim is picked node.extinct = True #kill the node nstyle = NodeStyle() nstyle["fgcolor"] = 'green' node.set_style(nstyle) return tree
def reset_tree(t): nstyle = NodeStyle() nstyle['shape'] = 'sphere' nstyle['size'] = 0 nstyle['fgcolor'] = 'black' for n in t.traverse(): n.set_style(nstyle)
def tree_to_tsvg(tree_file, contaminants=None, backpropagation=None): if contaminants is None: contaminants = set() tree_base = str(os.path.basename(tree_file)) # what if they will use somethig different than Raxml? We should make some if statement here maybe. name_ = tree_base.split('.')[1] if os.path.isfile(f'{args.input}/{name_}.trimmed') is True: build_len, len_dict, trimmed_len = get_build_len(name_) len_info = f'Final Align Len: {build_len}, Trimmed Align Len: {trimmed_len}' len_dict = {k: round(v / trimmed_len, 2) for k, v in len_dict.items()} else: build_len, len_dict = get_build_len(name_) len_info = f'Final Align Len: {build_len}' len_dict = {k: round(v / build_len, 2) for k, v in len_dict.items()} if not backpropagation: table = open(f"{output_folder}/{name_.split('_')[0]}.tsv", 'w') else: table = open(f"{output_folder}/{name_.split('_')[0]}.tsv", 'r') top_ranked = get_best_candidates(tree_file) t = Tree(tree_file) ts = TreeStyle() R = t.get_midpoint_outgroup() t.set_outgroup(R) sus_clades = 0 for node in t.traverse('preorder'): node_style = NodeStyle() node_style['vt_line_width'] = 3 node_style['hz_line_width'] = 3 node_style['vt_line_type'] = 0 node_style['hz_line_type'] = 0 if node.is_root() is False: if node.is_leaf() is False: # All internal nodes supp, sus_clades = format_nodes(node, node_style, sus_clades, t) node.add_face(supp, column=0, position="branch-bottom") node.set_style(node_style) else: # All leaves format_leaves(backpropagation, contaminants, node, node_style, table, top_ranked, len_dict) node.set_style(node_style) title_face = TextFace( f'<{name_} {len_info}, {sus_clades} suspicious clades>', bold=True) ts.title.add_face(title_face, column=1) t.render( f'{output_folder}/{name_}_tree.svg', tree_style=ts, ) if not backpropagation: # what what what? table.close()
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
def change_tree_branch(node_list, rgb_color, dst): val = 8 - int(dst) style1 = NodeStyle() style1["vt_line_width"] = val * 40 style1["hz_line_width"] = val * 40 style1["vt_line_color"] = rgb_color style1["hz_line_color"] = rgb_color for node in node_list: node.set_style(style1)
def queryNode(leaf): nsQuery = NodeStyle() nsQuery["fgcolor"] = "red" nsQuery["shape"] = "sphere" nsQuery["size"] = 9 nsQuery["hz_line_type"] = 1 nsQuery["hz_line_color"] = "red" faceQuery = AttrFace("name", fsize=9, fstyle="italic", text_prefix=" ") leaf.set_style(nsQuery) leaf.add_face(faceQuery, column=0, position="branch-right")
genedict = load_obj('genedict') speciescolors = load_obj('colors') red = Color('red') blue = Color('blue') colorvec = list(red.range_to(blue, len(genedict))) colormap = {} columnmap = {} for i,fasta in enumerate(genedict): columnmap[fasta] = i colormap[fasta] = colorvec[i].hex annotated = [] print speciescolors for fasta in genedict: for leaf in t.get_leaves(): nst = NodeStyle() nst["size"] = 0 nst["fgcolor"] = 'black' nst["hz_line_width"] = 2 nst["vt_line_width"]= 2 nst.show_name = True if leaf.name.split('/')[0] in genedict[fasta]: if 'HH' not in fasta and 'LOMETS' not in fasta: leaf.add_face( RectFace ( 10 , 10 , colormap[fasta], colormap[fasta] ), column = columnmap[fasta] ) if leaf not in annotated: try: face = leaf.add_face( TextFace ( text = genedict[fasta][leaf.name.split('/')[0]][2]) , column = 10 ) annotated.append(leaf) except: print genedict[fasta][leaf.name.split('/')[0]]
def format( tree , genedict , detection , includenames , filename , speciescolors = None): print 'final output...' red = Color('red') blue = Color('blue') colorvec = list(red.range_to(blue, len(genedict.keys()))) colormap = {} columnmap = {} for i,ref in enumerate(genedict): if ref not in detection: columnmap[ref] = 3 if 'hybrid' in ref.lower(): columnmap[ref] = 0 if 'eff' in ref.lower(): columnmap[ref] = 1 if 'hap' in ref.lower(): columnmap[ref] = 2 colormap[ref] = colorvec[i].hex for i,ref in enumerate(detection): columnmap[ref] = 3 + i colormap[ref] = colorvec[i].hex print columnmap print colormap circledict = {} for n in t.traverse(): nst = NodeStyle() nst["size"] = 0 nst["fgcolor"] = 'black' nst["hz_line_width"] = 4 nst["vt_line_width"]= 4 nst.show_name = False if n.is_leaf(): if speciescolors != None and n.name in speciescolors: nst["bgcolor"] = colors[n.name] nst.show_name = True n.add_face( AttrFace(attr = 'name', ftype='Helvetica', fgcolor='black', fsize =18 ,fstyle = 'normal' ), column =0 ) refs = json.loads(n.refs) for ref in genedict: if ref in refs and ref in detection: n.add_face( CircleFace ( 10 , colormap[ref]), column = 2 + columnmap[ref] ) n.img_style = nst if ref in refs and ref not in detection: n.add_face( RectFace ( 20 , 20 , colormap[ref], colormap[ref] ), column = 2 + columnmap[ref] ) n.img_style = nst if ref not in refs and ref not in detection: n.add_face( RectFace ( 20 , 20 , colormap[ref], 'white' ), column = 2 + columnmap[ref] ) n.img_style = nst ###color by species if n.name in speciescolors: nst['bgcolor'] = speciescolors[n.name] else: if n.name.strip() in includenames: n.add_face( AttrFace(attr = 'name', ftype='Helvetica', fgcolor='black', fsize =20 ,fstyle = 'normal' ), column =0 ) nst.size = 2 n.img_style = nst else: nst.size = 0 n.img_style = nst ts = TreeStyle() for i,ref in enumerate(colormap.keys()): if 'ubi' not in ref: ts.title.add_face(TextFace(ref, fsize=12), column=0) ts.title.add_face( RectFace(10 , 10 , colormap[ref] , colormap[ref]), column = 1) ts.show_leaf_name=False """ts.mode = "c" ts.arc_start = 270 ts.arc_span = 359 ts.root_opening_factor = 1 """ ts.scale = 190 t.show(tree_style = ts) t.render(filename + ".png", tree_style = ts) t.render( filename +".svg" , tree_style = ts)