Debian Codegraph @

weblogo/seq_io/nexus_io.py

raw
1 #!/usr/bin/env python
2
3 # Copyright 2005 Gavin E. Crooks <[email protected]>
4 # Copyright 2005-2006 The Regents of the University of California.
5 #
6 # This software is distributed under the MIT Open Source License.
7 # <http://www.opensource.org/licenses/mit-license.html>
8 #
9 # Permission is hereby granted, free of charge, to any person obtaining a
10 # copy of this software and associated documentation files (the "Software"),
11 # to deal in the Software without restriction, including without limitation
12 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
13 # and/or sell copies of the Software, and to permit persons to whom the
14 # Software is furnished to do so, subject to the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included
17 # in all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 # THE SOFTWARE.
26 #
27
28 """Read the sequence data from a nexus file.
29
30 This IO code only gives read access to the sequence data.
31
32 Reference:
33 'NEXUS: An extensible file format for systematic information'
34 Maddison, Swofford, Maddison. 1997. Syst. Biol. 46(4):590-621
35 """
36
37 from typing import Iterator, Optional, TextIO
38
39 from ..seq import Alphabet, Seq, SeqList
40 from .._ext.nexus import Nexus, safename
41
42 names = ("nexus", "paup")
43 extensions = ("nex", "nexus", "paup", "nxs")
44
45
46 def iterseq(fin: TextIO, alphabet: Optional[Alphabet] = None) -> Iterator[Seq]:
47 """Iterate over the sequences in the file."""
48 # Default implementation
49 return iter(read(fin, alphabet))
50
51
52 def read(fin: TextIO, alphabet: Optional[Alphabet] = None) -> SeqList:
53 """Extract sequence data from a nexus file."""
54 n = Nexus(fin)
55
56 seqs = []
57 for taxon in n.taxlabels:
58 name = safename(taxon)
59 r = n.matrix[taxon]
60 if alphabet is None:
61 s = Seq(r, name=name, alphabet=r.alphabet)
62 else:
63 s = Seq(r, name=name, alphabet=alphabet)
64 seqs.append(s)
65
66 if len(seqs) == 0:
67 # Something went terrible wrong.
68 raise ValueError("Cannot parse file")
69
70 return SeqList(seqs)