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 get_example_tree(): # Random tree t = Tree() t.populate(20, random_branches=True) # Some random features in all nodes for n in t.traverse(): n.add_features(weight=random.randint(0, 50)) # Create an empty TreeStyle ts = TreeStyle() # Set our custom layout function ts.layout_fn = layout # Draw a tree ts.mode = "c" # We will add node names manually ts.show_leaf_name = False # Show branch data ts.show_branch_length = True ts.show_branch_support = True return t, ts
def get_example_tree(): t = Tree() ts = TreeStyle() ts.layout_fn = layout ts.mode = "r" ts.show_leaf_name = False t.populate(10) return t, ts
def get_example_tree(): t = Tree() ts = TreeStyle() ts.layout_fn = layout ts.mode = "c" ts.show_leaf_name = True ts.min_leaf_separation = 15 t.populate(100) return t, ts
def get_example_tree(): t = Tree() t.populate(8, reuse_names=False) ts = TreeStyle() ts.layout_fn = master_ly ts.title.add_face(faces.TextFace("Drawing your own Qt Faces", fsize=15), 0) return t, ts
def get_example_tree(): t = Tree() t.populate(10) ts = TreeStyle() ts.rotation = 45 ts.show_leaf_name = False ts.layout_fn = rotation_layout return t, ts
def get_example_tree(): t = Tree() t.populate(8) # 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 layout(node): if node.is_leaf(): # Add node name to laef nodes N = AttrFace("name", fsize=14, fgcolor="black") faces.add_face_to_node(N, node, 0) t = Tree() t.populate(10) T = TreeFace(t, small_ts) # Let's make the sphere transparent T.opacity = 0.8 # And place as a float face over the tree faces.add_face_to_node(T, node, 1, position="aligned")
def get_example_tree(): # Create a random tree and add to each leaf a random set of motifs # from the original set t = Tree() t.populate(10) # for l in t.iter_leaves(): # seq_motifs = [list(m) for m in motifs] #sample(motifs, randint(2, len(motifs))) # seqFace = SeqMotifFace(seq, seq_motifs, intermotif_format="line", # seqtail_format="compactseq", scale_factor=1) # seqFace.margin_bottom = 4 # f = l.add_face(seqFace, 0, "aligned") ts = TreeStyle() ts.layout_fn = layout t.show(tree_style=ts) return t, ts
def get_example_tree(): t = Tree("((a,b),c);") right_c0_r0 = TextFace("right_col0_row0") right_c0_r1 = TextFace("right_col0_row1") right_c1_r0 = TextFace("right_col1_row0") right_c1_r1 = TextFace("right_col1_row1") right_c1_r2 = TextFace("right_col1_row2") top_c0_r0 = TextFace("top_col0_row0") top_c0_r1 = TextFace("top_col0_row1") bottom_c0_r0 = TextFace("bottom_col0_row0") bottom_c1_r0 = TextFace("bottom_col1_row0") aligned_c0_r0 = TextFace("aligned_col0_row0") aligned_c0_r1 = TextFace("aligned_col0_row1") aligned_c1_r0 = TextFace("aligned_col1_row0") aligned_c1_r1 = TextFace("aligned_col1_row1") t.add_face(right_c0_r1, column=1, position="branch-right") t.add_face(right_c0_r0, column=0, position="branch-right") t.add_face(right_c1_r2, column=2, position="branch-right") t.add_face(right_c1_r1, column=1, position="branch-right") t.add_face(right_c1_r0, column=0, position="branch-right") t.add_face(top_c0_r1, column=1, position="branch-top") t.add_face(top_c0_r0, column=0, position="branch-top") t.add_face(bottom_c0_r0, column=0, position="branch-bottom") t.add_face(bottom_c1_r0, column=1, position="branch-bottom") for leaf in t.iter_leaves(): leaf.add_face(aligned_c0_r1, 0, "aligned") leaf.add_face(aligned_c0_r0, 0, "aligned") leaf.add_face(aligned_c1_r1, 0, "aligned") leaf.add_face(aligned_c1_r0, 0, "aligned") return t, TreeStyle()
def get_example_tree(): # sample sequence and a list of example motif types seq = "LHGRISQQVEQSRSQVQAIGEKVSLAQAKIEKIKGSKKAIKVFSSAKYPAPERLQEYGSIFTDAQDPGLQRRPRHRIQSKQRPLDERALQEKLKDFPVCVSTKPEPEDDAEEGLGGLPSNISSVSSLLLFNTTENLYKKYVFLDPLAGAVTKTHVMLGAETEEKLFDAPLSISKREQLEQQVPENYFYVPDLGQVPEIDVPSYLPDLPGIANDLMYIADLGPGIAPSAPGTIPELPTFHTEVAEPLKVGELGSGMGAGPGTPAHTPSSLDTPHFVFQTYKMGAPPLPPSTAAPVGQGARQDDSSSSASPSVQGAPREVVDPSGGWATLLESIRQAGGIGKAKLRSMKERKLEKQQQKEQEQVRATSQGGHLMSDLFNKLVMRRKGISGKGPGAGDGPGGAFARVSDSIPPLPPPQQPQAEDEDDWES" motifs = [ # seq.start, seq.end, shape, width, height, fgcolor, bgcolor [ 10, 100, "[]", None, 10, "black", "rgradient:blue", "arial|8|white|domain Name" ], [110, 150, "o", None, 10, "blue", "pink", None], [155, 180, "()", None, 10, "blue", "rgradient:purple", None], [160, 170, "^", None, 14, "black", "yellow", None], [172, 180, "v", None, 12, "black", "rgradient:orange", None], [185, 190, "o", None, 12, "black", "brown", None], [198, 200, "<>", None, 15, "black", "rgradient:gold", None], [210, 240, "compactseq", 2, 10, None, None, None], [300, 320, "seq", 10, 10, None, None, None], [310, 345, "<>", None, 15, "black", "rgradient:black", None], ] # Create a random tree and add to each leaf a random set of motifs # from the original set t = Tree() t.populate(10) for l in t.iter_leaves(): seq_motifs = [list(m) for m in motifs ] #sample(motifs, randint(2, len(motifs))) seqFace = SeqMotifFace(seq, seq_motifs, intermotif_format="line", seqtail_format="compactseq", scale_factor=1) seqFace.margin_bottom = 4 f = l.add_face(seqFace, 0, "aligned") return t, TreeStyle()
from ete_dev import Tree # Loads a tree. Note that we use format 1 to read internal node names t = Tree('((((H,K)D,(F,I)G)B,E)A,((L,(N,Q)O)J,(P,S)M)C);', format=1) print "original tree looks like this:" # This is an alternative way of using "print t". Thus we have a bit # more of control on how tree is printed. Here i print the tree # showing internal node names print t.get_ascii(show_internal=True) # # /-H # /D-------| # | \-K # /B-------| # | | /-F # /A-------| \G-------| # | | \-I # | | # | \-E #-NoName--| # | /-L # | /J-------| # | | | /-N # | | \O-------| # \C-------| \-Q # | # | /-P # \M-------| # \-S # Get pointers to specific nodes G = t.search_nodes(name="G")[0] J = t.search_nodes(name="J")[0]
node.img_style["vt_line_width"] = 0 #if node.is_leaf(): # f = faces.CircleFace(50, "red") # faces.add_face_to_node(f, node, 0, position="aligned") ts = TreeStyle() ts.mode = "c" ts.arc_span = 360 ts.layout_fn = layout ts.show_leaf_name = False ts.show_border = True ts.draw_guiding_lines = False ts.show_scale = True #ts.scale = 60 t = Tree() t.dist = 0 t.size = 0, 0 for x in xrange(100): n = t.add_child() n = n.add_child() n = n.add_child() n2 = n.add_child() n3 = n.add_child() n4 = n2.add_child() n5 = n3.add_child() # n.size = (10, 10) # n2.size = (10, 70) # n3.size = (40, 40) # n4.size = (10, 10)
from ete_dev import Tree # Let's create simple tree t = Tree('((((H,K),(F,I)G),E),((L,(N,Q)O),(P,S)));') print "Original tree looks like this:" print t # # /-H # /--------| # | \-K # /--------| # | | /-F # /--------| \--------| # | | \-I # | | # | \-E #---------| # | /-L # | /--------| # | | | /-N # | | \--------| # \--------| \-Q # | # | /-P # \--------| # \-S # Prune the tree in order to keep only some leaf nodes. t.prune(["H","F","E","Q", "P"]) print "Pruned tree" print t # # /-F
def main(argv): parser = argparse.ArgumentParser( description=__DESCRIPTION__, formatter_class=argparse.RawDescriptionHelpFormatter) input_args = parser.add_argument_group("INPUT OPTIONS") input_args.add_argument("source_trees", metavar='source_trees', type=str, nargs="*", help='a list of source tree files') input_args.add_argument( "--source_file", dest="source_file", type=str, help="""path to a file containing many source trees, one per line""") input_args.add_argument("-r", dest="reftree", type=str, required=True, help="""Reference tree""") input_args.add_argument("--ref_tree_attr", dest="ref_tree_attr", type=str, default="name", help=("attribute in ref tree used as leaf name")) input_args.add_argument( "--src_tree_attr", dest="src_tree_attr", type=str, default="name", help=("attribute in source tree used as leaf name")) input_args.add_argument( "--min_support_ref", type=float, default=0.0, help=("min support for branches to be considered from the ref tree")) input_args.add_argument( "--min_support_src", type=float, default=0.0, help=( "min support for branches to be considered from the source tree")) output_args = parser.add_argument_group("OUTPUT OPTIONS") output_args.add_argument("-o", dest="output", type=str, help="""Path to the tab delimited report file""") opt_args = parser.add_argument_group("DISTANCE OPTIONS") opt_args.add_argument( "--outgroup", dest="outgroup", nargs="+", help= """outgroup used to root reference and source trees before distance computation""" ) opt_args.add_argument("--expand_polytomies", dest="polytomies", action="store_true", help="""expand politomies if necessary""") opt_args.add_argument("--unrooted", dest="unrooted", action="store_true", help="""compare trees as unrooted""") opt_args.add_argument( "--min_support", dest="min_support", type=float, default=0.0, help= ("min support value for branches to be counted in the distance computation (RF, treeko and refTree/targeGene compatibility)" )) opt_args = parser.add_argument_group("PHYLOGENETICS OPTIONS") opt_args.add_argument( "--extract_species", action="store_true", help= "When used, leaf names in the reference and source trees are assumed to represent species." " If target trees are gene-trees whose species information is encoded as a part of the leaf sequence name," " it can be automatically extracted by providing a Perl regular expression that extract a " " valid species code (see --sp_regexp). Such information will be also used to detect duplication" " events. ") opt_args.add_argument( "--sp_regexp", type=str, help= ("Specifies a Perl regular expression to automatically extract species names" " from the name string in source trees. If not used, leaf names are assumed to represent species names." " Example: use this expression '[^_]+_(.+)' to extract HUMAN from the string 'P53_HUMAN'." )) opt_args.add_argument("--collateral", action='store_true', help=("")) args = parser.parse_args(argv) print __DESCRIPTION__ reftree = args.reftree if args.source_file and args.source_trees: print >> sys.stderr, 'The use of targets_file and targets at the same time is not supported.' sys.exit(1) if args.source_file: source_trees = tree_iterator(args.source_file) else: source_trees = args.source_trees ref_tree = Tree(reftree) if args.ref_tree_attr: for lf in ref_tree.iter_leaves(): lf._origname = lf.name if args.ref_tree_attr not in lf.features: print lf lf.name = getattr(lf, args.ref_tree_attr) if args.outgroup: if len(args.outgroup) > 1: out = ref_tree.get_common_ancestor(args.outgroup) else: out = ref_tree.search_nodes(name=args.outgroup[0])[0] ref_tree.set_outgroup(out) HEADER = ("source tree", 'ref tree', 'common\ntips', 'normRF', 'RF', 'maxRF', "%reftree", "%genetree", "subtrees", "treeko\ndist") if args.output: OUT = open(args.output, "w") print >> OUT, '# ' + ctime() print >> OUT, '# ' + ' '.join(sys.argv) print >> OUT, '#' + '\t'.join(HEADER) else: print '# ' + ctime() print '# ' + ' '.join(sys.argv) COL_WIDTHS = [20, 20] + [9] * 10 print_table([HEADER], fix_col_width=COL_WIDTHS, wrap_style='wrap') prev_tree = None ref_fname = os.path.basename(args.reftree) for counter, tfile in enumerate(source_trees): if args.source_file: seedid, tfile = tfile else: seedid = None if args.extract_species: if args.sp_regexp: SPMATCHER = re.compile(args.sp_regexp) get_sp_name = lambda x: re.search(SPMATCHER, x).groups()[0] else: get_sp_name = lambda x: x tt = PhyloTree(tfile, sp_naming_function=get_sp_name) else: tt = Tree(tfile) if args.src_tree_attr: for lf in tt.iter_leaves(): lf._origname = lf.name lf.name = getattr(lf, args.src_tree_attr) if args.outgroup: if len(args.outgroup) > 1: out = tt.get_common_ancestor(args.outgroup) else: out = tt.search_nodes(name=args.outgroup[0])[0] tt.set_outgroup(out) if args.source_trees: fname = os.path.basename(tfile) else: fname = '%05d' % counter r = tt.compare(ref_tree, ref_tree_attr=args.ref_tree_attr, source_tree_attr=args.src_tree_attr, min_support_ref=args.min_support_ref, min_support_source=args.min_support_src, unrooted=args.unrooted, has_duplications=args.extract_species) print_table([ map(istr, [ fname[-30:], ref_fname[-30:], r['effective_tree_size'], r['norm_rf'], r['rf'], r['max_rf'], r["source_edges_in_ref"], r["ref_edges_in_source"], r['source_subtrees'], r['treeko_dist'] ]) ], fix_col_width=COL_WIDTHS, wrap_style='cut') if args.output: OUT.close()
from ete_dev import Tree # Loads 3 independent trees t1 = Tree('(A,(B,C));') t2 = Tree('((D,E), (F,G));') t3 = Tree('(H, ((I,J), (K,L)));') print "Tree1:", t1 # /-A # ---------| # | /-B # \--------| # \-C print "Tree2:", t2 # /-D # /--------| # | \-E # ---------| # | /-F # \--------| # \-G print "Tree3:", t3 # /-H # | # ---------| /-I # | /--------| # | | \-J # \--------| # | /-K # \--------| # \-L # Locates a terminal node in the first tree A = t1.search_nodes(name='A')[0]
import random from ete_dev import Tree # Creates a normal tree t = Tree( '((H:0.3,I:0.1):0.5, A:1, (B:0.4,(C:0.5,(J:1.3, (F:1.2, D:0.1):0.5):0.5):0.5):0.5);' ) print t # Let's locate some nodes using the get common ancestor method ancestor = t.get_common_ancestor("J", "F", "C") # the search_nodes method (I take only the first match ) A = t.search_nodes(name="A")[0] # and using the shorcut to finding nodes by name C = t & "C" H = t & "H" I = t & "I" # Let's now add some custom features to our nodes. add_features can be # used to add many features at the same time. C.add_features(vowel=False, confidence=1.0) A.add_features(vowel=True, confidence=0.5) ancestor.add_features(nodetype="internal") # Or, using the oneliner notation (t & "H").add_features(vowel=False, confidence=0.2) # But we can automatize this. (note that i will overwrite the previous # values) for leaf in t.traverse(): if leaf.name in "AEIOU": leaf.add_features(vowel=True, confidence=random.random()) else: leaf.add_features(vowel=False, confidence=random.random()) # Now we use these information to analyze the tree. print "This tree has", len(t.search_nodes(vowel=True)), "vowel nodes"
from ete_dev import Tree # Loads a tree with internal node names t = Tree('(A:1,(B:1,(E:1,D:1)Internal_1:0.5)Internal_2:0.5)Root;', format=1) # And prints its newick representation omiting all the information but # the tree topology print t.write(format=100) # (,(,(,))); # We can also write into a file t.write(format=100, outfile="/tmp/tree.new")
from ete_dev import Tree t = Tree('((H:0.3,I:0.1):0.5, A:1, (B:0.4,(C:1,D:1):0.5):0.5);') # Create a small function to filter your nodes def conditional_function(node): if node.dist > 0.3: return True else: return False # Use previous function to find matches. Note that we use the traverse # method in the filter function. This will iterate over all nodes to # assess if they meet our custom conditions and will return a list of # matches. matches = filter(conditional_function, t.traverse()) print len(matches), "nodes have ditance >0.3" # depending on the complexity of your conditions you can do the same # in just one line with the help of lambda functions: matches = filter(lambda n: n.dist > 0.3 and n.is_leaf(), t.traverse()) print len(matches), "nodes have ditance >0.3 and are leaves"
from ete_dev import Tree t = Tree('(A:1,(B:1,(C:1,D:1):0.5):0.5);') # Visit nodes in preorder (this is the default strategy) for n in t.traverse(): print n # It Will visit the nodes in the following order: # /-A # ---------| # | /-B # \--------| # | /-C # \--------| # \-D # --A # /-B # ---------| # | /-C # \--------| # \-D # --B # /-C # ---------| # \-D # --C # --D # Visit nodes in postorder for n in t.traverse("postorder"): print n # It Will visit the nodes in the following order: # --A
from ete_dev import Tree #Loads a tree tree = Tree('((H:1,I:1):0.5, A:1, (B:1,(C:1,D:1):0.5):0.5);') print "this is the original tree:" print tree # /-H # /--------| # | \-I # | #---------|--A # | # | /-B # \--------| # | /-C # \--------| # \-D # Finds the first common ancestor between B and C. ancestor = tree.get_common_ancestor("D", "C") print "The ancestor of C and D is:" print ancestor # /-C #---------| # \-D # You can use more than two nodes in the search ancestor = tree.get_common_ancestor("B", "C", "D") print "The ancestor of B, C and D is:" print ancestor # /-B #---------| # | /-C # \--------|
# This avoids installing nprlib module. npr script will find it in the # same directory in which it is ETEPATH = os.path.abspath(os.path.split(os.path.realpath(__file__))[0]+'/../') sys.path.insert(0, ETEPATH) from ete_dev import Tree, TreeStyle, NodeStyle, PhyloTree, faces from ete_dev.treeview.faces import * from ete_dev.treeview.main import random_color, _NODE_TYPE_CHECKER, FACE_POSITIONS sys.path.insert(0, os.path.join(ETEPATH, "examples/treeview")) import face_grid, bubble_map, item_faces, node_style, node_background, face_positions, face_rotation, seq_motif_faces, barchart_and_piechart_faces sys.path.insert(0, os.path.join(ETEPATH, "examples/phylogenies")) import phylotree_visualization main_tree = Tree() main_tree.dist = 0 t, ts = face_grid.get_example_tree() t_grid = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_grid, 0, "aligned") t, ts = bubble_map.get_example_tree() t_bubble = TreeFace(t, ts) n = main_tree.add_child() n.add_face(t_bubble, 0, "aligned") t, ts = item_faces.get_example_tree() t_items = TreeFace(t, ts) n = main_tree.add_child()
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
out = t & args.outgroup[0] else: out = t.get_common_ancestor(args.outgroup) if set(out.get_leaf_names()) ^ set(args.outgroup): raise ValueError("Outgroup is not monophyletic") t.set_outgroup(out) t.ladderize() if prev_tree: tree_compare(t, prev_tree) prev_tree = t if args.ref_tree: print "Reading ref tree from", args.ref_tree reft = Tree(args.ref_tree, format=1) else: reft = None if args.tax_info: tax2name, tax2track = annotate_tree_with_taxa( t, args.tax_info, tax2name, tax2track) if args.dump_tax_info: cPickle.dump(tax2track, open("tax2track.pkl", "w")) cPickle.dump(tax2name, open("tax2name.pkl", "w")) print "Tax info written into pickle files" else: for n in t.iter_leaves(): spcode = n.name n.add_features(taxid=spcode)
# Import Tree instance and faces module from ete_dev import Tree, faces # Loads an example tree nw = """ (((Dre:0.008339,Dme:0.300613)1.000000:0.596401, (Cfa:0.640858,Hsa:0.753230)1.000000:0.182035)1.000000:0.106234, ((Dre:0.271621,Cfa:0.046042)1.000000:0.953250, (Hsa:0.061813,Mms:0.110769)1.000000:0.204419)1.000000:0.973467); """ t = Tree(nw) # You can create any random tree containing the same leaf names, and # layout will work equally # # t = Tree() # Creates a random tree with 8 leaves using a given set of names # t.populate(8, ["Dme", "Dre", "Hsa", "Ptr", "Cfa", "Mms"]) # Set the path in which images are located img_path = "./" # Create faces based on external images humanFace = faces.ImgFace(img_path + "human.png") mouseFace = faces.ImgFace(img_path + "mouse.png") dogFace = faces.ImgFace(img_path + "dog.png") chimpFace = faces.ImgFace(img_path + "chimp.png") fishFace = faces.ImgFace(img_path + "fish.png") flyFace = faces.ImgFace(img_path + "fly.png") # Create a faces ready to read the name attribute of nodes #nameFace = faces.TextFace(open("text").readline().strip(), fsize=20, fgcolor="#009000")
from ete_dev import Tree t = Tree() # Creates an empty tree A = t.add_child(name="A") # Adds a new child to the current tree root # and returns it B = t.add_child(name="B") # Adds a second child to the current tree # root and returns it C = A.add_child(name="C") # Adds a new child to one of the branches D = C.add_sister(name="D") # Adds a second child to same branch as # before, but using a sister as the starting # point R = A.add_child(name="R") # Adds a third child to the # branch. Multifurcations are supported # Next, I add 6 random leaves to the R branch names_library is an # optional argument. If no names are provided, they will be generated # randomly. R.populate(6, names_library=["r1", "r2", "r3", "r4", "r5", "r6"]) # Prints the tree topology print t # /-C # | # |--D # | # /--------| /-r4 # | | /--------| # | | /--------| \-r3 # | | | | # | | | \-r5 # | \--------| # ---------| | /-r6 # | | /--------| # | \--------| \-r2
from ete_dev import Tree # Creates an empty tree and populates it with some new # nodes t = Tree() A = t.add_child(name="A") B = t.add_child(name="B") C = A.add_child(name="C") D = A.add_child(name="D") print t # /-C # /--------| #---------| \-D # | # \-B print 'is "t" the root?', t.is_root() # True print 'is "A" a terminal node?', A.is_leaf() # False print 'is "B" a terminal node?', B.is_leaf() # True print 'B.get_tree_root() is "t"?', B.get_tree_root() is t # True print 'Number of leaves in tree:', len( t) # returns number of leaves under node (3) print 'is C in tree?', C in t # Returns true print "All leaf names in tree:", [node.name for node in t]
import time from ete_dev import Tree # Creates a random tree with 10,000 leaf nodes tree = Tree() tree.populate(10000) # This code should be faster t1 = time.time() for leaf in tree.iter_leaves(): if "aw" in leaf.name: print "found a match:", leaf.name, break print "Iterating: ellapsed time:", time.time() - t1 # This slower t1 = time.time() for leaf in tree.get_leaves(): if "aw" in leaf.name: print "found a match:", leaf.name, break print "Getting: ellapsed time:", time.time() - t1 # Results in something like: # found a match: guoaw Iterating: ellapsed time: 0.00436091423035 secs # found a match: guoaw Getting: ellapsed time: 0.124316930771 secs
def get_rooting(tol, seed_species, agename=False): ''' returns dict of species age for a given TOL and a given seed **Example:** :: tol = "((((((((Drosophila melanogaster,(Drosophila simulans,Drosophila secchellia)),(Drosophila yakuba,Drosophila erecta))[&&NHX:name=melanogaster subgroup],Drosophila ananassae)[&&NHX:name=melanogaster group],(Drosophila pseudoobscura,Drosophila persimilis)[&&NHX:name=obscura group])[&&NHX:name=Sophophora Old World],Drosophila willistoni)[&&NHX:name=subgenus Sophophora],(Drosophila grimshawi,(Drosophila virilis,Drosophila mojavensis))[&&NHX:name=subgenus Drosophila])[&&NHX:name=genus Drosophila],(Anopheles gambiae,Aedes aegypti)[&&NHX:name=Culicidae])[&&NHX:name=Arthropoda],Caenorhabditis elegans)[&&NHX:name=Animalia];" seed = "Drosophila melanogaster" ROOTING, age2name = get_rooting (tol, seed, True) ROOTING == {"Aedes aegypti" : 7, "Anopheles gambiae" : 7, "Caenorhabditis elegans" : 8, "Drosophila ananassae" : 3, "Drosophila erecta" : 2, "Drosophila grimshawi" : 6, "Drosophila melanogaster" : 1, "Drosophila mojavensis" : 6, "Drosophila persimilis" : 4, "Drosophila pseudoobscura": 4, "Drosophila secchellia" : 1, "Drosophila simulans" : 1, "Drosophila virilis" : 6, "Drosophila willistoni" : 5, "Drosophila yakuba" : 2} age2name == {1: "Drosophila melanogaster. Drosophila simulans. Drosophila secchellia", 2: "melanogaster subgroup", 3: "melanogaster group", 4: "Sophophora Old World", 5: "subgenus Sophophora", 6: "genus Drosophila", 7: "Arthropoda", 8: "Animalia"} :argument seed_species: species name :argument False agename: if True, also returns the inverse dictionary :returns: ROOTING dictionary with age of each species ''' tol = Tree(tol) try: node = tol.search_nodes(name=seed_species)[0] except IndexError: exit('ERROR: Seed species not found in tree\n') age = 1 ROOTING = {} if agename: age2name = {} while not node.is_root(): node = node.up for leaf in node.get_leaf_names(): if agename: if node.name == 'NoName': nam = '.'.join(node.get_leaf_names()) else: nam = node.name age2name.setdefault(age, nam) ROOTING.setdefault(leaf, age) age += 1 if agename: return ROOTING, age2name return ROOTING
from ete_dev import Tree # Loads a basic tree t = Tree('(A:0.2,(B:0.4,(C:1.1,D:0.45):0.5):0.1);') print t # /-A #---------| # | /-B # \--------| # | /-C # \--------| # \-D # Counts leaves within the tree nleaves = 0 for leaf in t.get_leaves(): nleaves += 1 print "This tree has", nleaves, "terminal nodes" # But, like this is much simpler :) nleaves = len(t) print "This tree has", nleaves, "terminal nodes [proper way: len(tree) ]" # Counts leaves within the tree ninternal = 0 for node in t.get_descendants(): if not node.is_leaf(): ninternal += 1 print "This tree has", ninternal, "internal nodes" # Counts nodes with whose distance is higher than 0.3 nnodes = 0 for node in t.get_descendants(): if node.dist > 0.3: nnodes += 1 # or, translated into a better pythonic