Debian Codegraph @

weblogo/seq_io/clustal_io.py

raw
1 # Copyright (c) 2005 Gavin E. Crooks <[email protected]>
2 #
3 # This software is distributed under the MIT Open Source License.
4 # <http://www.opensource.org/licenses/mit-license.html>
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a
7 # copy of this software and associated documentation files (the "Software"),
8 # to deal in the Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Software, and to permit persons to whom the
11 # Software is furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 """Read and write the CLUSTAL sequence file format.
26
27 See :
28 - http://www.cmpharm.ucsf.edu/~goh/Treecorr/sampleAlignment.html
29 - http://www.bioperl.org/wiki/ClustalW_multiple_alignment_format
30
31 Ref :
32 - Higgins D., Thompson J., Gibson T., Thompson J.D., Higgins D.G., Gibson
33 T.J. (1994). CLUSTAL W: improving the sensitivity of progressive multiple
34 sequence alignment through sequence weighting, position-specific gap
35 penalties and weight matrix choice. Nucleic Acids Res. 22:4673-4680.
36 """
37
38 # TODO: What happens if CLUSTAL is not the first line of the file?
39
40 import re
41 from typing import Iterator, Optional, TextIO
42
43 from ..seq import Alphabet, Seq, SeqList
44 from ..utils import Token
45
46 __all__ = ("example", "names", "extensions", "read")
47
48 example = """
49 CLUSTAL W (1.81) multiple sequence alignment
50
51
52 CXCR3_MOUSE --------------------------LENSTSPYDYGENESD-------FSDSPPCPQDF
53 BLR_HUMAN --------------------------LENLEDLF-WELDRLD------NYNDTSLVENH-
54 CXCR1_HUMAN --------------------------MSNITDPQMWDFDDLN-------FTGMPPADEDY
55 CXCR4_MURINE -----------------------------------YTSDN---------YSGSGDYDSNK
56 : : :.. ..
57
58 CXCR3_MOUSE -SL-------NFDRTFLPALYSLLFLLGLLGNGAVAAVLLSQRTALSSTDTFLLHLAVAD
59 BLR_HUMAN --LC-PATMASFKAVFVPVAYSLIFLLGVIGNVLVLVILERHRQTRSSTETFLFHLAVAD
60 CXCR1_HUMAN -SPC-MLETETLNKYVVIIAYALVFLLSLLGNSLVMLVILYSRVGRSVTDVYLLNLALAD
61 CXCR4_MURINE -EPC-RDENVHFNRIFLPTIYFIIFLTGIVGNGLVILVMGYQKKLRSMTDKYRLHLSVAD
62 :. .: * ::** .::** * :: : * *: : ::*::**
63
64 CXCR3_MOUSE VLLVLTLPLWAVDAA-VQWVFGPGLCKVAGALFNINFYAGAFLLACISFDRYLSIVHATQ
65 BLR_HUMAN LLLVFILPFAVAEGS-VGWVLGTFLCKTVIALHKVNFYCSSLLLACIAVDRYLAIVHAVH
66 CXCR1_HUMAN LLFALTLPIWAASKV-NGWIFGTFLCKVVSLLKEVNFYSGILLLACISVDRYLAIVHATR
67 CXCR4_MURINE LLFVITLPFWAVDAM-ADWYFGKFLCKAVHIIYTVNLYSSVLILAFISLDRYLAIVHATN
68 :*:.: **: ... * :* ***.. : :*:*.. ::** *:.****:****..
69 """
70
71 names = (
72 "clustal",
73 "clustalw",
74 )
75 extensions = ("aln",)
76
77 header_line = re.compile(r"(CLUSTAL.*)$")
78
79 # (sequence_id) (Sequence) (Optional sequence number)
80 seq_line = re.compile(r"(\s*\S+\s+)(\S+)\s*(\d*)\s*$")
81
82 # Saved group includes variable length leading space.
83 # Must consult a seq_line to figure out how long the leading space is since
84 # the maximum CLUSTAL ids length (normally 10 characters) can be changed.
85 match_line = re.compile(r"([\s:\.\*]*)$")
86
87
88 def iterseq(fin: TextIO, alphabet: Optional[Alphabet] = None) -> Iterator[Seq]:
89 """Iterate over the sequences in the file."""
90 # Default implementation
91 return iter(read(fin, alphabet))
92
93
94 def read(fin: TextIO, alphabet: Optional[Alphabet] = None) -> SeqList:
95 alphabet = Alphabet(alphabet)
96 seq_ids = []
97 seqs: list = []
98 block_count = 0
99 data_len = 0
100
101 for token in _scan(fin):
102 if token.typeof == "begin_block":
103 block_count = 0
104 elif token.typeof == "seq_id":
105 if len(seqs) <= block_count:
106 seq_ids.append(token.data)
107 seqs.append([])
108
109 elif token.typeof == "seq":
110 data = token.data
111 assert data is not None
112
113 if not alphabet.alphabetic(data):
114 raise ValueError(
115 "Character on line: %d not in alphabet: %s : %s"
116 % (token.lineno, alphabet, data)
117 )
118 seqs[block_count].append(data)
119 if block_count == 0:
120 data_len = len(data)
121 elif data_len != len(data):
122 raise ValueError("Inconsistent line lengths")
123
124 block_count += 1
125
126 seqs = [Seq("".join(s), alphabet, name=i) for s, i in zip(seqs, seq_ids)]
127 return SeqList(seqs)
128
129
130 # 1) The word "CLUSTAL" should be the first word on the first line of the file.
131 # (But sometimes isn't.)
132 # 2) The alignment is displayed in blocks of fixed length.
133 # 3) Each line in the block corresponds to one sequence.
134 # 4) Each sequence line starts with a sequence name followed by at least one
135 # space and then the sequence.
136
137
138 def _scan(fin: TextIO) -> Iterator[Token]:
139 """Scan a clustal format MSA file and yield tokens.
140 The basic file structure is
141 begin_document
142 header?
143 (begin_block
144 (seq_id seq seq_index?)+
145 match_line?
146 end_block)*
147 end_document
148
149 Usage:
150 for token in scan(clustal_file):
151 do_something(token)
152 """
153 header, body, block = range(3)
154
155 yield Token("begin")
156 leader_width = -1
157 state = header
158 for L, line in enumerate(fin):
159 if state == header:
160 if line.isspace():
161 continue
162 m = header_line.match(line)
163 state = body
164 if m is not None:
165 yield Token("header", m.group())
166 continue
167 # Just keep going and hope for the best.
168 # else:
169 # raise ValueError("Cannot find required header")
170
171 if state == body:
172 if line.isspace():
173 continue
174 yield Token("begin_block")
175 state = block
176 # fall through to block
177
178 if state == block:
179 if line.isspace():
180 yield Token("end_block")
181 state = body
182 continue
183
184 m = match_line.match(line)
185 if m is not None:
186 yield Token("match_line", line[leader_width:-1])
187 continue
188
189 m = seq_line.match(line)
190 if m is None:
191 raise ValueError("Parse error on line: %d (%s)" % (L, line))
192 leader_width = len(m.group(1))
193 yield Token("seq_id", m.group(1).strip())
194 yield Token("seq", m.group(2).strip())
195 if m.group(3):
196 yield Token("seq_num", m.group(3))
197 continue
198
199 # END state blocks. If I ever get here something has gone terrible wrong
200 raise RuntimeError() # pragma: nocover
201
202 if state == block:
203 yield Token("end_block")
204 yield Token("end")
205
206
207 def write(fout: TextIO, seqs: SeqList) -> None:
208 """Write 'seqs' to 'fout' as text in clustal format"""
209 header = "CLUSTAL W (1.81) multiple sequence alignment"
210 name_width = 17
211 seq_width = 60
212
213 print(header, end="\n\n", file=fout)
214 L = max(len(s) for s in seqs)
215 for block in range(0, L, seq_width):
216 for s in seqs:
217 start = min(block, len(s))
218 end = min(start + seq_width, len(s))
219 print(s.name.ljust(name_width), end="", file=fout)
220 print(s[start:end], file=fout)
221
222 print(file=fout)