def tree_layout(node): """ TODO """ if node.is_leaf(): nameSize = 14 nameColor = '#009000' relAbundSize = 10 else: nameSize = 10 nameColor = '#303030' relAbundSize = 8 nameFace = faces.TextFace(node.name, fsize=nameSize, fgcolor=nameColor) nameFace.margin_bottom = 5 nameFace.margin_right = 10 nameFace.margin_left = 5 faces.add_face_to_node(nameFace, node, column=0, position='branch-top') relAbundFace = faces.TextFace(node.rel_abund, fsize=relAbundSize, fgcolor='#2148c8') relAbundFace.margin_top = 5 relAbundFace.margin_left = 5 faces.add_face_to_node(relAbundFace, node, column=0, position='branch-bottom')
def mylayout(node): # If node is a leaf if node.is_leaf(): # And a line profile faces.add_face_to_node(profileFace, node, 0, aligned=True) node.img_style["size"] = 0 faces.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 = faces.TextFace("Silh=%0.2f" % node.silhouette, "Verdana", 10, "#056600") node.img_style["fgcolor"] = "#056600" # Otherwise, use red bubbles else: validationFace = faces.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 faces.add_face_to_node(validationFace, node, 0) if len(node) > 100: faces.add_face_to_node(cbarsFace, node, 1)
def phyparts_pie_layout(mynode): if mynode.name in phyparts_pies: pie = faces.PieChartFace( phyparts_pies[mynode.name], #colors=COLOR_SCHEMES["set1"], colors=["blue", "green", "red", "dark gray"], width=50, height=50) pie.border.width = None pie.opacity = 0.5 faces.add_face_to_node(pie, mynode, 0, position="branch-right") concord_text = faces.TextFace(str(int(concord_dict[mynode.name])) + ' ', fsize=20) conflict_text = faces.TextFace(str(int(conflict_dict[mynode.name])) + ' ', fsize=20) faces.add_face_to_node(concord_text, mynode, 0, position="branch-top") faces.add_face_to_node(conflict_text, mynode, 0, position="branch-bottom") else: F = faces.TextFace(mynode.name, fsize=20) faces.add_face_to_node(F, mynode, 0, position="aligned")
def mylayout(node): # If node is a leaf, add the nodes name and a its scientific # name if node.is_leaf(): # Add an static face that handles the node name faces.add_face_to_node(nameFace, node, column=0) # We can also create faces on the fly longNameFace = faces.TextFace(code2name[node.name]) faces.add_face_to_node(longNameFace, node, column=0) # text faces support multiline. We add a text face # with the whole description of each leaf. descFace = faces.TextFace(code2desc[node.name], fsize=10) # Note that this faces is added in "aligned" mode faces.add_face_to_node(descFace, node, column=0, aligned=True) # Sets the style of leaf nodes node.img_style["size"] = 12 node.img_style["shape"] = "circle" #If node is an internal node else: # Sets the style of internal nodes node.img_style["size"] = 6 node.img_style["shape"] = "circle" node.img_style["fgcolor"] = "#000000" # If an internal node contains more than 4 leaves, add the # images of the represented species sorted in columns of 2 # images max. if len(node) >= 4: col = 0 for i, name in enumerate(set(node.get_leaf_names())): if i > 0 and i % 2 == 0: col += 1 # Add the corresponding face to the node if name.startswith("Dme"): faces.add_face_to_node(flyFace, node, column=col) elif name.startswith("Dre"): faces.add_face_to_node(fishFace, node, column=col) elif name.startswith("Mms"): faces.add_face_to_node(mouseFace, node, column=col) elif name.startswith("Ptr"): faces.add_face_to_node(chimpFace, node, column=col) elif name.startswith("Hsa"): faces.add_face_to_node(humanFace, node, column=col) elif name.startswith("Cfa"): faces.add_face_to_node(dogFace, node, column=col) # Modifies this node's style node.img_style["size"] = 16 node.img_style["shape"] = "sphere" node.img_style["fgcolor"] = "#AA0000" # If leaf is "Hsa" (h**o sapiens), highlight it using a # different background. if node.is_leaf() and node.name.startswith("Hsa"): node.img_style["bgcolor"] = "#9db0cf"
def mylayout(node): if node.is_leaf(): longNameFace = faces.TextFace(code_name[node.name], fsize=15, fgcolor="green") faces.add_face_to_node(longNameFace, node, column=0)
def layout(node): if node.is_leaf(): pretty_name = names[node.name] if node.name in names else node.name # derp = AttrFace("name", fsize=10, ftype="Arial", fgcolor="black") pretty_name_face = faces.TextFace(pretty_name) pretty_name_face.margin_left = 5 faces.add_face_to_node(pretty_name_face, node, column=0)
def tree_to_png(self, filepath: str): nodes = list() for i in range(self.leafs.shape[0]): thisNode = Tree() thisNode.add_face( faces.BarChartFace( self.leafs[i].detach().cpu().numpy(), labels=self.action_labels, min_value=0.0, max_value=self.leafs[i].max().detach().cpu().numpy() + 1e-7, ), 0) nodes.append(thisNode) for d in range(self.depth-1): for node_i in range(self.nodes_beta[d].shape[0]): thisNode = Tree() thisNode.add_child(nodes.pop(1)) thisNode.add_child(nodes.pop(0)) beta = F.softmax(self.nodes_beta[d][node_i].squeeze(), 0 ).detach().cpu().numpy() phi = self.nodes_phi[d][node_i].squeeze().detach().cpu().item() thisNode.add_face( faces.BarChartFace( beta, labels=self.labels, min_value=0.0, max_value=1.0 ), 0) thisNode.add_face( faces.TextFace('phi: {0:.3f}'.format(phi)), 0) nodes.append(thisNode) if filepath is not None: nodes[0].render(filepath) return nodes[0]
def create_phylo_tree(self): """ Creates a basic tree with only the leafs and branches by reading the tree file in nwk format. """ self.ts = TreeStyle() self.ts.show_leaf_name = True self.ts.layout_fn = master_ly self.ts.title.add_face(faces.TextFace("Phyolgenetic tree showing BGCs per organism", fsize=25), 0) self.tree = Tree(self.nwk)
def layout(node): node.img_style['size'] = 0 node.img_style['vt_line_width'] = 0 node.img_style['hz_line_width'] = 0 if "bgcolor" in node.features: node.img_style['bgcolor'] = node.bgcolor if node.is_leaf(): if not args.no_names: name = faces.TextFace(node.sci_name, fsize=12, fstyle='italic') faces.add_face_to_node(name, node, 0, aligned=True) fake = faces.TextFace(" ") fake.background.color = "white" faces.add_face_to_node(fake, node, 1, aligned=True) # fake else: if not args.no_internal_names and node.get_distance( tNCBI, topology_only=True) < 3: name = faces.TextFace(node.sci_name, fsize=12, fstyle='italic') faces.add_face_to_node(name, node, 0, position='branch-top')
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 layout(node): node.img_style["size"] = 0 #add boostrap in not-leaf nodes if not node.is_leaf(): boostFace = faces.TextFace(node.support, fgcolor="grey", fsize=34) add_face_to_node(boostFace, node, column=0, position="branch-top") if node.is_leaf(): #get taxid and name taxid = (node.name.split('.')[0]) seq_name = (node.name.split('.')[1]) #add predicted name (eggnog-mapper) try: pred_name = predict_name[node.name] predNameFace = faces.TextFace(pred_name, fgcolor="salmon", fsize=34) predNameFace.margin_right = 20 predNameFace.margin_left = 20 add_face_to_node(predNameFace, node, column=2, position="branch-right") except: predNameFace = faces.TextFace('--', fgcolor="salmon", fsize=34) add_face_to_node(predNameFace, node, column=2, position="branch-right") #add sequence name (seq_name) seqNameFace = faces.TextFace(seq_name, fgcolor="grey", fsize=34) add_face_to_node(seqNameFace, node, column=1, position="branch-right") #get scientific name from taxid sp_name = ncbi.get_taxid_translator([(node.name.split('.')[0])]) node.name = sp_name[int(taxid)] #add alignment seqFace = SeqMotifFace(node.sequence, gap_format="blank") add_face_to_node(seqFace, node, column=3, position="aligned")
def layout(node): if node.is_leaf(): longNameFace = faces.TextFace(code_name[node.name], fsize=15, fgcolor="green") faces.add_face_to_node(longNameFace, node, column=0) if "weight" in node.features: C = CircleFace(radius=node.weight, color="blue", style="sphere") C.opacity = 0.3 faces.add_face_to_node(C, node, 0, position="float")
def get_example_tree(): with open("avian_tree", "r") as infile: data = infile.read() t = Tree(data) 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 hard_tree_to_png(self, filepath: str): nodes = list() leaf_tmpl = '{}: y_{}' for i in range(self.leafs.shape[0]): thisNode = Tree() if self.continuous: thisNode.add_face( faces.BarChartFace( self.leafs[i].detach().cpu().numpy(), min_value=0.0, max_value=self.leafs[i].max().detach().cpu().numpy() + 1e-7, labels=self.action_labels ), 0) else: max_leaf_idx = np.argmax(self.leafs[i].detach().cpu().numpy()) thisNode.add_face(faces.TextFace( leaf_tmpl.format( self.action_labels[max_leaf_idx], max_leaf_idx)), 0) nodes.append(thisNode) node_tmpl = '{}: x_{} >= {}' for d in range(self.depth-1): for node_i in range(self.nodes_beta[d].shape[0]): thisNode = Tree() thisNode.add_child(nodes.pop(1)) thisNode.add_child(nodes.pop(0)) beta = F.softmax(self.nodes_beta[d][node_i].squeeze(), 0 ).detach().cpu().numpy() phi = self.nodes_phi[d][node_i].squeeze().detach().cpu().item() max_beta_idx = np.argmax(beta) thisNode.add_face(faces.TextFace(node_tmpl.format( self.labels[max_beta_idx], max_beta_idx, phi)), 0) nodes.append(thisNode) if filepath is not None: nodes[0].render(filepath,) return nodes[0]
def add_section_annotations(tree: Tree) -> None: """Annotates taxonomic sections. Pretty hacky. Finds first common ancestor of leaf nodes per section, then sets a bgcolor. If a section contains a single node, then only that node is styled. Also adds a section label, but exact position is determined by which node gets found first using search_nodes(). Relies on accurate section annotation - FP strains were set to Talaromyces which breaks this. """ leaves = tree.get_leaf_names() sections = defaultdict(list) for strain in session.query(Strain).filter(Strain.id.in_(leaves)): if "FP" in strain.species.epithet: continue sections[strain.species.section.name].append(str(strain.id)) index = 0 colours = [ "LightSteelBlue", "Moccasin", "DarkSeaGreen", "Khaki", "LightSalmon", "Turquoise", "Thistle" ] for section, ids in sections.items(): # Find MRCA and set bgcolor of its node style = NodeStyle() style["bgcolor"] = colours[index] if len(ids) == 1: node = tree.search_nodes(name=ids[0])[0] else: node = tree.get_common_ancestor(*ids) node.set_style(style) # Grab first node found in this section, and add section label node = tree.search_nodes(name=ids[0])[0] face = faces.TextFace(section, fsize=20) node.add_face(face, column=1, position="aligned") # Wraparound colour scheme index += 1 if index > len(colours) - 1: index = 0
def aligned_faces(node): if node.is_leaf(): for i in xrange(3): F = faces.TextFace("ABCDEFGHIJK"[0:random.randint(1, 11)]) F.border.width = 1 F.border.line_style = 1 F.inner_background.color = "lightgreen" F.border.width = 1 F.inner_border.width = 1 F.background.color = "darkgreen" F.border.width = 2 F.vt_align = random.randint(0, 4) F.hz_align = random.randint(0, 4) F.margin_bottom = random.randint(1, 20) F.margin_right = random.randint(1, 20) F.margin_left = random.randint(1, 20) F.margin_top = random.randint(1, 20) faces.add_face_to_node(F, node, i, position="aligned") if random.randint(0, 1): faces.add_face_to_node(F, node, i, position="aligned")
def node_viz(self): thisNode = Tree() thisNode.set_style(NodeStyle(shape='square')) if self.child2 is not None: thisNode.add_child(self.child2.node_viz()) if self.child1 is not None: thisNode.add_child(self.child1.node_viz()) if self.child1 is not None and self.child2 is not None: thisNode.add_face( faces.BarChartFace( self.beta.squeeze().detach().cpu().numpy(), labels=self.labels, min_value=0.0, max_value=self.beta.max().detach().cpu().item()), 0) thisNode.add_face( faces.TextFace("phi: {0:.3f}".format(self.phi.item())), 0) else: thisNode.add_face( faces.BarChartFace( self.beta.squeeze().detach().cpu().numpy(), min_value=0.0, max_value=self.beta.max().detach().cpu().item()), 0) return thisNode
def bub_tree(tree, fasta, outfile1, root, types, c_dict, show, size, colours, field1, field2, scale, multiplier, dna): """ :param tree: tree object from ete :param fasta: the fasta file used to make the tree :param outfile1: outfile suffix :param root: sequence name to use as root :param types: tree type: circular (c) or rectangle (r) :param c_dict: dictionary mapping colour to time point (from col_map) :param show: show the tree in a gui (y/n) :param size: scale the terminal nodes by frequency information (y/n) :param colours: if using a matched fasta file, colour the sequence by charge/IUPAC :param field1: the field that contains the size/frequency value :param field2: the field that contains the size/frequency value :param scale: how much to scale the x axis :param multiplier :param dna true/false, is sequence a DNA sequence? :param t_list list of time points :return: None, outputs svg/pdf image of the tree """ if multiplier is None: mult = 500 else: mult = multiplier if dna: dna_prot = 'dna' bg_c = { 'A': 'green', 'C': 'blue', 'G': 'black', 'T': 'red', '-': 'grey', 'X': 'white' } fg_c = { 'A': 'black', 'C': 'black', 'G': 'black', 'T': 'black', '-': 'black', 'X': 'white' } else: dna_prot = 'aa' bg_c = { 'K': '#145AFF', 'R': '#145AFF', 'H': '#8282D2', 'E': '#E60A0A', 'D': '#E60A0A', 'N': '#00DCDC', 'Q': '#00DCDC', 'S': '#FA9600', 'T': '#FA9600', 'L': '#0F820F', 'I': '#0F820F', 'V': '#0F820F', 'Y': '#3232AA', 'F': '#3232AA', 'W': '#B45AB4', 'C': '#E6E600', 'M': '#E6E600', 'A': '#C8C8C8', 'G': '#EBEBEB', 'P': '#DC9682', '-': 'grey', 'X': 'white' } fg_c = { 'K': 'black', 'R': 'black', 'H': 'black', 'E': 'black', 'D': 'black', 'N': 'black', 'Q': 'black', 'S': 'black', 'T': 'black', 'L': 'black', 'I': 'black', 'V': 'black', 'Y': 'black', 'F': 'black', 'W': 'black', 'C': 'black', 'M': 'black', 'A': 'black', 'G': 'black', 'P': 'black', '-': 'grey', 'X': 'white' } if colours == 3: bg_c = None fg_c = None # outfile3 = str(outfile1.replace(".svg", ".nwk")) tstyle = TreeStyle() tstyle.force_topology = False tstyle.mode = types tstyle.scale = scale tstyle.min_leaf_separation = 0 tstyle.optimal_scale_level = 'full' # 'mid' # tstyle.complete_branch_lines_when_necessary = False if types == 'c': tstyle.root_opening_factor = 0.25 tstyle.draw_guiding_lines = False tstyle.guiding_lines_color = 'slateblue' tstyle.show_leaf_name = False tstyle.allow_face_overlap = True tstyle.show_branch_length = False tstyle.show_branch_support = False TreeNode(format=0, support=True) # tnode = TreeNode() if root is not None: tree.set_outgroup(root) # else: # r = tnode.get_midpoint_outgroup() # print("r", r) # tree.set_outgroup(r) time_col = [] for node in tree.traverse(): # node.ladderize() if node.is_leaf() is True: try: name = node.name.split("_") time = name[field2] kind = name[3] # print(name) except: time = 'zero' name = node.name print("Incorrect name format for ", node.name) if size is True: try: s = 20 + float(name[field1]) * mult except: s = 20 print("No frequency information for ", node.name) else: s = 20 colour = c_dict[time] time_col.append((time, colour)) nstyle = NodeStyle() nstyle["fgcolor"] = colour nstyle["size"] = s nstyle["hz_line_width"] = 10 nstyle["vt_line_width"] = 10 nstyle["hz_line_color"] = colour nstyle["vt_line_color"] = 'black' nstyle["hz_line_type"] = 0 nstyle["vt_line_type"] = 0 node.set_style(nstyle) if root is not None and node.name == root: # place holder in case you want to do something with the root leaf print('root is ', node.name) # nstyle["shape"] = "square" # nstyle["fgcolor"] = "black" # nstyle["size"] = s # nstyle["shape"] = "circle" # node.set_style(nstyle) else: nstyle["shape"] = "circle" node.set_style(nstyle) if fasta is not None: seq = fasta[str(node.name)] seqFace = SequenceFace(seq, seqtype=dna_prot, fsize=10, fg_colors=fg_c, bg_colors=bg_c, codon=None, col_w=40, alt_col_w=3, special_col=None, interactive=True) # seqFace = SeqMotifFace(seq=seq, motifs=None, seqtype=dna_prot, gap_format=' ', seq_format='()', scale_factor=20, # height=20, width=50, fgcolor='white', bgcolor='grey', gapcolor='white', ) # seqFace = SeqMotifFace(seq, seq_format="seq", fgcolor=fg_c, bgcolor=bg_c) #interactive=True (tree & node.name).add_face(seqFace, 0, "aligned") else: nstyle = NodeStyle() nstyle["size"] = 0.1 nstyle["hz_line_width"] = 10 nstyle["vt_line_width"] = 10 node.set_style(nstyle) continue tree.ladderize() # tnode.ladderize() legendkey = sorted(set(time_col)) legendkey = [(tp, col) for tp, col in legendkey] # legendkey.insert(0, ('Root', 'black')) legendkey.append(('', 'white')) for tm, clr in legendkey: tstyle.legend.add_face(faces.CircleFace(30, clr), column=0) tstyle.legend.add_face(faces.TextFace('\t' + tm, ftype='Arial', fsize=60, fgcolor='black', tight_text=True), column=1) if show is True: tree.show(tree_style=tstyle) tree.render(outfile1, dpi=600, tree_style=tstyle)
def get_example_tree(): t = Tree() t.populate(10) # Margins, alignment, border, background and opacity can now be set for any face rs1 = faces.TextFace("branch-right\nmargins&borders", fsize=12, fgcolor="#009000") rs1.margin_top = 10 rs1.margin_bottom = 50 rs1.margin_left = 40 rs1.margin_right = 40 rs1.border.width = 1 rs1.background.color = "lightgreen" rs1.inner_border.width = 0 rs1.inner_border.line_style = 1 rs1.inner_border.color = "red" rs1.opacity = 0.6 rs1.hz_align = 2 # 0 left, 1 center, 2 right rs1.vt_align = 1 # 0 left, 1 center, 2 right br1 = faces.TextFace("branch-right1", fsize=12, fgcolor="#009000") br2 = faces.TextFace("branch-right3", fsize=12, fgcolor="#009000") # New face positions (branch-top and branch-bottom) bb = faces.TextFace("branch-bottom 1", fsize=8, fgcolor="#909000") bb2 = faces.TextFace("branch-bottom 2", fsize=8, fgcolor="#909000") bt = faces.TextFace("branch-top 1", fsize=6, fgcolor="#099000") # And faces can also be used as headers or foot notes of aligned # columns t1 = faces.TextFace("Header Face", fsize=12, fgcolor="#aa0000") t2 = faces.TextFace("Footer Face", fsize=12, fgcolor="#0000aa") # Attribute faces can now contain prefix and suffix fixed text aligned = faces.AttrFace("name", fsize=12, fgcolor="RoyalBlue", text_prefix="Aligned (", text_suffix=")") # horizontal and vertical alignment per face aligned.hz_align = 1 # 0 left, 1 center, 2 right aligned.vt_align = 1 # 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) style = NodeStyle() style["fgcolor"] = "Gold" style["shape"] = "square" style["size"] = 15 style["vt_line_color"] = "#ff0000" t.set_style(style) # add a face to the style. This face will be render in any node # associated to the style. fixed = faces.TextFace("FIXED branch-right", fsize=11, fgcolor="blue") t.add_face(fixed, column=1, position="branch-right") # Bind the precomputed style to the root node # ETE 2.1 has now support for general image properties ts = TreeStyle() # You can add faces to the tree image (without any node # associated). They will be used as headers and foot notes of the # aligned columns (aligned faces) ts.aligned_header.add_face(t1, column=0) ts.aligned_header.add_face(t1, 1) ts.aligned_header.add_face(t1, 2) ts.aligned_header.add_face(t1, 3) t1.hz_align = 1 # 0 left, 1 center, 2 right t1.border.width = 1 ts.aligned_foot.add_face(t2, column=0) ts.aligned_foot.add_face(t2, 1) ts.aligned_foot.add_face(t2, 2) ts.aligned_foot.add_face(t2, 3) t2.hz_align = 1 # Set tree image style. Note that aligned header and foot is only # visible in "rect" mode. ts.mode = "r" ts.scale = 10 for node in t.traverse(): # If node is a leaf, add the nodes name and a its scientific # name if node.is_leaf(): node.add_face(aligned, column=0, position="aligned") node.add_face(aligned, column=1, position="aligned") node.add_face(aligned, column=3, position="aligned") else: node.add_face(bt, column=0, position="branch-top") node.add_face(bb, column=0, position="branch-bottom") node.add_face(bb2, column=0, position="branch-bottom") node.add_face(br1, column=0, position="branch-right") node.add_face(rs1, column=0, position="branch-right") node.add_face(br2, column=0, position="branch-right") return t, ts
def main_layout(node): ''' Main layout function. It controls what is shown in tree images. ''' # Add faces to leaf nodes. This allows me to add the faces from # the global variable LEAVE_FACES, which is set by the application # controler according to the arguments passed through the URL. if node.is_leaf(): for f, fkey, pos in LEAVE_FACES: if hasattr(node, fkey): faces.add_face_to_node(f, node, column=pos, position="branch-right") else: # Add special faces on collapsed nodes if hasattr(node, "hide") and int(node.hide) == 1: node.img_style["draw_descendants"] = False collapsed_face = faces.TextFace(\ " %s collapsed leaves." %len(node), \ fsize=10, fgcolor="#444", ftype="Arial") faces.add_face_to_node(collapsed_face, node, 0) else: node.img_style["draw_descendants"] = True # Set node aspect. This controls which node features are used to # control the style of the tree. You can add or modify this # features, as well as their behaviour if node.is_leaf(): node.img_style["shape"] = "square" node.img_style["size"] = 4 else: node.img_style["size"] = 8 node.img_style["shape"] = "sphere" # Evoltype: [D]uplications, [S]peciations or [L]osess. if hasattr(node, "evoltype"): if node.evoltype == 'D': node.img_style["fgcolor"] = "#1d176e" node.img_style["hz_line_color"] = "#1d176e" node.img_style["vt_line_color"] = "#1d176e" elif node.evoltype == 'S': node.img_style["fgcolor"] = "#FF0000" node.img_style["line_color"] = "#FF0000" elif node.evoltype == 'L': node.img_style["fgcolor"] = "#777777" node.img_style["vt_line_color"] = "#777777" node.img_style["hz_line_color"] = "#777777" node.img_style["line_type"] = 1 # If no evolutionary information, set a default style else: node.img_style["fgcolor"] = "#000000" node.img_style["vt_line_color"] = "#000000" node.img_style["hz_line_color"] = "#000000" # Parse node features features and conver them into styles. This # must be done like this, since current ete version does not allow # modifying style outside the layout function. if hasattr(node, "bsize"): node.img_style["size"] = int(node.bsize) if hasattr(node, "shape"): node.img_style["shape"] = node.shape if hasattr(node, "bgcolor"): node.img_style["bgcolor"] = node.bgcolor if hasattr(node, "fgcolor"): node.img_style["fgcolor"] = node.fgcolor
from ete3 import TreeStyle from ete3 import EvolTree from ete3 import faces tree = EvolTree("data/S_example/measuring_S_tree.nw") tree.link_to_alignment('data/S_example/alignment_S_measuring_evol.fasta') print(tree) print('\n Running free-ratio model with calculation of ancestral sequences...') tree.run_model('fb_anc') #tree.link_to_evol_model('/tmp/ete3-codeml/fb_anc/out', 'fb_anc') I = TreeStyle() I.force_topology = False I.draw_aligned_faces_as_table = True I.draw_guiding_lines = True I.guiding_lines_type = 2 I.guiding_lines_color = "#CCCCCC" for n in sorted(tree.get_descendants() + [tree], key=lambda x: x.node_id): if n.is_leaf(): continue anc_face = faces.SequenceFace(n.sequence, 'aa', fsize=10, bg_colors={}) I.aligned_foot.add_face(anc_face, 1) I.aligned_foot.add_face( faces.TextFace('node_id: #%d ' % (n.node_id), fsize=8), 0) print('display result of bs_anc model, with ancestral amino acid sequences.') tree.show(tree_style=I) print('\nThe End.')
def node_text_layout(mynode): F = faces.TextFace(mynode.name, fsize=20) faces.add_face_to_node(F, mynode, 0, position="branch-right")
def setup_heatmap(tree, tree_style, header, center_value=0, nameMap={}, nameLabel='', color_up=0.7, color_down=0.2, color_center="white"): DEFAULT_COLOR_SATURATION = 0.5 BASE_LIGHTNESS = 0.7 def gradient_color(value, max_value, saturation=0.5, hue=0.1): def rgb2hex(rgb): return '#%02x%02x%02x' % rgb def hls2hex(h, l, s): return rgb2hex( tuple(map(lambda x: int(x * 255), colorsys.hls_to_rgb(h, l, s)))) lightness = 1 - (value * BASE_LIGHTNESS) / max_value return hls2hex(hue, lightness, DEFAULT_COLOR_SATURATION) # Calculate max gradient value from the ClusterTree matrix maxv = abs(center_value - tree.arraytable._matrix_max) minv = abs(center_value - tree.arraytable._matrix_min) if center_value <= tree.arraytable._matrix_min: MAX_VALUE = minv + maxv else: MAX_VALUE = max(maxv, minv) # Add heatmap colors to tree cols_add_before_heat = 0 if nameMap: cols_add_before_heat = 1 for lf in tree: if nameMap: longNameFace = faces.TextFace(nameMap.get(lf.name, lf.name)) lf.add_face(longNameFace, column=0, position="aligned") for i, value in enumerate(getattr(lf, "profile", [])): if value > center_value: color = gradient_color(abs(center_value - value), MAX_VALUE, hue=color_up) elif value < center_value: color = gradient_color(abs(center_value - value), MAX_VALUE, hue=color_down) else: color = center_value #color = "LightGreen" lf.add_face(RectFace(25, 25, "white", color), position="aligned", column=i + cols_add_before_heat) # Uncomment to add numeric values to the matrix #lf.add_face(TextFace("%0.2f "%value, fsize=5), position="aligned", column=i) lf.add_face(nameFace, column=i + cols_add_before_heat + 1, position="aligned") if nameMap and nameLabel: nameF = TextFace(nameLabel, fsize=10) #nameF.rotation = -90 tree_style.aligned_header.add_face(nameF, column=0) # Add header for i, name in enumerate(header): nameF = TextFace(name, fsize=10) nameF.rotation = -90 tree_style.aligned_header.add_face(nameF, column=i + cols_add_before_heat)
node_name = str(node).split('-')[-1] rt_name = 'LTR_retrotransposon{0}'.format(node_name.split('_')[0]) if rt_name in divergences: if greatest_div['value'] < float(divergences[rt_name]): greatest_div['value'] = float(divergences[rt_name]) greatest_div['element'] = rt_name # print(int(divergences[rt_name][:6].replace('.', ''))) # print(len(color_gradient['hex'])) col = color_gradient['hex'][int(divergences[rt_name][:6].replace('.', ''))] else: NOLTRDIVERGENCES = True #col = '#417849' if ANYANNOT: if ANNOT: try: classifFace = faces.TextFace(classifDct[rt_name], fsize = 8, fgcolor = 'DarkBlue', penwidth = 8) except KeyError: classifFace = faces.TextFace('?', fsize = 8, fgcolor = 'DarkBlue', penwidth = 8) #(t & node_name).add_face(classifFace, 1, 'branch-right') (t & node_name).add_face(classifFace, 0, 'aligned') if GCLABEL: GCAVAIL = False try: IGCface = faces.TextFace(IGCdct[rt_name], fsize = 8, penwidth = 10, fgcolor = 'Black') GCAVAIL = True except KeyError: pass #IGCface = faces.TextFace('?', fsize = 8, penwidth = 10, fgcolor = 'Black') #(t & node_name).add_face(IGCface, 0, 'aligned') if GCAVAIL:
def layout(node): node.img_style["size"] = 0 if not node.is_leaf(): boostFace = faces.TextFace(node.support, fgcolor="grey", fsize=34) add_face_to_node(boostFace, node, column=0, position="branch-top") if node.is_leaf(): taxid = (node.name.split('.')[0]) seq_name = (node.name.split('.')[1]) #add predicted name (eggnog 4.5) try: pred_name = predict_name[node.name] predNameFace = faces.TextFace(pred_name, fgcolor="salmon", fsize=34) predNameFace.margin_right = 20 predNameFace.margin_left = 20 add_face_to_node(predNameFace, node, column=2, position="branch-right") except: predNameFace = faces.TextFace('--', fgcolor="salmon", fsize=34) add_face_to_node(predNameFace, node, column=2, position="branch-right") seqNameFace = faces.TextFace(seq_name, fgcolor="grey", fsize=34) add_face_to_node(seqNameFace, node, column=1, position="branch-right") sp_name = ncbi.get_taxid_translator([(node.name.split('.')[0])]) node.name = sp_name[int(taxid)] seqFace = SeqMotifFace(node.sequence, gap_format="blank") add_face_to_node(seqFace, node, column=3, position="aligned") lin = ncbi.get_lineage(taxid) #metazoa #if int('33208') in lin: # N = AttrFace("name", fsize=34, fgcolor="blue") # N.margin_left = 20 # N.margin_right= 20 # faces.add_face_to_node(N, node, column=0) #cnidaria if int('6073') in lin: N = AttrFace("name", fsize=34, fgcolor="red") N.margin_left = 20 N.margin_right = 20 faces.add_face_to_node(N, node, column=0) #ctenophora elif int('10197') in lin: N = AttrFace("name", fsize=34, fgcolor="orange") N.margin_left = 20 N.margin_right = 20 faces.add_face_to_node(N, node, column=0) #bilateria elif int('33213') in lin: N = AttrFace("name", fsize=34, fgcolor="blue") N.margin_left = 20 N.margin_right = 20 faces.add_face_to_node(N, node, column=0) #porifera elif int('6040') in lin: N = AttrFace("name", fsize=34, fgcolor="green") N.margin_left = 20 N.margin_right = 20 faces.add_face_to_node(N, node, column=0) else: N = AttrFace("name", fsize=34, fgcolor="black") N.margin_left = 20 N.margin_right = 20 faces.add_face_to_node(N, node, column=0)
t.populate(size, reuse_names=False) I = TreeStyle() I.mode = "r" I.orientation = 0 I.layout_fn = master_ly I.margin_left = 100 I.margin_right = 50 I.margin_top = 100 I.arc_start = 45 I.arc_span = 360 I.margin_bottom = 50 I.show_border = True I.legend_position = 4 I.title.add_face(faces.TextFace("HOLA MUNDO", fsize=30), 0) I.draw_aligned_faces_as_table = True def test(node): if node.is_leaf(): faces.add_face_to_node(faces.AttrFace("name"), node, 0, position="aligned") I.aligned_header.add_face(faces.TextFace("H1"), 0) I.aligned_header.add_face(faces.TextFace("H1"), 1) I.aligned_header.add_face(faces.TextFace("H1"), 2) I.aligned_header.add_face(faces.TextFace("H1111111111111"), 3)