1
2
3
4
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 __docformat__ = "epytext en"
11
12 from Bio.Phylo import BaseTree, NewickIO, NexusIO
13
14
15 try:
16 from Bio.Phylo import PhyloXMLIO
17 except ImportError:
18
19
20
21
22 supported_formats = {
23 'newick': NewickIO,
24 'nexus': NexusIO,
25 }
26 else:
27 supported_formats = {
28 'newick': NewickIO,
29 'nexus': NexusIO,
30 'phyloxml': PhyloXMLIO,
31 }
32
33
35 """Iteratively parse a file and return each of the trees it contains.
36
37 If a file only contains one tree, this still returns an iterable object that
38 contains one element.
39
40 Example::
41
42 >>> trees = parse('../../Tests/PhyloXML/apaf.xml', 'phyloxml')
43 >>> for tree in trees:
44 ... print tree.rooted
45 True
46 """
47 do_close = False
48 if isinstance(file, basestring):
49 file = open(file, 'r')
50 do_close = True
51
52
53 for tree in getattr(supported_formats[format], 'parse')(file):
54 yield tree
55
56 if do_close:
57 file.close()
58
59
60 -def read(file, format):
61 """Parse a file in the given format and return a single tree.
62
63 Raises a ValueError if there are zero or multiple trees -- if this occurs,
64 use parse() instead to get the complete sequence of trees.
65 """
66 try:
67 tree_gen = parse(file, format)
68 tree = tree_gen.next()
69 except StopIteration:
70 raise ValueError("There are no trees in this file.")
71 try:
72 tree_gen.next()
73 except StopIteration:
74 return tree
75 else:
76 raise ValueError(
77 "There are multiple trees in this file; use parse() instead.")
78
79
80 -def write(trees, file, format, **kwargs):
81 """Write a sequence of trees to file in the given format."""
82 if isinstance(trees, BaseTree.Tree):
83
84 trees = [trees]
85 do_close = False
86 if isinstance(file, basestring):
87 file = open(file, 'w+')
88 do_close = True
89 try:
90 n = getattr(supported_formats[format], 'write')(trees, file, **kwargs)
91 finally:
92 if do_close:
93 file.close()
94 return n
95
96
97 -def convert(in_file, in_format, out_file, out_format, **kwargs):
98 """Convert between two tree file formats."""
99 trees = parse(in_file, in_format)
100 return write(trees, out_file, out_format, **kwargs)
101