1
2
3
4
5
6
7 """Tree class to handle phylogenetic trees.
8
9 Provides a set of methods to read and write newick-format tree descriptions,
10 get information about trees (monphyly of taxon sets, congruence between trees,
11 common ancestors,...) and to manipulate trees (reroot trees, split terminal
12 nodes).
13 """
14
15 import sys, random, copy
16 import Nodes
17
18 PRECISION_BRANCHLENGTH=6
19 PRECISION_SUPPORT=6
20 NODECOMMENT_START='[&'
21 NODECOMMENT_END=']'
22
24
26 """Stores tree-relevant data associated with nodes (e.g. branches or otus)."""
27 - def __init__(self,taxon=None,branchlength=0.0,support=None,comment=None):
28 self.taxon=taxon
29 self.branchlength=branchlength
30 self.support=support
31 self.comment=comment
32
33 -class Tree(Nodes.Chain):
34 """Represents a tree using a chain of nodes with on predecessor (=ancestor)
35 and multiple successors (=subclades).
36 """
37
38
39
40
41
42
43
44
45
46 - def __init__(self,tree=None,weight=1.0,rooted=False,name='',data=NodeData,values_are_support=False,max_support=1.0):
47 """Ntree(self,tree)."""
48 Nodes.Chain.__init__(self)
49 self.dataclass=data
50 self.__values_are_support=values_are_support
51 self.max_support=max_support
52 self.weight=weight
53 self.rooted=rooted
54 self.name=name
55 root=Nodes.Node(data())
56 self.root = self.add(root)
57 if tree:
58
59 tree=tree.strip().replace('\n','').replace('\r','')
60
61 tree=tree.rstrip(';')
62 subtree_info, base_info = self._parse(tree)
63 root.data = self._add_nodedata(root.data, [[], base_info])
64 self._add_subtree(parent_id=root.id,tree=subtree_info)
65
67 """Parses (a,b,c...)[[[xx]:]yy] into subcomponents and travels down recursively."""
68
69
70 tree = tree.strip()
71 if tree.count('(')!=tree.count(')'):
72 raise TreeError('Parentheses do not match in (sub)tree: '+tree)
73 if tree.count('(')==0:
74
75 nodecomment=tree.find(NODECOMMENT_START)
76 colon=tree.find(':')
77 if colon==-1 and nodecomment==-1:
78 return [tree,[None]]
79 elif colon==-1 and nodecomment>-1:
80 return [tree[:nodecomment],self._get_values(tree[nodecomment:])]
81 elif colon>-1 and nodecomment==-1:
82 return [tree[:colon],self._get_values(tree[colon+1:])]
83 elif colon < nodecomment:
84 return [tree[:colon],self._get_values(tree[colon+1:])]
85 else:
86 return [tree[:nodecomment],self._get_values(tree[nodecomment:])]
87 else:
88 closing=tree.rfind(')')
89 val=self._get_values(tree[closing+1:])
90 if not val:
91 val=[None]
92 subtrees=[]
93 plevel=0
94 prev=1
95 for p in range(1,closing):
96 if tree[p]=='(':
97 plevel+=1
98 elif tree[p]==')':
99 plevel-=1
100 elif tree[p]==',' and plevel==0:
101 subtrees.append(tree[prev:p])
102 prev=p+1
103 subtrees.append(tree[prev:closing])
104 subclades=[self._parse(subtree) for subtree in subtrees]
105 return [subclades,val]
106
108 """Adds leaf or tree (in newick format) to a parent_id. (self,parent_id,tree)."""
109 if parent_id is None:
110 raise TreeError('Need node_id to connect to.')
111 for st in tree:
112 nd=self.dataclass()
113 nd = self._add_nodedata(nd, st)
114 if type(st[0])==list:
115 sn=Nodes.Node(nd)
116 self.add(sn,parent_id)
117 self._add_subtree(sn.id,st[0])
118 else:
119 nd.taxon=st[0]
120 leaf=Nodes.Node(nd)
121 self.add(leaf,parent_id)
122
124 """Add data to the node parsed from the comments, taxon and support.
125 """
126 if isinstance(st[1][-1],str) and st[1][-1].startswith(NODECOMMENT_START):
127 nd.comment=st[1].pop(-1)
128
129 elif isinstance(st[1][0], str):
130 nd.taxon = st[1][0]
131 st[1] = st[1][1:]
132 if len(st)>1:
133 if len(st[1])>=2:
134 nd.support=st[1][0]
135 if st[1][1] is not None:
136 nd.branchlength=st[1][1]
137 elif len(st[1])==1:
138 if not self.__values_are_support:
139 if st[1][0] is not None:
140 nd.branchlength=st[1][0]
141 else:
142 nd.support=st[1][0]
143 return nd
144
175
176 - def _walk(self,node=None):
177 """Return all node_ids downwards from a node."""
178
179 if node is None:
180 node=self.root
181 for n in self.node(node).succ:
182 yield n
183 for sn in self._walk(n):
184 yield sn
185
186 - def node(self,node_id):
187 """Return the instance of node_id.
188
189 node = node(self,node_id)
190 """
191 if node_id not in self.chain:
192 raise TreeError('Unknown node_id: %d' % node_id)
193 return self.chain[node_id]
194
195 - def split(self,parent_id=None,n=2,branchlength=1.0):
196 """Speciation: generates n (default two) descendants of a node.
197
198 [new ids] = split(self,parent_id=None,n=2,branchlength=1.0):
199 """
200 if parent_id is None:
201 raise TreeError('Missing node_id.')
202 ids=[]
203 parent_data=self.chain[parent_id].data
204 for i in range(n):
205 node=Nodes.Node()
206 if parent_data:
207 node.data=self.dataclass()
208
209 if parent_data.taxon:
210 node.data.taxon=parent_data.taxon+str(i)
211 node.data.branchlength=branchlength
212 ids.append(self.add(node,parent_id))
213 return ids
214
216 """Returns the first matching taxon in self.data.taxon. Not restricted to terminal nodes.
217
218 node_id = search_taxon(self,taxon)
219 """
220 for id,node in self.chain.items():
221 if node.data.taxon==taxon:
222 return id
223 return None
224
226 """Prunes a terminal taxon from the tree.
227
228 id_of_previous_node = prune(self,taxon)
229 If taxon is from a bifurcation, the connectiong node will be collapsed
230 and its branchlength added to remaining terminal node. This might be no
231 longer a meaningful value'
232 """
233
234 id=self.search_taxon(taxon)
235 if id is None:
236 raise TreeError('Taxon not found: %s' % taxon)
237 elif id not in self.get_terminals():
238 raise TreeError('Not a terminal taxon: %s' % taxon)
239 else:
240 prev=self.unlink(id)
241 self.kill(id)
242 if len(self.node(prev).succ)==1:
243 if prev==self.root:
244 self.root=self.node(self.root).succ[0]
245 self.node(self.root).branchlength=0.0
246 self.kill(prev)
247 else:
248 succ=self.node(prev).succ[0]
249 new_bl=self.node(prev).data.branchlength+self.node(succ).data.branchlength
250 self.collapse(prev)
251 self.node(succ).data.branchlength=new_bl
252 return prev
253
255 """Return a list of all otus downwards from a node (self, node_id).
256
257 nodes = get_taxa(self,node_id=None)
258 """
259
260 if node_id is None:
261 node_id=self.root
262 if node_id not in self.chain:
263 raise TreeError('Unknown node_id: %d.' % node_id)
264 if self.chain[node_id].succ==[]:
265 if self.chain[node_id].data:
266 return [self.chain[node_id].data.taxon]
267 else:
268 return None
269 else:
270 list=[]
271 for succ in self.chain[node_id].succ:
272 list.extend(self.get_taxa(succ))
273 return list
274
276 """Return a list of all terminal nodes."""
277 return [i for i in self.all_ids() if self.node(i).succ==[]]
278
280 """Returns True if node is a terminal node."""
281 return self.node(node).succ==[]
282
284 """Returns True if node is an internal node."""
285 return len(self.node(node).succ)>0
286
288 """Returns True if all successors of a node are terminal ones."""
289 if self.is_terminal(node):
290 return False not in [self.is_terminal(n) for n in self.node(node).succ]
291 else:
292 return False
294 """Counts the number of terminal nodes that are attached to a node."""
295 if node is None:
296 node=self.root
297 return len([n for n in self._walk(node) if self.is_terminal(n)])
298
300 """Collapses all subtrees which belong to the same genus (i.e share the same first word in their taxon name."""
301
302 while True:
303 for n in self._walk():
304 if self.is_terminal(n):
305 continue
306 taxa=self.get_taxa(n)
307 genera=[]
308 for t in taxa:
309 if space_equals_underscore:
310 t=t.replace(' ','_')
311 try:
312 genus=t.split('_',1)[0]
313 except:
314 genus='None'
315 if genus not in genera:
316 genera.append(genus)
317 if len(genera)==1:
318 self.node(n).data.taxon=genera[0]+' <collapsed>'
319
320 nodes2kill=[kn for kn in self._walk(node=n)]
321 for kn in nodes2kill:
322 self.kill(kn)
323 self.node(n).succ=[]
324 break
325 else:
326 break
327
328
330 """Adds up the branchlengths from root (default self.root) to node.
331
332 sum = sum_branchlength(self,root=None,node=None)
333 """
334
335 if root is None:
336 root=self.root
337 if node is None:
338 raise TreeError('Missing node id.')
339 blen=0.0
340 while node is not None and node is not root:
341 blen+=self.node(node).data.branchlength
342 node=self.node(node).prev
343 return blen
344
346 """Return subtree as a set of nested sets.
347
348 sets = set_subtree(self,node)
349 """
350
351 if self.node(node).succ==[]:
352 return self.node(node).data.taxon
353 else:
354 try:
355 return frozenset([self.set_subtree(n) for n in self.node(node).succ])
356 except:
357 print node
358 print self.node(node).succ
359 for n in self.node(node).succ:
360 print n, self.set_subtree(n)
361 print [self.set_subtree(n) for n in self.node(node).succ]
362 raise
363
365 """Compare tree and tree2 for identity.
366
367 result = is_identical(self,tree2)
368 """
369 return self.set_subtree(self.root)==tree2.set_subtree(tree2.root)
370
372 """Compares branches with support>threshold for compatibility.
373
374 result = is_compatible(self,tree2,threshold)
375 """
376
377
378 missing2=set(self.get_taxa())-set(tree2.get_taxa())
379 missing1=set(tree2.get_taxa())-set(self.get_taxa())
380 if strict and (missing1 or missing2):
381 if missing1:
382 print 'Taxon/taxa %s is/are missing in tree %s' % (','.join(missing1) , self.name)
383 if missing2:
384 print 'Taxon/taxa %s is/are missing in tree %s' % (','.join(missing2) , tree2.name)
385 raise TreeError('Can\'t compare trees with different taxon compositions.')
386 t1=[(set(self.get_taxa(n)),self.node(n).data.support) for n in self.all_ids() if \
387 self.node(n).succ and\
388 (self.node(n).data and self.node(n).data.support and self.node(n).data.support>=threshold)]
389 t2=[(set(tree2.get_taxa(n)),tree2.node(n).data.support) for n in tree2.all_ids() if \
390 tree2.node(n).succ and\
391 (tree2.node(n).data and tree2.node(n).data.support and tree2.node(n).data.support>=threshold)]
392 conflict=[]
393 for (st1,sup1) in t1:
394 for (st2,sup2) in t2:
395 if not st1.issubset(st2) and not st2.issubset(st1):
396 intersect,notin1,notin2=st1 & st2, st2-st1, st1-st2
397
398 if intersect and not (notin1.issubset(missing1) or notin2.issubset(missing2)):
399 conflict.append((st1,sup1,st2,sup2,intersect,notin1,notin2))
400 return conflict
401
403 """Return the common ancestor that connects two nodes.
404
405 node_id = common_ancestor(self,node1,node2)
406 """
407
408 l1=[self.root]+self.trace(self.root,node1)
409 l2=[self.root]+self.trace(self.root,node2)
410 return [n for n in l1 if n in l2][-1]
411
412
414 """Add and return the sum of the branchlengths between two nodes.
415 dist = distance(self,node1,node2)
416 """
417
418 ca=self.common_ancestor(node1,node2)
419 return self.sum_branchlength(ca,node1)+self.sum_branchlength(ca,node2)
420
422 """Return node_id of common ancestor if taxon_list is monophyletic, -1 otherwise.
423
424 result = is_monophyletic(self,taxon_list)
425 """
426 if isinstance(taxon_list,str):
427 taxon_set=set([taxon_list])
428 else:
429 taxon_set=set(taxon_list)
430 node_id=self.root
431 while 1:
432 subclade_taxa=set(self.get_taxa(node_id))
433 if subclade_taxa==taxon_set:
434 return node_id
435 else:
436 for subnode in self.chain[node_id].succ:
437 if set(self.get_taxa(subnode)).issuperset(taxon_set):
438 node_id=subnode
439 break
440 else:
441 return -1
442
457
458
459
461 """Move values stored in data.branchlength to data.support, and set branchlength to 0.0
462
463 This is necessary when support has been stored as branchlength (e.g. paup), and has thus
464 been read in as branchlength.
465 """
466
467 for n in self.chain.keys():
468 self.node(n).data.support=self.node(n).data.branchlength
469 self.node(n).data.branchlength=0.0
470
472 """Convert absolute support (clade-count) to rel. frequencies.
473
474 Some software (e.g. PHYLIP consense) just calculate how often clades appear, instead of
475 calculating relative frequencies."""
476
477 for n in self._walk():
478 if self.node(n).data.support:
479 self.node(n).data.support/=float(nrep)
480
482 """Returns True if any of the nodes has data.support != None."""
483 for n in self._walk(node):
484 if self.node(n).data.support:
485 return True
486 else:
487 return False
488
489 - def randomize(self,ntax=None,taxon_list=None,branchlength=1.0,branchlength_sd=None,bifurcate=True):
490 """Generates a random tree with ntax taxa and/or taxa from taxlabels.
491
492 new_tree = randomize(self,ntax=None,taxon_list=None,branchlength=1.0,branchlength_sd=None,bifurcate=True)
493 Trees are bifurcating by default. (Polytomies not yet supported).
494 """
495
496 if not ntax and taxon_list:
497 ntax=len(taxon_list)
498 elif not taxon_list and ntax:
499 taxon_list=['taxon'+str(i+1) for i in range(ntax)]
500 elif not ntax and not taxon_list:
501 raise TreeError('Either numer of taxa or list of taxa must be specified.')
502 elif ntax != len(taxon_list):
503 raise TreeError('Length of taxon list must correspond to ntax.')
504
505 self.__init__()
506 terminals=self.get_terminals()
507
508 while len(terminals)<ntax:
509 newsplit=random.choice(terminals)
510 new_terminals=self.split(parent_id=newsplit,branchlength=branchlength)
511
512 if branchlength_sd:
513 for nt in new_terminals:
514 bl=random.gauss(branchlength,branchlength_sd)
515 if bl<0:
516 bl=0
517 self.node(nt).data.branchlength=bl
518 terminals.extend(new_terminals)
519 terminals.remove(newsplit)
520
521 random.shuffle(taxon_list)
522 for (node,name) in zip(terminals,taxon_list):
523 self.node(node).data.taxon=name
524
526 """Quick and dirty lists of all nodes."""
527 table=[('#','taxon','prev','succ','brlen','blen (sum)','support','comment')]
528 for i in self.all_ids():
529 n=self.node(i)
530 if not n.data:
531 table.append((str(i),'-',str(n.prev),str(n.succ),'-','-','-','-'))
532 else:
533 tx=n.data.taxon
534 if not tx:
535 tx='-'
536 blength=n.data.branchlength
537 if blength is None:
538 blength='-'
539 sum_blength='-'
540 else:
541 sum_blength=self.sum_branchlength(node=i)
542 support=n.data.support
543 if support is None:
544 support='-'
545 comment=n.data.comment
546 if comment is None:
547 comment='-'
548 table.append((str(i),tx,str(n.prev),str(n.succ),blength,sum_blength,support,comment))
549 print '\n'.join(['%3s %32s %15s %15s %8s %10s %8s %20s' % l for l in table])
550 print '\nRoot: ',self.root
551
552 - def to_string(self,support_as_branchlengths=False,branchlengths_only=False,plain=True,plain_newick=False,ladderize=None):
553 """Return a paup compatible tree line.
554
555 to_string(self,support_as_branchlengths=False,branchlengths_only=False,plain=True)
556 """
557
558 if support_as_branchlengths or branchlengths_only:
559 plain=False
560 self.support_as_branchlengths=support_as_branchlengths
561 self.branchlengths_only=branchlengths_only
562 self.plain=plain
563
564 def make_info_string(data,terminal=False):
565 """Creates nicely formatted support/branchlengths."""
566
567 if self.plain:
568 return ''
569 elif self.support_as_branchlengths:
570 if terminal:
571 return ':%1.2f' % self.max_support
572 else:
573 return ':%1.2f' % (data.support)
574 elif self.branchlengths_only:
575 return ':%1.5f' % (data.branchlength)
576 else:
577 if terminal:
578 return ':%1.5f' % (data.branchlength)
579 else:
580 if data.branchlength is not None and data.support is not None:
581 return '%1.2f:%1.5f' % (data.support,data.branchlength)
582 elif data.branchlength is not None:
583 return '0.00000:%1.5f' % (data.branchlength)
584 elif data.support is not None:
585 return '%1.2f:0.00000' % (data.support)
586 else:
587 return '0.00:0.00000'
588 def ladderize_nodes(nodes,ladderize=None):
589 """Sorts node numbers according to the number of terminal nodes."""
590 if ladderize in ['left','LEFT','right','RIGHT']:
591 succnode_terminals=[(self.count_terminals(node=n),n) for n in nodes]
592 succnode_terminals.sort()
593 if (ladderize=='right' or ladderize=='RIGHT'):
594 succnode_terminals.reverse()
595 if succnode_terminals:
596 succnodes=zip(*succnode_terminals)[1]
597 else:
598 succnodes=[]
599 else:
600 succnodes=nodes
601 return succnodes
602
603 def newickize(node,ladderize=None):
604 """Convert a node tree to a newick tree recursively."""
605
606 if not self.node(node).succ:
607 return self.node(node).data.taxon+make_info_string(self.node(node).data,terminal=True)
608 else:
609 succnodes=ladderize_nodes(self.node(node).succ,ladderize=ladderize)
610 subtrees=[newickize(sn,ladderize=ladderize) for sn in succnodes]
611 return '(%s)%s' % (','.join(subtrees),make_info_string(self.node(node).data))
612
613 treeline=['tree']
614 if self.name:
615 treeline.append(self.name)
616 else:
617 treeline.append('a_tree')
618 treeline.append('=')
619 if self.weight != 1:
620 treeline.append('[&W%s]' % str(round(float(self.weight),3)))
621 if self.rooted:
622 treeline.append('[&R]')
623 succnodes=ladderize_nodes(self.node(self.root).succ)
624 subtrees=[newickize(sn,ladderize=ladderize) for sn in succnodes]
625 treeline.append('(%s)' % ','.join(subtrees))
626 if plain_newick:
627 return treeline[-1]
628 else:
629 return ' '.join(treeline)+';'
630
632 """Short version of to_string(), gives plain tree"""
633 return self.to_string(plain=True)
634
636 """Defines a unrooted Tree structure, using data of a rooted Tree."""
637
638
639
640 def _get_branches(node):
641 branches=[]
642 for b in self.node(node).succ:
643 branches.append([node,b,self.node(b).data.branchlength,self.node(b).data.support])
644 branches.extend(_get_branches(b))
645 return branches
646
647 self.unrooted=_get_branches(self.root)
648
649 if len(self.node(self.root).succ)==2:
650
651 rootbranches=[b for b in self.unrooted if self.root in b[:2]]
652 b1=self.unrooted.pop(self.unrooted.index(rootbranches[0]))
653 b2=self.unrooted.pop(self.unrooted.index(rootbranches[1]))
654
655
656 newbranch=[b1[1],b2[1],b1[2]+b2[2]]
657 if b1[3] is None:
658 newbranch.append(b2[3])
659 elif b2[3] is None:
660 newbranch.append(b1[3])
661 elif b1[3]==b2[3]:
662 newbranch.append(b1[3])
663 elif b1[3]==0 or b2[3]==0:
664 newbranch.append(b1[3]+b2[3])
665 else:
666 raise TreeError('Support mismatch in bifurcating root: %f, %f' \
667 % (float(b1[3]),float(b2[3])))
668 self.unrooted.append(newbranch)
669
671
672 def _connect_subtree(parent,child):
673 """Hook subtree starting with node child to parent."""
674 for i,branch in enumerate(self.unrooted):
675 if parent in branch[:2] and child in branch[:2]:
676 branch=self.unrooted.pop(i)
677 break
678 else:
679 raise TreeError('Unable to connect nodes for rooting: nodes %d and %d are not connected' \
680 % (parent,child))
681 self.link(parent,child)
682 self.node(child).data.branchlength=branch[2]
683 self.node(child).data.support=branch[3]
684
685 child_branches=[b for b in self.unrooted if child in b[:2]]
686 for b in child_branches:
687 if child==b[0]:
688 succ=b[1]
689 else:
690 succ=b[0]
691 _connect_subtree(child,succ)
692
693
694 if outgroup is None:
695 return self.root
696 outgroup_node=self.is_monophyletic(outgroup)
697 if outgroup_node==-1:
698 return -1
699
700
701 if (len(self.node(self.root).succ)==2 and outgroup_node in self.node(self.root).succ) or outgroup_node==self.root:
702 return self.root
703
704 self.unroot()
705
706
707 for i,b in enumerate(self.unrooted):
708 if outgroup_node in b[:2] and self.node(outgroup_node).prev in b[:2]:
709 root_branch=self.unrooted.pop(i)
710 break
711 else:
712 raise TreeError('Unrooted and rooted Tree do not match')
713 if outgroup_node==root_branch[1]:
714 ingroup_node=root_branch[0]
715 else:
716 ingroup_node=root_branch[1]
717
718 for n in self.all_ids():
719 self.node(n).prev=None
720 self.node(n).succ=[]
721
722 root=Nodes.Node(data=NodeData())
723 self.add(root)
724 self.root=root.id
725 self.unrooted.append([root.id,ingroup_node,root_branch[2],root_branch[3]])
726 self.unrooted.append([root.id,outgroup_node,0.0,0.0])
727 _connect_subtree(root.id,ingroup_node)
728 _connect_subtree(root.id,outgroup_node)
729
730 oldroot=[i for i in self.all_ids() if self.node(i).prev is None and i!=self.root]
731 if len(oldroot)>1:
732 raise TreeError('Isolated nodes in tree description: %s' \
733 % ','.join(oldroot))
734 elif len(oldroot)==1:
735 self.kill(oldroot[0])
736 return self.root
737
739 """Merges clade support (from consensus or list of bootstrap-trees) with phylogeny.
740
741 tree=merge_bootstrap(phylo,bs_tree=<list_of_trees>)
742 or
743 tree=merge_bootstrap(phylo,consree=consensus_tree with clade support)
744 """
745
746 if bstrees and constree:
747 raise TreeError('Specify either list of boostrap trees or consensus tree, not both')
748 if not (bstrees or constree):
749 raise TreeError('Specify either list of boostrap trees or consensus tree.')
750
751 if outgroup is None:
752 try:
753 succnodes=self.node(self.root).succ
754 smallest=min([(len(self.get_taxa(n)),n) for n in succnodes])
755 outgroup=self.get_taxa(smallest[1])
756 except:
757 raise TreeError("Error determining outgroup.")
758 else:
759 self.root_with_outgroup(outgroup)
760
761 if bstrees:
762 constree=consensus(bstrees,threshold=threshold,outgroup=outgroup)
763 else:
764 if not constree.has_support():
765 constree.branchlength2support()
766 constree.root_with_outgroup(outgroup)
767
768 for pnode in self._walk():
769 cnode=constree.is_monophyletic(self.get_taxa(pnode))
770 if cnode>-1:
771 self.node(pnode).data.support=constree.node(cnode).data.support
772
773
774 -def consensus(trees, threshold=0.5,outgroup=None):
848