Debian Codegraph @

weblogo/seq_io/array_io.py

raw
1 #!/usr/bin/env python
2
3 # Copyright (c) 2005 Gavin E. Crooks <[email protected]>
4 #
5 # This software is distributed under the MIT Open Source License.
6 # <http://www.opensource.org/licenses/mit-license.html>
7 #
8 # Permission is hereby granted, free of charge, to any person obtaining a
9 # copy of this software and associated documentation files (the "Software"),
10 # to deal in the Software without restriction, including without limitation
11 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 # and/or sell copies of the Software, and to permit persons to whom the
13 # Software is furnished to do so, subject to the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be included
16 # in all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 # THE SOFTWARE.
25 #
26
27 """Read and write a rectangular array of sequence data.
28
29 One sequence per line and nothing else. Each line must contain the same number
30 of characters. Blank lines and white space are ignored.
31
32 --- Example Array ---
33
34 --------------------------LENSTSPYDYGENESD-------FSDSPPCPQDF
35 --------------------------LENLEDLF-WELDRLD------NYNDTSLVENH-
36 --------------------------MSNITDPQMWDFDDLN-------FTGMPPADEDY
37 -----------------------------------YTSDN---------YSGSGDYDSNK
38 -SL-------NFDRTFLPALYSLLFLLGLLGNGAVAAVLLSQRTALSSTDTFLLHLAVAD
39 --LC-PATMASFKAVFVPVAYSLIFLLGVIGNVLVLVILERHRQTRSSTETFLFHLAVAD
40 -SPC-MLETETLNKYVVIIAYALVFLLSLLGNSLVMLVILYSRVGRSVTDVYLLNLALAD
41 -EPC-RDENVHFNRIFLPTIYFIIFLTGIVGNGLVILVMGYQKKLRSMTDKYRLHLSVAD
42 """
43
44 from typing import Generator, Optional, TextIO
45
46 from ..seq import Alphabet, Seq, SeqList
47 from ..utils import remove_whitespace
48
49 example = """
50 --------------------------LENSTSPYDYGENESD-------FSDSPPCPQDF
51 --------------------------LENLEDLF-WELDRLD------NYNDTSLVENH-
52 --------------------------MSNITDPQMWDFDDLN-------FTGMPPADEDY
53 -----------------------------------YTSDN---------YSGSGDYDSNK
54 -SL-------NFDRTFLPALYSLLFLLGLLGNGAVAAVLLSQRTALSSTDTFLLHLAVAD
55 --LC-PATMASFKAVFVPVAYSLIFLLGVIGNVLVLVILERHRQTRSSTETFLFHLAVAD
56 -SPC-MLETETLNKYVVIIAYALVFLLSLLGNSLVMLVILYSRVGRSVTDVYLLNLALAD
57 -EPC-RDENVHFNRIFLPTIYFIIFLTGIVGNGLVILVMGYQKKLRSMTDKYRLHLSVAD
58 """
59
60 names = ("array", "flatfile")
61 extensions = ()
62
63
64 def read(fin: TextIO, alphabet: Optional[Alphabet] = None) -> SeqList:
65 """Read a file of raw sequence alignment data.
66
67 Args:
68 fin -- A stream or file to read
69 alphabet -- The expected alphabet of the data, if given
70 Returns:
71 SeqList -- A list of sequences
72 Raises:
73 ValueError -- If the file is unparsable
74 """
75 seqs = [s for s in iterseq(fin, alphabet)]
76 return SeqList(seqs)
77
78
79 def iterseq(fin: TextIO, alphabet: Optional[Alphabet] = None) -> Generator:
80 """Read one line of sequence data and yield the sequence.
81
82 Args:
83 fin -- A stream or file to read
84 alphabet -- The expected alphabet of the data, if given
85 Yields:
86 Seq -- One alphabetic sequence at a time.
87 Raises:
88 ValueError -- If the file is unparsable
89 """
90
91 alphabet = Alphabet(alphabet)
92 line_length = 0
93
94 for linenum, line in enumerate(fin):
95 if line.isspace():
96 continue # Blank line
97 line = line.strip()
98
99 if line[0] == ">": # probably a fasta file. Fail.
100 raise ValueError("Parse Error on input line: %d " % linenum)
101
102 line = remove_whitespace(line)
103
104 if not alphabet.alphabetic(line):
105 raise ValueError(
106 "Character on line: %d not in alphabet: %s : %s"
107 % (linenum, alphabet, line)
108 )
109
110 if line_length and line_length != len(line):
111 raise ValueError("Line %d has an incommensurate length." % linenum)
112 line_length = len(line)
113
114 yield Seq(line, alphabet)
115
116
117 def write(afile: TextIO, seqs: SeqList) -> None:
118 """Write raw sequence data, one line per sequence.
119
120 arguments:
121 afile -- A writable stream.
122 seqs -- A list of Seq's
123 """
124 for s in seqs:
125 writeseq(afile, s)
126
127
128 def writeseq(afile: TextIO, seq: SeqList) -> None:
129 """Write a single sequence in raw format.
130
131 arguments:
132 afile -- A writable stream.
133 seq -- A Seq instance
134 """
135 print(seq, file=afile)