def plot_tree(newick_in_fn, out_plot_fn, attribute_name): tree = pro.load_nhx_tree(newick_in_fn) ts = ete3.TreeStyle() ts.show_leaf_name = False def my_layout(node): name = getattr(node, attribute_name) try: kmer_full = locale.format("%d", int(node.kmers_full), grouping=True), except AttributeError: kmer_full = None try: kmer_reduced = locale.format("%d", int(node.kmers_reduced), grouping=True) except AttributeError: kmer_reduced = None if kmer_full is None: if kmer_reduced is None: t = name else: t = "{} [red. {}]".format(name, kmer_reduced) else: if kmer_reduced is None: t = "{} [full {}]".format(name, kmer_full) else: t = "{} [full {} & red. {}]".format(name, kmer_full, kmer_reduced) f = ete3.TextFace(t, tight_text=True) ete3.add_face_to_node(f, node, column=0, position="branch-right") ts.layout_fn = my_layout tree.render(out_plot_fn, tree_style=ts)
def draw_tree(plotdir, plotname, treestr, gl_sets, all_genes, gene_categories, ref_label=None, arc_start=None, arc_span=None): etree = ete3.ClusterTree(treestr) node_names = set() # make sure we get out all the genes we put in for node in etree.traverse(): if set_distance_to_zero(node): node.dist = 0. if ref_label is not None else 1e-9 # data crashes sometimes with float division by zero if you set it to 0., but simulation sometimes gets screwed up for some other reason (that I don't understand) if it's 1e-9 # node.dist = 1. status = getstatus(gene_categories, node, ref_label=ref_label) set_node_style(node, status, len(gl_sets), ref_label=ref_label) if node.is_leaf(): node_names.add(node.name) if len(set(all_genes) - node_names) > 0: raise Exception('missing genes from final tree: %s' % ' '.join(node_names)) if ref_label is None: # have to do it in a separate loop so it doesn't screw up the distance setting for node in [n for n in etree.traverse() if n.is_leaf()]: # yeah I'm sure there's a fcn for that node.name = shorten_name(node.name) tstyle = ete3.TreeStyle() tstyle.show_scale = False if not args.leaf_names: tstyle.show_leaf_name = False # tstyle.mode = 'c' # if arc_start is not None: # tstyle.arc_start = arc_start # if arc_span is not None: # tstyle.arc_span = arc_span write_legend(plotdir) if args.title is not None: fsize = 13 tstyle.title.add_face(ete3.TextFace(args.title, fsize=fsize, bold=True), column=0) if args.title_color is not None: # tstyle.title.add_face(ete3.CircleFace(fsize, scolors[args.title]), column=1) tcol = scolors[ args. title_color] if args.title_color in scolors else args.title_color rect_width = 3 if len(args.title) < 12 else 2 tstyle.title.add_face(ete3.RectFace(width=rect_width * fsize, height=fsize, bgcolor=tcol, fgcolor=None), column=1) suffix = '.svg' imagefname = plotdir + '/' + plotname + suffix print ' %s' % imagefname etree.render(imagefname, tree_style=tstyle)
def plot_data_tree(args, plotdir, plotname, glsfnames, glslabels, leg_title=None, title=None): all_genes, gl_sets = get_gene_sets(glsfnames, glslabels) print_data_results(gl_sets) treefname = make_tree(all_genes, plotdir + '/workdir', use_cache=args.use_cache) with open(treefname) as treefile: treestr = treefile.read().strip() # treestr = "(A:0.7,B:0.7):0.3;" etree = ete3.ClusterTree(treestr) node_names = set() # make sure we get out all the genes we put in for node in etree.traverse(): node.dist = 1 status = getdatastatus(gl_sets, node, pair=False) set_node_style(node, status, data=True) if node.is_leaf(): node_names.add(node.name) if len(set(all_genes) - node_names) > 0: raise Exception('missing genes from final tree: %s' % ' '.join(set(all_genes) - node_names)) tstyle = ete3.TreeStyle() tstyle.show_leaf_name = True tstyle.mode = 'c' tstyle.show_scale = False etree.render(plotdir + '/' + plotname + '.svg', h=750, tree_style=tstyle)
def draw_lh(root, image, tree, draw_names): ts = ete3.TreeStyle() ts.show_scale = False ts.scale_length = False ts.legend_position = 1 if not os.path.isfile(tree): raise Exception("File not found:" + tree) with open(tree) as infile: t = ete3.Tree(infile.read()) if root: with open(root) as root_tree_file: root_tree = ete3.Tree(root_tree_file.read()) if get_leaf_set(t) != get_leaf_set(root_tree): raise Exception("leaves don't match") mark_root(t, root_tree) ts.layout_fn = make_render_node(draw_names) leg1 = ete3.faces.TextFace("LWR", fgcolor=color1) #leg2 = ete3.faces.TextFace("Alpha", fgcolor=color2) leg3 = ete3.faces.TextFace("Root Branch", fgcolor=root_color) ts.legend.add_face(leg1, column=0) #ts.legend.add_face(leg2, column=0) if root: ts.legend.add_face(leg3, column=0) ts.show_leaf_name = False t.render(image, tree_style=ts)
def plot_state_tree(state, orders, mode, g): print('Writing ancestral state trees: mode = {}, number of pdf files = {}'.format(mode, state.shape[1]), flush=True) if not is_ete_plottable(): return None if mode=='codon': missing_state = '---' else: missing_state = '-' ts = ete3.TreeStyle() ts.mode = 'r' ts.show_leaf_name = False ts.layout_fn = branch_state_layout ndigit = int(numpy.log10(state.shape[1]))+1 for i in numpy.arange(state.shape[1]): for node in g['tree'].traverse(): if node.is_root(): node.state = missing_state continue nlabel = node.numerical_label index = numpy.where(state[nlabel,i,:]==max(state[nlabel,i,:]))[0] if len(index)==1: node.state = orders[index[0]] elif len(index)==0: node.state = missing_state file_name = 'csubst_state_'+mode+'_'+str(i+1).zfill(ndigit)+'.pdf' g['tree'].render(file_name=file_name, tree_style=ts, units='px', dpi=300)
def __init__(self, label="name", attribute=None, output=None, multiple=False, width=None, height=None, units="px", dpi=300, dummy=False): self.label = label self.attribute = attribute self.output = output self.multiple = multiple self.width = width self.height = height self.units = units self.dpi = dpi self.n = 0 self.dummy = dummy if not self.dummy: # Setup TreeStyle self.ts = ete3.TreeStyle() self.ts.show_scale = False self.ts.show_branch_support = True
def main(name='phytree_show', args=None): myname = 'phytree_show' if name == myname: nwkfile, tree_format, tree_mode, show_leaf_name, show_branch_length, show_branch_support, \ align_leaf_name, hide_inner_node, save_plot, show_inner_name, out_file = getargs(args) tree = ete3.TreeNode(nwkfile, format=tree_format) tree_style = ete3.TreeStyle() tree_style.mode = tree_mode tree_style.show_leaf_name = show_leaf_name tree_style.show_branch_length = show_branch_length if align_leaf_name: tree_style.show_leaf_name = False _align_leaf_name(tree) if hide_inner_node: _hide_inner_node(tree) if show_inner_name: _show_inner_name(tree, tree_format) try: if save_plot: tree.render(out_file, tree_style=tree_style) else: tree.show(tree_style=tree_style) except: print('opps...') return 0
def draw_tree(species, spTree, outfileNameTree): anc = spTree.get_common_ancestor(species) ts = ete3.TreeStyle() ts.show_leaf_name = False ts.layout_fn = geneTree_layout ts.mode = "c" spTree.prune(species) return spTree
def display_tree(self): ts = ete3.TreeStyle() ts.show_scale = False ts.show_leaf_name = True return self.root.ete3_node.render('%%inline', w=200, units='mm', tree_style=ts)
def summary_tree(self): ''' show a tree that visualizes the total number of expansions and contractions across the whole phylogeny for allgene families. ''' def fam_size_piechart_layout(node): ''' the PieChart layout function, defined in local scope so it can access class attributes (graphics options). ''' if not node.is_root(): if self.count_all_expansions: n_exp = node.expansion n_con = node.decrease else: n_exp = node.sig_expansions n_con = node.sig_expansions if hasattr(self, 'lambda_colors'): circle_color = self.lambda_colors[node.lambda_group] else: circle_color = "blue" # add a text that shows expansions & contractions, e.g. +10/-20 exp_cnt_txt = ete3.TextFace( '+{} -{}\n'.format(int(n_exp), int(n_con)), fsize=6, fgcolor=circle_color ) pos = 'aligned' if node.is_leaf() else 'float' # add a circle that shows the average expansion ete3.faces.add_face_to_node(exp_cnt_txt, node, 1, position=pos) # add average expansion info: scale_factor = 1 + node.avg_expansion avg_exp = '{:+}'.format(round(node.avg_expansion, 2)) circle = ete3.CircleFace(radius=9 * scale_factor, color=circle_color, label={'text': avg_exp, 'color': 'white', 'fontsize': 3 + (2.25*scale_factor)}) circle.opacity = self.graphics_options['opacity'] ete3.faces.add_face_to_node(circle, node, 2, position='float') nstyle = ete3.NodeStyle() nstyle['size'] = 0 node.set_style(nstyle) return t = self.tree ts = ete3.TreeStyle() header = 'Family expansions and contractions' if hasattr(self, "lambdas"): header += ('\nmin lambda: {} ' '(blue)\nmax lambda: {} (red)').format( min(self.lambdas.values()), max(self.lambdas.values())) ts.title.add_face(ete3.TextFace(header, fsize=8), column=0) ts.scale = self.graphics_options['pixels_per_mya'] # pixels per million years ts.layout_fn = fam_size_piechart_layout self.show_or_dump_tree(tree_obj=t, tree_style=ts, fname='summary') return
def _get_tree_style(self): ts = ete3.TreeStyle() # Global styles ts.show_scale = False ts.show_leaf_name = False ts.branch_vertical_margin = BRANCH_VERTICAL_MARGIN # Dynamic styles ts.layout_fn = self._layout return ts
def prior_style(tree): ts = ete3.TreeStyle() ts.layout_fn = prior_layout ts.show_leaf_name = True # ts.mode = "c" # tree.show(tree_style=ts) nstyle = ete3.NodeStyle() nstyle['size'] = 0 for n in tree.traverse(): n.set_style(nstyle) return ts
def draw_tree(plotdir, plotname, treestr, gl_sets, all_genes, gene_categories, ref_label=None, arc_start=None, arc_span=None): etree = ete3.ClusterTree(treestr) node_names = set() # make sure we get out all the genes we put in for node in etree.traverse(): if set_distance_to_zero(node): node.dist = 0. if ref_label is not None else 1e-9 # data crashes sometimes with float division by zero if you set it to 0., but simulation sometimes gets screwed up for some other reason (that I don't understand) if it's 1e-9 # node.dist = 1. status = getstatus(gene_categories, node, ref_label=ref_label) set_node_style(node, status, len(gl_sets), ref_label=ref_label) if node.is_leaf(): node_names.add(node.name) if len(set(all_genes) - node_names) > 0: raise Exception('missing genes from final tree: %s' % ' '.join(node_names)) if args.param_dirs is not None: countfo = OrderedDict() for label, pdir in zip(args.glslabels, args.param_dirs): # it would be cleaner to do this somewhere else if pdir == 'None': # not the best way to do this continue countfo[label] = utils.read_overall_gene_probs(pdir, normalize=True)[args.region] for node in etree.traverse(): node.countstr = '%s' % ' '.join([('%.2f' % (100 * cfo[node.name])) if node.name in cfo else '-' for cfo in countfo.values()]) if ref_label is None: # have to do it in a separate loop so it doesn't screw up the distance setting for node in [n for n in etree.traverse() if n.is_leaf()]: # yeah I'm sure there's a fcn for that node.name = utils.shorten_gene_name(node.name) tstyle = ete3.TreeStyle() tstyle.show_scale = False if len(args.glslabels) > 1: write_legend(plotdir) if args.title is not None: fsize = 13 tstyle.title.add_face(ete3.TextFace(args.title, fsize=fsize, bold=True), column=0) if args.title_color is not None: # tstyle.title.add_face(ete3.CircleFace(fsize, scolors[args.title]), column=1) tcol = scolors[args.title_color] if args.title_color in scolors else args.title_color rect_width = 3 if len(args.title) < 12 else 2 tstyle.title.add_face(ete3.RectFace(width=rect_width*fsize, height=fsize, bgcolor=tcol, fgcolor=None), column=1) suffix = '.svg' imagefname = plotdir + '/' + plotname + suffix print ' %s' % imagefname etree.render(utils.insert_before_suffix('-leaf-names', imagefname), tree_style=tstyle) tstyle.show_leaf_name = False etree.render(imagefname, tree_style=tstyle) # NOTE all the node names are screwed up after this, so you'll have to fix them if you add another step if args.param_dirs is not None: for node in etree.traverse(): node.name = node.countstr tstyle.show_leaf_name = True etree.render(utils.insert_before_suffix('-gene-counts', imagefname), tree_style=tstyle)
def _main(): print("Reading matrix from file") root = None output_file_name = None if len(sys.argv) < 2: print("Please supply at least one path to a distance matrix") quit(1) elif sys.argv[1] == "matrix": # Usage: python3 PhyloTree.py matrix OUTPUT_FILE_NAME [PATH_TO_INPUT_MATRICES . . .] node_names_list = [] dist_mat_list = [] for mat in sys.argv[3:]: (node_names, dist_mat) = Utility.read_distance_matrix(mat) node_names_list.append(node_names) dist_mat_list.append(dist_mat) (node_names, dist_mat) = Utility.combine_distance_matrices(node_names_list, dist_mat_list, norm=False) print("Writing combined matrix to {}".format(sys.argv[2])) Utility.write_distance_matrix(dist_mat, node_names, sys.argv[2]) exit(0) elif len(sys.argv) == 2: # Only one matrix provided # Read the distance matrix in to memory (node_names, dist_mat) = Utility.read_distance_matrix(sys.argv[1]) print("Creating tree with Neighbor-Joining from 1 matrix") # Our neighbor joining algorithm creates rooted trees # the root is created a node in the middle of the final edge added to the tree root = create_nj_tree(node_names, dist_mat) gene_name = sys.argv[1].split("/")[-1] output_file_name = "{}_tree.png".format(gene_name) else: # more than one matrix, average them then make tree node_names_list = [] dist_mat_list = [] for mat in sys.argv[1:]: (node_names, dist_mat) = Utility.read_distance_matrix(mat) node_names_list.append(node_names) dist_mat_list.append(dist_mat) (node_names, dist_mat) = Utility.combine_distance_matrices(node_names_list, dist_mat_list, norm=False) print("Creating tree with Neighbor-Joining from {} matrices".format(len(sys.argv[1:]))) root = create_nj_tree(node_names, dist_mat) system_name = sys.argv[1].split("/")[-1] output_file_name = "{}_combined_tree.png".format(system_name) ts = ete3.TreeStyle() ts.show_branch_length = True ts.title.add_face(ete3.TextFace(output_file_name[0:-4], fsize=20), column=0) nstyle = ete3.NodeStyle() nstyle["shape"] = "sphere" nstyle["size"] = 6 nstyle["fgcolor"] = "darkred" for n in root.traverse(): n.set_style(nstyle) root.show(tree_style=ts) root.render(output_file_name, tree_style=ts, units="px", w=600)
def render_tree(fname, tree, annotations, highlight_node, inferred_naive_name, supports=False, support_cuttof=0.8): "render tree SVG" ts = ete3.TreeStyle() ts.show_leaf_name = False tp_colors = timepoint_colors(annotations) seed_lineage = [n for n in iter_lineage(tree, highlight_node)] def my_layout(node): seqmeta = annotations.get(node.name) # handle leaves if seqmeta and not re.compile("naive").match(node.name): leaf_style(node, seqmeta, tp_colors, highlight_node) # Deal with naive and true internal nodes else: # Have to set all node sizes to 0 or we end up distorting the x-axis nstyle = ete3.NodeStyle() nstyle['size'] = 0 node.set_style(nstyle) # Highlight just those nodes in the seedlineage which have nonzero branch lengths, or bad things if node in seed_lineage and node.dist > 0: position = "float" # Note; we use circleface instead of node style to avoid borking the x-axis circle_face = ete3.CircleFace(radius=5, color='brown', style="circle") ete3.add_face_to_node(circle_face, node, column=0, position=position) ts.layout_fn = my_layout if supports: for node in tree.get_descendants(): if node.support and node.support < 0.8: node.support = None ts.show_branch_support = True timepoint_legend(ts, tp_colors) multiplicity_legend(ts) # whether or not we had rerooted on naive before, we want to do so for the SVG tree if inferred_naive_name not in tree.name: tree = reroot_tree(tree, inferred_naive_name) ts.scale = 2300 tree.render(fname, tree_style=ts)
def quickfig(input_tre, outname): """ make a quick ete2 fig. Plots total quartets """ ts = ete3.TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False ts.mode = 'r' ts.draw_guiding_lines = True ts.show_scale = False ts.scale = 25 tre = ete3.Tree(input_tre) tre.ladderize() tre.convert_to_ultrametric(tree_length=len(tre)//2) tre.render(file_name=outname, h=40*len(tre), tree_style=ts)
def display_onetree(tree, treename=None, rootnode=None, ladderize=False, show_internal=False, show_dists=False, nodesize=1, text=False, compact=False, output=None): if rootnode: #print(tree.search_nodes(name=rootnode)) tree = tree.search_nodes(name=rootnode)[0] if ladderize: tree.ladderize() if text: show_attr = ['dist'] if show_dists else None print( tree.get_ascii(show_internal=show_internal, compact=compact, attibutes=show_attr)) else: mynodestyle = ete3.NodeStyle(size=nodesize) ts = ete3.TreeStyle() if show_dists: ts.show_branch_length = True def mybasiclayout(node): node.set_style(mynodestyle) if show_internal: nameface = ete3.faces.AttrFace("name") def mylayout(node): mybasiclayout(node) if not node.is_leaf(): ete3.faces.add_face_to_node(nameface, node, column=0) else: mylayout = mybasiclayout if output: tree.render(output, tree_style=ts, layout=mylayout) else: tree.show(tree_style=ts, layout=mylayout, name=treename)
def draw_gene_trees(trees, allProteins, outFolder): for code in trees: #~ print code t = trees[code] common = set(t.get_leaf_names()).intersection(allProteins) if len(common) > 1: anc = t.get_common_ancestor(common) if not anc.is_root(): anc = anc.up outfileName = outFolder + "/" + code + ".pdf" ts = ete3.TreeStyle() ts.show_leaf_name = False ts.mode = "c" ts.layout_fn = geneTree_layout #anc.show(tree_style=ts) anc.render(outfileName, tree_style=ts, w=200)
def plot_branch_category(tree, file_name, label='all'): if not is_ete_plottable(): return None ts = ete3.TreeStyle() ts.mode = 'r' ts.show_leaf_name = False if label=='all': ts.layout_fn = branch_category_layout ts.branch_vertical_margin = 0 elif label=='leaf': ts.layout_fn = branch_category_layout_leafonly ts.branch_vertical_margin = 0 elif label=='no': ts.layout_fn = branch_category_layout_nolabel ts.branch_vertical_margin = 1 tree.render(file_name=file_name, tree_style=ts, units='mm', w=172)
def produceHOGGainLossTree(HOG_groups_dict, intnode_lossdict, leafnode_lossdict, intnodes, tree, leafname_dict, outdir): import ete3 for n in tree.traverse(): if n.is_leaf() and leafname_dict: n.name = leafname_dict[n.name] schema_names = ete3.COLOR_SCHEMES.keys() def mylayout(n): if not n.is_leaf(): #print("\n\n\nintnode_lossdict", intnode_lossdict.keys()) shortn = int(n.name.split('_')[1]) number_of_hogs = len(HOG_groups_dict[intnodes[shortn]].keys()) number_of_gains = number_of_hogs try: number_of_losses = int(intnode_lossdict[shortn]) except: number_of_losses = 0 #thisface = ete3.faces.BarChartFace([int(number_of_losses), int(number_of_gains)], # colors=ete3.COLOR_SCHEMES["set1"], # #["Tomato","DarkCyan"], # labels=["#Losses","#Gains"], # width=20, height=40, min_value=0, max_value=4100) #thisface.opacity = 0.8 thisfaceA = ete3.faces.TextFace('L: ' + str(int(number_of_losses)) + '\n' + 'G: ' + str(int(number_of_gains))) thisfaceA.opacity = 0.8 ete3.faces.add_face_to_node(thisfaceA, n, column=0, position="branch-right") ete3.faces.add_face_to_node(ete3.AttrFace("name"), n, column=1) else: pass #ete3.faces.add_face_to_node(ete3.AttrFace("name"), n, column=0) # for n in tree.traverse(): # if not n.is_leaf(): ts = ete3.TreeStyle() ts.layout_fn = mylayout #ts.rotation = 90 ts.allow_face_overlap = True ts.title.add_face(ete3.faces.TextFace("HOG Gain Loss Eventcount", fsize=20), column=0) tree.render(os.path.join(outdir,"img_faces.png"), tree_style = ts)
def produce_mapped_root_images(results_summary, print_node_name=False): def make_key(exp): return (exp.taxa, exp.sites) colors = ['Green', 'Red', 'Blue'] prog_names = { 'iq': 'IQ-TREE', 'rd_es': 'RootDigger ES', 'rd_nes': 'RootDigger No ES' } progs = sorted(results_summary.get_programs()) exps = results_summary.get_experiments() def layout(node): for idx, prog in enumerate(progs): text = str(getattr(node, prog) if hasattr(node, prog) else (0)) label = ete3.faces.TextFace(text, fgcolor=colors[idx]) if hasattr(node, prog) and getattr(node, prog) == 100: label.inner_border.type = 0 label.inner_border.type = 1 node.add_face(label, column=0) if node.name and print_node_name: node.add_face(ete3.faces.TextFace(node.name), column=1) ts = ete3.TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False ts.show_scale = False ts.scale_length = False ts.legend_position = 1 cur_col = 0 for idx, prog in enumerate(progs): leg = ete3.faces.TextFace(prog_names[prog], fgcolor=colors[idx]) ts.legend.add_face(leg, column=cur_col) for exp in exps: exp_key = make_key(exp) mapped_tree = results_summary.get_true_tree(exp.taxa, exp.sites).copy() for prog in progs: for r in results_summary.select(prog, exp.taxa, exp.sites): map_root(prog, mapped_tree, r.left_clade_list, r.right_clade_list) tree_image_name = "{taxa}_{align}.svg".format(taxa=exp.taxa, align=exp.sites) mapped_tree.render(tree_image_name, tree_style=ts)
def plot_trees(args): treefo = read_input(args) etree = ete3.Tree(treefo['treestr'], format=1) tstyle = ete3.TreeStyle() # tstyle.show_scale = False # tstyle.scale_length = args.lb_tau # tstyle.show_branch_length = True # tstyle.complete_branch_lines_when_necessary = True if args.metafo is not None: set_meta_styles(args, etree, tstyle) print ' %s' % args.outfname tstyle.show_leaf_name = False etree.render(args.outfname, tree_style=tstyle)
def array2tree(d, names, outbase="", method="ward"): """Return tree representation for array""" import ete3 Z = fastcluster.linkage(d[np.triu_indices(d.shape[0], 1)], method=method) tree = sch.to_tree(Z, False) t = ete3.Tree(getNewick(tree, "", tree.dist, names)) # save tree & newick if outbase: pdf, nw = outbase+".nw.pdf", outbase+".nw" with open(nw, "w") as out: out.write(t.write()) ts = ete3.TreeStyle() ts.show_leaf_name = False ts.layout_fn = mylayout t.render(pdf, tree_style=ts) return t
def tree_plot(tree_pk, feature_names=[], show_names=False, return_ete=False): tree_result = Result.objects.get(pk=tree_pk) newick_str = tree_result.get_value("newick") tree = ete3.Tree(newick_str) if return_ete: return tree ts = ete3.TreeStyle() ts.show_leaf_name = show_names ts.mode = "c" ts.root_opening_factor = 0.075 ts.arc_start = -180 # 0 degrees = 3 o'clock ts.arc_span = 360 tree = tree.get_common_ancestor(feature_names) svg = tree.render("%%return", tree_style=ts)[0].replace("b'", "'").strip("'").replace( "\\n", "").replace("\\'", "") svg = svg.replace("<svg ", "<svg class=\"img-fluid\" ") return svg
def show(self, mode=None, inline=False, styling=None, **kwargs): "Display the tree." # Check if a tree styling dict was specified if styling: # Assemble the treestyle object ts = ete3.TreeStyle() for key, value in styling.items(): setattr(ts, key, value) # Update the arguments list kwargs['tree_style'] = ts # Inline Jupyter output if inline or (mode == 'inline'): return self.render('%%inline', **kwargs) else: # Tree GUI rendering return super().show(**kwargs)
def make_tree_vis(newick_tree, gene_name, file_name): """ Create visualizations of maximum-likelihood trees generated using ete """ tree = et.Tree(newick_tree) #Customizations nifty = et.TreeStyle() nifty.show_branch_support = True nifty.branch_vertical_margin = 15 nifty.scale = 10 #Leaf node customizations style_L = et.NodeStyle() style_L['shape'] = 'sphere' style_L['size'] = 10 style_L['fgcolor'] = '#6BC245' style_L['hz_line_type'] = 1 style_L['hz_line_color'] = '#cccccc' #Internal node customizations style_I = et.NodeStyle() style_I['shape'] = 'sphere' style_I['size'] = 10 style_I['fgcolor'] = '#5271FF' style_I['hz_line_type'] = 1 style_I['hz_line_color'] = '#cccccc' #Apply stylizations for node in tree.traverse(): if node.is_leaf(): node.set_style(style_L) else: node.set_style(style_I) #Annotate root of tree with gene name gene_label = et.TextFace(gene_name, ftype="Helvetica", fsize=5,\ fgcolor='green') tree.add_face(gene_label, column=0, position="branch-top") tree.render(file_name + "_tree.png", tree_style=nifty)
def array2tree(d, names, outbase="", method="ward"): """Return tree representation for array""" # cluster Z = sch.linkage(d[np.triu_indices(d.shape[0], 1)], method=method) # get ete Tree t = distance_matrix2tree(Z, names) # save tree & newick if outbase: pdf, nw = outbase+".nw.pdf", outbase+".nw" with open(nw, "w") as out: out.write(t.write()) ts = ete3.TreeStyle() ts.show_leaf_name = False ts.layout_fn = mylayout t.render(pdf, tree_style=ts) return t
def PhylTree_draw(phyltree, images=None): """Draw tree in a gui window using Ete3""" import ete3 ptree = PhylTree_to_ete3(phyltree) ts = ete3.TreeStyle() ts.scale = 2 ts.show_branch_length = True nameface = ete3.faces.AttrFace("name", fsize=12) def mylayout(node): if node.is_leaf(): # add species image pass else: ete3.faces.add_face_to_node(nameface, node, column=0, position='branch-top') ptree.show(layout=mylayout, tree_style=ts, name='Species tree')
def visualize(self, fileName): t = self.rootNode.visualize() ts = ete3.TreeStyle() def my_layout(node): if node.is_leaf(): # If terminal node, draws its name name_face = ete3.AttrFace("name") else: # If internal node, draws label with smaller font size name_face = ete3.AttrFace("name", fsize=10) # Adds the name face to the image at the preferred position ete3.faces.add_face_to_node(name_face, node, column=0, position="branch-right") ts.layout_fn = my_layout ts.show_leaf_name = False t.render(file_name=fileName, tree_style=ts) pass
def write_tree(phy, out, evc, attributes, sep="|", do_print=True, cut_gene_names=120): logging.info("Print tree") phy_alter = phy.copy(method="newick-extended") for i in phy_alter.get_leaves(): i_name = i.name for attribute in attributes: c = evc[evc["node"] == i_name][attribute].values if c.size == 0: c = "NA" else: c = c[0] # cut if string is too long if cut_gene_names is not None: cut_gene_names = int(cut_gene_names) if len(c) > cut_gene_names + 3: c = c[:cut_gene_names] + '...' i.name = str(i.name) + sep + str(c) i.name = str(i.name) + sep phy_alter.write(outfile=out) # print tree in pdf if do_print: ts = ete3.TreeStyle() ts.show_branch_support = True ts.show_leaf_name = False ts.complete_branch_lines_when_necessary = False ts.scale = 120 phy_alter.render("%s.pdf" % out, tree_style=ts)