Package Bio :: Package Phylo :: Module NexusIO
[hide private]
[frames] | no frames]

Source Code for Module Bio.Phylo.NexusIO

 1  # Copyright (C) 2009 by Eric Talevich (eric.talevich@gmail.com) 
 2  # This code is part of the Biopython distribution and governed by its 
 3  # license. Please see the LICENSE file that should have been included 
 4  # as part of this package. 
 5   
 6  """I/O function wrappers for `Bio.Nexus` trees.""" 
 7  __docformat__ = "restructuredtext en" 
 8   
 9  from itertools import chain 
10   
11  from Bio.Nexus import Nexus 
12  from Bio.Phylo import Newick, NewickIO 
13   
14   
15  # Structure of a Nexus tree-only file 
16  NEX_TEMPLATE = """\ 
17  #NEXUS 
18  Begin Taxa; 
19   Dimensions NTax=%(count)d; 
20   TaxLabels %(labels)s; 
21  End; 
22  Begin Trees; 
23   %(trees)s 
24  End; 
25  """ 
26   
27  # 'index' starts from 1; 'tree' is the Newick tree string 
28  TREE_TEMPLATE = "Tree tree%(index)d=[&U]%(tree)s" 
29   
30   
31 -def parse(handle):
32 """Parse the trees in a Nexus file. 33 34 Uses the old Nexus.Trees parser to extract the trees, converts them back to 35 plain Newick trees, and feeds those strings through the new Newick parser. 36 This way we don't have to modify the Nexus module yet. (Perhaps we'll 37 eventually change Nexus to use the new NewickIO parser directly.) 38 """ 39 nex = Nexus.Nexus(handle) 40 41 # NB: Once Nexus.Trees is modified to use Tree.Newick objects, do this: 42 # return iter(nex.trees) 43 # Until then, convert the Nexus.Trees.Tree object hierarchy: 44 def node2clade(nxtree, node): 45 subclades = [node2clade(nxtree, nxtree.node(n)) for n in node.succ] 46 return Newick.Clade( 47 branch_length=node.data.branchlength, 48 name=node.data.taxon, 49 clades=subclades, 50 confidence=node.data.support, 51 comment=node.data.comment)
52 53 for nxtree in nex.trees: 54 newroot = node2clade(nxtree, nxtree.node(nxtree.root)) 55 yield Newick.Tree(root=newroot, rooted=nxtree.rooted, name=nxtree.name, 56 weight=nxtree.weight) 57 58
59 -def write(obj, handle, **kwargs):
60 """Write a new Nexus file containing the given trees. 61 62 Uses a simple Nexus template and the NewickIO writer to serialize just the 63 trees and minimal supporting info needed for a valid Nexus file. 64 """ 65 trees = list(obj) 66 writer = NewickIO.Writer(trees) 67 nexus_trees = [TREE_TEMPLATE % {'index': idx + 1, 'tree': nwk} 68 for idx, nwk in enumerate( 69 writer.to_strings(plain=False, plain_newick=True, 70 **kwargs))] 71 tax_labels = [str(x) for x in chain(*(t.get_terminals() for t in trees))] 72 text = NEX_TEMPLATE % { 73 'count': len(tax_labels), 74 'labels': ' '.join(tax_labels), 75 'trees': '\n'.join(nexus_trees), 76 } 77 handle.write(text) 78 return len(nexus_trees)
79