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 populate_legend(ts, nstyles): ts.legend_position = 4 all_files = os.listdir('.') for file in all_files: # find the legend.txt file # this is a hack, should implement a real solution eventually if 'legend.txt' in file: #j = 0 with open(file) as f: for line in f: line = line.strip() line_arr = line.split('\t') x = CircleFace(5, nstyles[line_arr[0]]['fgcolor']) ts.legend.add_face(x, column=0) ts.legend.add_face(TextFace(line_arr[0]), column=1) genome_list = '' for i in range(1, len(line_arr)): if i > 5: genome_list += '...' # too many genomes break if i == len( line_arr ) - 1: # last element shouldn't end with comma genome_list += line_arr[i][1:] else: genome_list += line_arr[i][1:] + ', ' ts.legend.add_face(TextFace(genome_list), column=2)
def my_layout(node): F = TextFace(node.name, tight_text=True, penwidth=5, fsize=12) if node.name is not 'a': add_face_to_node(F, node, column=0, position="branch-right") node.set_style(ns) if node.name in families: G = TextFace(families[node.name], fstyle='italic') add_face_to_node(G, node, column=0, position="branch-right") node.set_style(ns) if node.name in dict_genera: H = TextFace(dict_genera[node.name], fstyle='italic') add_face_to_node(H, node, column=0, position="branch-right") node.set_style(ns) if node.name in dict_species: I = TextFace(dict_species[node.name], fstyle='italic') add_face_to_node(I, node, column=0, position="branch-right") node.set_style(ns) if node.name == 'sumatrana': dict_species[node.name] = '(Sumatran Torrent Frog)' # if node.is_leaf(): # node.img_style["size"] = 0 # img = ImgFace('/home/stine/Desktop/{}.jpg'.format(node.name)) # add_face_to_node(img, node, column=0, aligned=True) for n in Anura.iter_search_nodes(): if n.dist > 1: n.img_style = ns
def attribute_legend(node, authors, styles): indx1 = authors.index(node.name) author_styles = styles[indx1] text = " " counter = 0 for style in author_styles: if counter % 2 == 0: text += " \n " counter += 1 text += style + ", " text = text[:-2] text = " " + text #F = TextFace(node.name, tight_text=True, fsize=15, fgcolor="white") #add_face_to_node(F, node, column=0, position="branch-right") N = TextFace(text, fgcolor="Black", fsize=21, fstyle="bold", bold=False, tight_text=False) if not node.is_leaf(): N.rotation = 90 Nspace = TextFace(" ", fgcolor="Black", fsize=21, bold=True) node.add_face(face=Nspace, column=1) node.add_face(face=N, column=2)
def get_example_tree(tree, color_dict=None, annot_dict=None, col=None): used_colours = set() for n in tree.traverse(): if n.is_leaf(): if n.name in annot_dict: n.img_style["bgcolor"] = color_dict[annot_dict[n.name]] used_colours.add(annot_dict[n.name]) ts = TreeStyle() ts.layout_fn = layout ts.show_leaf_name = False ts.mode = "c" # ts.arc_start = -180 # 0 degrees = 3 o'clock # ts.arc_span = 180 # ts.root_opening_factor = 1 # print (used_colours) for k,v in color_dict.items(): # Check that the specific colour was actually present in the tree we're annotating if k in used_colours: ts.legend.add_face(CircleFace(100, v), column=0) ts.legend.add_face(TextFace(k, fsize=50), column=1) # Add title ts.title.add_face(TextFace("Colouring tips on " + col, fsize=100), column=0) return tree, ts
def traitTree(traits, mapper, outDir): ### 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 for n in tree.traverse(): if n.is_leaf(): n.set_style(nstyle_L) n.add_face(TextFace(str(n.name)), column=0, position="aligned") else: n.set_style(nstyle) #nd = TextFace(str(n.ND)) # label with node ID nd = TextFace(str(int( traits[n.ND]))) # label with rounded continuous trait value nd.background.color = rgb2hex(*[ int(val) for val in mapper(traits[n.ND], gamma=0.8, scaleMax=255) ]) # setup for wl2RGB nd.margin_right = 2 nd.margin_top = 1 nd.margin_left = 2 nd.margin_bottom = 1 nd.border.width = 1 n.add_face(nd, column=0, position="float") n.add_face(TextFace(" "), column=0, position="branch-bottom") #outFile = args.output + "/test_trees/cont_trait.pdf" outFile = outDir + "/cont_trait.pdf" tree.render(outFile, tree_style=tree_style) 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 draw_tree(tree): tree_copy = tree.copy("newick-extended") tree_copy.add_feature("i", tree.i) tree_copy.add_feature("Condition", tree.Condition) for n in tree_copy.traverse(): if n.is_leaf(): n.set_style(nstyle) n.add_face(TextFace(str(n.name)), column=0, position="aligned") else: n.set_style(nstyle) nd = TextFace(str(n.i)) nd.background.color = condi_color_dic[str(n.Condition)] nd.margin_right = 2 nd.margin_top = 1 nd.margin_left = 2 nd.margin_bottom = 1 nd.border.width = 1 if add_transition: if hasattr(n, "Transition"): nd.border.color = "red" nd.border.width = 2 n.add_face(nd, column=0, position="float") n.add_face(TextFace(" "), column=0, position="branch-bottom") return tree_copy
def mylayout(node): # If node is a leaf if node.is_leaf(): # And a line profile add_face_to_node(profileFace, node, 0, aligned=True) node.img_style["size"] = 0 add_face_to_node(nameFace, node, 1, aligned=True) # If node is internal else: # If silhouette is good, creates a green bubble if node.silhouette > 0: validationFace = TextFace("Silh=%0.2f" % node.silhouette, "Verdana", 10, "#056600") node.img_style["fgcolor"] = "#056600" # Otherwise, use red bubbles else: validationFace = TextFace("Silh=%0.2f" % node.silhouette, "Verdana", 10, "#940000") node.img_style["fgcolor"] = "#940000" # Sets node size proportional to the silhouette value. node.img_style["shape"] = "sphere" if node.silhouette <= 1 and node.silhouette >= -1: node.img_style["size"] = 15 + int((abs(node.silhouette) * 10)**2) # If node is very internal, draw also a bar diagram # with the average expression of the partition add_face_to_node(validationFace, node, 0) if len(node) > 100: add_face_to_node(cbarsFace, node, 1)
def my_layout(node): N = None # If user specified labels are specified add these: if 'node_label' in tree_features: for t in tree_features['node_label']: node_attr = ifhasthenget(node, t) if node_attr and to_string(node_attr): if t == 'name' and hasattr(node, 'cl'): continue textface = to_string(node_attr) N = TextFace(textface, fsize=12, fgcolor='black') if 'e-' in textface and to_float( textface ): # Stupid exception because ete3 rendering doesn't understand scientific notation N = TextFace('%2.1e ' % to_float(textface), fsize=12, fgcolor='black') # Add default values: elif not no_default and node.frequency > 1 and not hasattr(node, 'cl'): N = TextFace( node.frequency, fsize=12, fgcolor='black') # Default: use node frequency as TextFace if N is not None: N.rotation = -90 faces.add_face_to_node(N, node, 0, position='branch-top')
def tree_style_with_data(self, data={}, order=None, force_topology=False): """ newick: text or file render_in: default %%inline for notebooks data: {leaf -> col -> value} """ ts = TreeStyle() if data: if not order: # order = list(data.keys()) first = data.keys() first = list(first)[0] order = data[first].keys() ts.show_leaf_name = True ts.draw_guiding_lines = True ts.force_topology = force_topology for i, x in enumerate(order): tf = TextFace(x) tf.margin_left = 5 ts.aligned_header.add_face(tf, column=i) if data: for leaf in self.tree.get_leaves(): for i, col in enumerate(order): tf = TextFace(data[leaf.name][col]) tf.margin_left = 5 leaf.add_face(tf, column=i, position="aligned") return 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 custom_layout(node): if node.is_leaf(): aligned_name_face = TextFace(node.name, fgcolor='olive', fsize=14) add_face_to_node(aligned_name_face, node, column=2, position='aligned') name_face = TextFace(node.name, fgcolor='#333333', fsize=11) add_face_to_node(name_face, node, column=2, position='branch-right') node.img_style['size'] = 0 if node.name in tip2info: # For some reason img urls are very slow! #img_face = ImgFace(tip2info[node.name][0], is_url=True) #add_face_to_node(img_face, node, column=4, position='branch-right') habitat_face = TextFace(tip2info[node.name][2], fsize=11, fgcolor='white') habitat_face.background.color = 'steelblue' habitat_face.margin_left = 3 habitat_face.margin_top = 3 habitat_face.margin_right = 3 habitat_face.margin_bottom = 3 add_face_to_node(habitat_face, node, column=3, position='aligned') else: node.img_style['size'] = 4 node.img_style['shape'] = 'square' if node.name: name_face = TextFace(node.name, fgcolor='grey', fsize=10) name_face.margin_bottom = 2 add_face_to_node(name_face, node, column=0, position='branch-top') if node.support: support_face = TextFace(node.support, fgcolor='indianred', fsize=10) add_face_to_node(support_face, node, column=0, position='branch-bottom')
def add_text_face(self, taxon2text, header_name, color_scale=False): from metagenlab_libs.colors import get_categorical_color_scale if color_scale: value2color = get_categorical_color_scale(taxon2text.values()) self._add_header(header_name) # add column for i, lf in enumerate(self.tree.iter_leaves()): if lf.name in taxon2text: n = TextFace('%s' % taxon2text[lf.name]) if color_scale: n.background.color = value2color[taxon2text[lf.name]] else: print(lf.name, "not in", taxon2text) n = TextFace('-') n.margin_top = 1 n.margin_right = 10 n.margin_left = 10 n.margin_bottom = 1 n.opacity = 1. if self.rotate: n.rotation= 270 lf.add_face(n, self.column_count, position="aligned") self.column_count += 1
def view_by_gene(tree, orthologous_grp, save_file): # Make a copy of the tree tree = copy.deepcopy(tree) for node in tree.traverse(): percents = [ orthologous_grp.regulation_states[(node.name, s)] * 100 for s in ['1', '0', 'A'] ] stacked_bar_face = StackedBarFace(percents, width=30, height=15, colors=['green', 'red', 'blue']) stacked_bar_face.margin_left = 5 stacked_bar_face.margin_right = 5 node.add_face(stacked_bar_face, column=1) # Add locus tag if the genome has the gene from this orthologous group if node.is_leaf(): # Check if the orthologous group contains any gene of the genome gene = orthologous_grp.member_from_genome(node.name) if gene: node.add_face(TextFace(text='[%s]' % gene.locus_tag), column=2) ts = TreeStyle() ts.title.add_face(TextFace(text=orthologous_grp.description), column=1) tree.render(save_file, tree_style=ts)
def add_labels_n_colors_2_tree(tree_path, refseq_2_entropy, colors, feature, out): """ add entropy measurement to a tree and color it's leaves :param tree_path: a path to a tree :param refseq_2_entropy: a data base with entropy values for each refseq id :param out: output directory path to save the results :return: a tree with colors and entropy labels """ print(tree_path) str_tree = tree_2_string(tree_path) if str_tree == '': return tree = Tree(str_tree) # get all refseq ids in the tree and all corresponding entropy values all_leaves = [] for node in tree: if node.is_leaf(): all_leaves.append(node.name) #all_values = refseq_2_entropy[refseq_2_entropy['refseq_id'].isin(all_leaves)]['entropy_5'].values all_values = refseq_2_entropy[feature].values num_leaves = len(all_leaves) # create a gradient color bar #colors = linear_gradient("#DC9221", "#33C193", n=num_leaves) #mapping = value_2_color(all_values, colors['hex']) mapping = value_2_color(all_values, colors['hex']) for node in tree: if node.is_leaf(): value = refseq_2_entropy[refseq_2_entropy['refseq_id'] == node.name.split('.')[0]][feature].values[0] virus_name = refseq_2_entropy[refseq_2_entropy['refseq_id'] == node.name.split('.')[0]]['virus_name'].values[0] # change virus name node.name = virus_name c = mapping[str(value)] node.add_feature("label", value) label_face = TextFace(node.label, fgcolor=c, fsize=22) node.add_face(label_face, column=0, position='branch-right') family = os.path.basename(tree_path).split('.')[0] ts = TreeStyle() ts.mode = 'c' ts.scale = 5 # Disable the default tip names config ts.show_leaf_name = True ts.show_scale = True ts.show_branch_length = True ts.title.add_face(TextFace("{} values for {}".format(feature, family), fsize=20), column=0) # Draw Tree tree.render(os.path.join(out, '{}_{}_tree.pdf'.format(family, feature)), dpi=300, tree_style=ts)
def rotation_layout(node): if node.is_leaf(): F = TextFace(node.name, tight_text=True) F.rotation = randint(0, 360) add_face_to_node(TextFace("third" ), node, column=8, position="branch-right") add_face_to_node(TextFace("second" ), node, column=2, position="branch-right") add_face_to_node(F, node, column=0, position="branch-right") F.border.width = 1 F.inner_border.width = 1
def add_Edges(node, tree, rootNode): def calculate_thickness(child, style): thickness = (child.total_children / rootNode.total_children) * 60 if child.rank == "Superkingdom" or child.rank == "Kingdom": # just to offset MASSIVE thick lines since those two thickness = 3 # will typically contain >90% of all results if thickness < 3: # just to offset later nodes having invisible borders thickness = 3 style["vt_line_width"] = thickness style["hz_line_width"] = thickness return style #unecessary since it passes by reference, but it might be useful in future def highlight_tax(child, style): ranks = {'Name':'FireBrick', 'Species':'Crimson', 'Genus':'Chocolate', 'Family':'Gold', 'Order':'LawnGreen', 'Class':'LimeGreen', 'Phylum':'Turquoise', 'Kingdom':'SteelBlue', 'Superkingdom':'Plum'} style["bgcolor"] = ranks[child.rank] return style #unecessary since it passes by reference, but it might be useful in future for child in node.child_nodes: if child.rank is not ("Name"): # Restricting it to above Species means it won't crash rendering a tree with thousands of results newNode = Tree(name=child.node_name) # Set borders name = TextFace(child.node_name) name.border.width = 1 name.border.color = '#ffffff' # Add name, total children, and rank. newNode.add_face(name,column=0,position="branch-right") children = "[" + str(child.total_children) + "]" newNode.add_face(TextFace(children),column=0, position="branch-bottom") newNode.add_face(TextFace(child.rank),column=0, position="branch-top") # Set colour based on rank and thickness based on total number of node's children. style = NodeStyle() highlight_tax(child, style) calculate_thickness(child, style) newNode.set_style(style) # Keep iterating tree.add_child(newNode) add_Edges(child, newNode, rootNode)
def layout(self, node): try: percents = [ round(100.0 * node.f_a / node.total), round(100.0 * node.f_b / node.total), round(100.0 * node.f_c / node.total), round(100.0 * node.f_ab / node.total), round(100.0 * node.f_ac / node.total), round(100.0 * node.f_bc / node.total), round(100.0 * node.f_all / node.total), round(100.0 * node.f_none / node.total) ] except ZeroDivisionError: txt = TextFace(' ' + node.plainName, ftype='Arial', fgcolor='#000000') else: i = 0 if sum(percents) != 100: x = sorted(percents)[-1] i = percents.index(x) percents[i] += 100 - sum(percents) if self.sqrt: size = int(math.sqrt(node.total) * 5 + 1) else: size = int(math.log10(node.total) * 20 + 10) P = PieChartFace(percents, size, size, self.colors) faces.add_face_to_node(P, node, 0, position="branch-top") #fgcol = mpl_colors.rgb2hex(mpl_colormap.brg(col/10.0)) # foreground/text color depending on NAD consumer density fgcol = '#000000' if node.counter: cnt = float(sum(node.counter)) / float(node.total) txt = TextFace(' {}\n {:.2f}'.format(node.plainName, cnt), ftype='Arial', fgcolor=fgcol) elif self.count: cnt = node.total txt = TextFace(' {}\n {:d}'.format(node.plainName, cnt), ftype='Arial', fgcolor=fgcol) else: txt = TextFace(' ' + node.plainName, ftype='Arial', fgcolor=fgcol) #txt.margin_right = -30 if node.is_leaf(): faces.add_face_to_node(txt, node, 0, position="branch-right") else: faces.add_face_to_node(txt, node, 0, position="branch-bottom")
def add_node(self, node_text, edge_text, is_max): new = self.curr_node.add_child() new.add_face(TextFace(node_text, fsize=12, fgcolor='darkred'), column=0, position='branch-right') tf = TextFace(edge_text, fsize=9, fgcolor='darkgoldenrod') tf.margin_right = 30 new.add_face(tf, column=0, position='branch-bottom') new.set_style(NodeStyle(size=14, fgcolor=('blue' if is_max else 'red'))) self.curr_node = new
def testTrees(scenarios, outDir): ### Draw test trees. This is a modified version of the test routine in pcoc_num_tree.py, stuffed in a for loop for cutoff in sorted(scenarios.keys()): tree = init_tree(args.tree) # not mucking with additive trees yet; ultrametrize the tree and normalize to length 1 tree.convert_to_ultrametric(tree_length=1) manual_mode_nodes = {} manual_mode_nodes = {"T": [], "C": []} p_events = scenarios[cutoff].strip().split("/") for e in p_events: l_e = map(int, e.split(",")) manual_mode_nodes["T"].append(l_e[0]) manual_mode_nodes["C"].extend(l_e[1:]) for n in tree.traverse(): if n.is_leaf(): n.set_style(nstyle_L) n.add_face(TextFace(str(n.name)), column=0, position="aligned") else: n.set_style(nstyle) nd = TextFace(str(n.ND)) if manual_mode_nodes: if n.ND in manual_mode_nodes["T"]: nd.background.color = "red" elif n.ND in manual_mode_nodes["C"]: nd.background.color = "orange" else: nd.background.color = "white" else: nd.background.color = "white" nd.background.color = "white" nd.margin_right = 2 nd.margin_top = 1 nd.margin_left = 2 nd.margin_bottom = 1 nd.border.width = 1 n.add_face(nd, column=0, position="float") n.add_face(TextFace(" "), column=0, position="branch-bottom") # if --float set, limit number of digits in filename if args.float: outFile = str(cutoff).replace( '.', '_')[:np.min([args.float, len(str(cutoff))])] + ".pdf" else: outFile = str(cutoff).replace('.', '_') + ".pdf" # prepend path to filename outFile = outDir + '/' + outFile tree.render(outFile, tree_style=tree_style) print >> sys.stderr, outFile
def attach_counts_to_tree(tree, genome_count_per_family, species_count_per_family): ''' Attaches TextFaces to tree leaves with plastid genome counts per leaf (=family) and leaf name Params: - tree: ete3 tree with family names as leaves - genome_count_per_family: dict with key = family name, value = number of sequenced plastid genomes for that family ''' for leaf in tree.iter_leaves(): leaf.add_face(TextFace(str(leaf.name)), column=0, position="aligned") if leaf.name in genome_count_per_family: leaf.add_face(TextFace("(" + str(species_count_per_family[leaf.name]) + "/" + str(genome_count_per_family[leaf.name]) + ")"), column=1, position="aligned") else: leaf.add_face(TextFace("(" + str(species_count_per_family[leaf.name]) + "/0)"), column=1, position="aligned")
def add_t(node): nd = TextFace("-") nd.fsize = 4 nd.background.color = "black" nd.margin_right = 0 nd.margin_top = 0 nd.margin_left = 0 nd.margin_bottom = 0 nd.border.width = 1 nd2 = TextFace(" ") nd2.fsize = 4 node.add_face(nd, column=0, position = "float") node.add_face(nd2, column=1, position = "float")
def para_from_meta(backpropagation, node, org, table, len_dict): """for paralogs from metadata""" unique_id = org.split('..')[0] group = f"{metadata[unique_id]['Higher Taxonomy']}" paraf = TextFace(f'{metadata[unique_id]["full"]}_{len_dict[org]}@{org}', fgcolor='blue') node.name = '' node.add_face(paraf, column=0) if not backpropagation: table.write( f'{metadata[unique_id]["full"]}_{len_dict[org]}@{org}\t{group}\tp\n' ) gface = TextFace(f'[{group} {metadata[unique_id]["Lower Taxonomy"]}]') node.add_face(gface, column=1, position="aligned")
def add_branch_text(tree, tree_style, node_dict): root_node = tree & 'root' for node in tree.traverse(): if node is root_node: continue T1 = TextFace(node.name, ftype="Monaco", fsize=10) T1.hz_align = 0 node.add_face(T1, 0, 'branch-top') T2 = TextFace('%s%%' % float_trans(node_dict[node.name].profile * 100), ftype="Monaco", fsize=10) T2.hz_align = 0 node.add_face(T2, 0, 'branch-bottom') # print node_dict[node.name].size node.dist = node_dict[node.name].branch_length tree_style.scale = 1
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 add_pie_face(tree, ts, total_profile, group): for leaf_name in tree.iter_leaf_names(): node = tree & leaf_name profile_list = total_profile[node.name] if group is not None: profile_list_grouped = OrderedDict() for sample_name, profile in profile_list.iteritems(): if group[sample_name] not in profile_list_grouped: profile_list_grouped[group[sample_name]] = 0 profile_list_grouped[group[sample_name]] += profile profile_list = pd.Series(profile_list_grouped) col_num = len(profile_list) times = int(math.ceil(col_num / len(COLS_BREWER))) cols = (COLS_BREWER * times)[:col_num] summary = sum(profile_list) if not summary: print profile_list print profile_list_grouped continue percents = map(lambda s: s / summary * 100, profile_list) P = PieChartFace(percents=percents, width=50, height=50, colors=cols) node.add_face(P, 0, 'aligned') #ts.legend.add_face(TextFace(" "), 0) #ts.legend.add_face(TextFace(" "), 1) for ind, g in enumerate(profile_list.index): T = TextFace(' %s ' % g) ts.legend.add_face(T, ind*2%24) C = CircleFace(radius=10, color=cols[ind], style="circle") ts.legend.add_face(C, (ind*2+1)%24) ts.legend_position = 1
def rename_leaves(self, taxon2new_taxon, keep_original=False, add_face=True): for i, lf in enumerate(self.tree.iter_leaves()): #print(dir(lf)) #print((lf.faces[0])) #lf.faces # = None #print("Iter leaf names") #for i in lf.features: # print("i", i) if not keep_original: if lf.name in taxon2new_taxon: label = taxon2new_taxon[lf.name] else: label = 'n/a' else: if lf.name in taxon2new_taxon: label = '%s (%s)' % (taxon2new_taxon[lf.name], lf.name) else: label = 'n/a' print ("add_face", add_face) if add_face: n = TextFace(label, fgcolor = "black", fsize = 12, fstyle = 'italic') lf.add_face(n, 0) lf.name = label
def writeTrees(trees, label): ts = TreeStyle() ts.show_leaf_name = False ts.show_branch_length = False ts.branch_vertical_margin = 20 ts.scale = 0.05 outtrees = open(lengthdir + label + ".newick", "w") #round the branch lengths for index, tree in enumerate(trees): #print(tree) for branch in tree.traverse(): branch.dist = round(branch.dist) line = tree.write(format=1) outtrees.write(line + "\n") if (showTrees): for branch in tree.traverse(): if branch.dist != 0: text_face = TextFace(str(round(branch.dist, 2)), fsize=30) branch.add_face(text_face, column=1, position="branch-top") elif branch.name != "": name_face = AttrFace("name", fsize=30) branch.add_face(name_face, column=0, position="branch-right") else: print("Branch found of length zero but not a tip in tree", label) print(branch) filename = label if len(trees) > 1: filename += "_" + str(index) filename += ".png" tree.render(lengthdir + filename, tree_style=ts) #foo() outtrees.close()
def __init__(self, tree, logger, scale=None, labels_dict=None, node_colors=defaultdict(lambda: 'black')): self.tree = Tree(tree) self.scale = scale for node in self.tree.traverse(): if len(node.children) == 3: logger.info("Trying to root tree by first child of root") logger.info(f'Children of root: {node.children}') self.tree.set_outgroup(node.children[0]) break for node in self.tree.traverse(): # Hide node circles node.img_style['size'] = 0 if node.is_leaf(): try: name_face = TextFace( labels_dict[node.name] if labels_dict else node.name, fgcolor=node_colors[node.name]) except KeyError: msg = f'There is not label for leaf {node.name} in labels file' logger.error(msg) raise KeyError(msg) node.add_face(name_face, column=0)