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

Source Code for Module Bio.Phylo._io

 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 phylogenetic tree formats. 
 7   
 8  This API follows the same semantics as Biopython's `SeqIO` and `AlignIO`. 
 9  """ 
10   
11  from __future__ import print_function 
12   
13  __docformat__ = "restructuredtext en" 
14   
15  from Bio import File 
16  from Bio.Phylo import ( 
17                         BaseTree,  
18                         NewickIO,  
19                         NexusIO,  
20                         PhyloXMLIO, 
21                         NeXMLIO, 
22                         ) 
23   
24  supported_formats = { 
25          'newick':   NewickIO, 
26          'nexus':    NexusIO, 
27          'phyloxml': PhyloXMLIO, 
28          'nexml':    NeXMLIO, 
29          } 
30   
31  try:  
32      from Bio.Phylo import CDAOIO 
33      supported_formats['cdao'] = CDAOIO 
34  except: 
35      pass 
36   
37   
38 -def parse(file, format, **kwargs):
39 """Iteratively parse a file and return each of the trees it contains. 40 41 If a file only contains one tree, this still returns an iterable object that 42 contains one element. 43 44 Example 45 ------- 46 47 >>> trees = parse('../../Tests/PhyloXML/apaf.xml', 'phyloxml') 48 >>> for tree in trees: 49 ... print(tree.rooted) 50 True 51 """ 52 with File.as_handle(file, 'r') as fp: 53 for tree in getattr(supported_formats[format], 'parse')(fp, **kwargs): 54 yield tree
55 56
57 -def read(file, format, **kwargs):
58 """Parse a file in the given format and return a single tree. 59 60 Raises a `ValueError` if there are zero or multiple trees -- if this occurs, 61 use `parse` instead to get the complete sequence of trees. 62 """ 63 try: 64 tree_gen = parse(file, format, **kwargs) 65 tree = next(tree_gen) 66 except StopIteration: 67 raise ValueError("There are no trees in this file.") 68 try: 69 next(tree_gen) 70 except StopIteration: 71 return tree 72 else: 73 raise ValueError( 74 "There are multiple trees in this file; use parse() instead.")
75 76
77 -def write(trees, file, format, **kwargs):
78 """Write a sequence of trees to file in the given format.""" 79 if isinstance(trees, BaseTree.Tree) or isinstance(trees, BaseTree.Clade): 80 # Passed a single tree instead of an iterable -- that's OK 81 trees = [trees] 82 with File.as_handle(file, 'w+') as fp: 83 n = getattr(supported_formats[format], 'write')(trees, fp, **kwargs) 84 return n
85 86
87 -def convert(in_file, in_format, out_file, out_format, parse_args={}, **kwargs):
88 """Convert between two tree file formats.""" 89 trees = parse(in_file, in_format, **parse_args) 90 return write(trees, out_file, out_format, **kwargs)
91