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