| 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 sequence information in FASTA format. |
| 28 |
|
| 29 |
This is a very common format for unannotated biological sequence data, |
| 30 |
accepted by many multiple sequence alignment programs. Each sequence |
| 31 |
consists of a single-line description, followed by lines of sequence data. |
| 32 |
The first character of the description line is a greater-than (">") symbol |
| 33 |
in the first column. The first word of the description is often the name or |
| 34 |
ID of the sequence. Fasta files containing multiple sequences have one |
| 35 |
sequence listed right after another. |
| 36 |
|
| 37 |
|
| 38 |
Example Fasta File :: |
| 39 |
|
| 40 |
>Lamprey GLOBIN V - SEA LAMPREY |
| 41 |
PIVDTGSVA-P------------------LSAAEKTKIRSAWAPVYSTY---ETSGVDILVKFFTSTPAAQEFFPKFKGL |
| 42 |
TT-----ADQLKKSA---DVRWHA-ERIINAVNDAVASMDDTEKMS--MKL-RDLSGKH----AKSFQV-----DPQYFK |
| 43 |
VLAAVI-AD-TVAAGD--AGFEKLMSM------I---CILLR----S-----A-----Y------------ |
| 44 |
>Hagfish GLOBIN III - ATLANTIC HAGFISH |
| 45 |
PITDHGQPP-T------------------LSEGDKKAIRESWPQIYKNF---EQNSLAVLLEFLKKFPKAQDSFPKFSAK |
| 46 |
KS-------HLEQDP---AVKLQA-EVIINAVNHTIGLMDKEAAMK--KYL-KDLSTKH----STEFQV-----NPDMFK |
| 47 |
ELSAVF-VS-TMG-GK--AAYEKLFSI------I---ATLLR----S-----T-----YDA---------- |
| 48 |
>Frog HEMOGLOBIN BETA CHAIN - EDIBLE FROG |
| 49 |
----------GS-----------------------DLVSGFWGKV--DA---HKIGGEALARLLVVYPWTQRYFTTFGNL |
| 50 |
GSADAIC-----HNA---KVLAHG-EKVLAAIGEGLKHPENLKAHY--AKL-SEYHSNK----LHVDPANFRLLGNVFIT |
| 51 |
VLARHF-QH-EFTPELQ-HALEAHFCA------V---GDALA----K-----A-----YH----------- |
| 52 |
|
| 53 |
|
| 54 |
""" |
| 55 |
|
| 56 |
from typing import Iterator, List, Optional, TextIO |
| 57 |
|
| 58 |
from ..seq import Alphabet, Seq, SeqList |
| 59 |
|
| 60 |
names = ("fasta", "pearson", "fa") |
| 61 |
extensions = ( |
| 62 |
"fa", |
| 63 |
"fasta", |
| 64 |
"fast", |
| 65 |
"seq", |
| 66 |
"fsa", |
| 67 |
"fst", |
| 68 |
"nt", |
| 69 |
"aa", |
| 70 |
"fna", |
| 71 |
"mpfa", |
| 72 |
"faa", |
| 73 |
"fnn", |
| 74 |
"mfasta", |
| 75 |
"tfa", |
| 76 |
"pfa", |
| 77 |
) |
| 78 |
|
| 79 |
example = """ |
| 80 |
>Lamprey GLOBIN V - SEA LAMPREY |
| 81 |
PIVDTGSVA-P------------------LSAAEKTKIRSAWAPVYSTY---ETSGVDILVKFFTSTPAAQEFFPKFKGL |
| 82 |
TT-----ADQLKKSA---DVRWHA-ERIINAVNDAVASMDDTEKMS--MKL-RDLSGKH----AKSFQV-----DPQYFK |
| 83 |
VLAAVI-AD-TVAAGD--AGFEKLMSM------I---CILLR----S-----A-----Y------------ |
| 84 |
|
| 85 |
>Hagfish GLOBIN III - ATLANTIC HAGFISH |
| 86 |
PITDHGQPP-T------------------LSEGDKKAIRESWPQIYKNF---EQNSLAVLLEFLKKFPKAQDSFPKFSAK |
| 87 |
KS-------HLEQDP---AVKLQA-EVIINAVNHTIGLMDKEAAMK--KYL-KDLSTKH----STEFQV-----NPDMFK |
| 88 |
ELSAVF-VS-TMG-GK--AAYEKLFSI------I---ATLLR----S-----T-----YDA---------- |
| 89 |
|
| 90 |
>Frog HEMOGLOBIN BETA CHAIN - EDIBLE FROG |
| 91 |
----------GS-----------------------DLVSGFWGKV--DA---HKIGGEALARLLVVYPWTQRYFTTFGNL |
| 92 |
GSADAIC-----HNA---KVLAHG-EKVLAAIGEGLKHPENLKAHY--AKL-SEYHSNK----LHVDPANFRLLGNVFIT |
| 93 |
VLARHF-QH-EFTPELQ-HALEAHFCA------V---GDALA----K-----A-----YH----------- |
| 94 |
|
| 95 |
""" |
| 96 |
|
| 97 |
|
| 98 |
def read(fin: TextIO, alphabet: Optional[Alphabet] = None) -> SeqList: |
| 99 |
"""Read and parse a fasta file. |
| 100 |
|
| 101 |
Args: |
| 102 |
fin -- A stream or file to read |
| 103 |
alphabet -- The expected alphabet of the data, if given |
| 104 |
Returns: |
| 105 |
SeqList -- A list of sequences |
| 106 |
Raises: |
| 107 |
ValueError -- If the file is unparsable |
| 108 |
""" |
| 109 |
seqs = [s for s in iterseq(fin, alphabet)] |
| 110 |
name = names[0] |
| 111 |
if hasattr(fin, "name"): |
| 112 |
name = fin.name |
| 113 |
return SeqList(seqs, name=name) |
| 114 |
|
| 115 |
|
| 116 |
# def readseq(fin: TextIO, alphabet: Alphabet = None) -> Seq: |
| 117 |
# """Read one sequence from the file, starting |
| 118 |
# from the current file position.""" |
| 119 |
# return next(iterseq(fin, alphabet)) |
| 120 |
|
| 121 |
|
| 122 |
def iterseq(fin: TextIO, alphabet: Optional[Alphabet] = None) -> Iterator[Seq]: |
| 123 |
"""Parse a fasta file and generate sequences. |
| 124 |
|
| 125 |
Args: |
| 126 |
fin -- A stream or file to read |
| 127 |
alphabet -- The expected alphabet of the data, if given |
| 128 |
Yields: |
| 129 |
Seq -- One alphabetic sequence at a time. |
| 130 |
Raises: |
| 131 |
ValueError -- If the file is unparsable |
| 132 |
""" |
| 133 |
alphabet = Alphabet(alphabet) |
| 134 |
|
| 135 |
seqs = [] |
| 136 |
comments: List[str] = [] # FIXME: comments before first sequence are lost. |
| 137 |
header = None |
| 138 |
header_lineno = -1 |
| 139 |
|
| 140 |
def build_seq( |
| 141 |
seqs: List[str], |
| 142 |
alphabet: Alphabet, |
| 143 |
header: str, |
| 144 |
header_lineno: int, |
| 145 |
comments: List[str], |
| 146 |
) -> Seq: |
| 147 |
try: |
| 148 |
name = header.split(" ", 1)[0] |
| 149 |
if comments: |
| 150 |
header += "\n" + "\n".join(comments) |
| 151 |
s = Seq("".join(seqs), alphabet, name=name, description=header) |
| 152 |
except ValueError: |
| 153 |
raise ValueError( |
| 154 |
"Parse failed with sequence starting at line %d: " |
| 155 |
"Character not in alphabet: %s" % (header_lineno, alphabet) |
| 156 |
) |
| 157 |
return s |
| 158 |
|
| 159 |
for lineno, line in enumerate(fin): |
| 160 |
line = line.strip() |
| 161 |
if line == "": |
| 162 |
continue |
| 163 |
if line.startswith(">"): |
| 164 |
if header is not None: |
| 165 |
yield build_seq(seqs, alphabet, header, header_lineno, comments) |
| 166 |
header = None |
| 167 |
seqs = [] |
| 168 |
header = line[1:] |
| 169 |
header_lineno = lineno |
| 170 |
comments = [] |
| 171 |
elif line.startswith(";"): |
| 172 |
# Optional (and unusual) comment line |
| 173 |
comments.append(line[1:]) |
| 174 |
else: |
| 175 |
if header is None: |
| 176 |
raise ValueError( |
| 177 |
"Parse failed on line %d: sequence before header" % (lineno) |
| 178 |
) |
| 179 |
seqs.append(line) |
| 180 |
|
| 181 |
if not seqs: |
| 182 |
return |
| 183 |
assert header is not None |
| 184 |
yield build_seq(seqs, alphabet, header, header_lineno, comments) |
| 185 |
|
| 186 |
|
| 187 |
def write(fout: TextIO, seqs: SeqList) -> None: |
| 188 |
"""Write a fasta file. |
| 189 |
|
| 190 |
Args: |
| 191 |
fout -- A writable stream. |
| 192 |
seqs -- A list of Seq's |
| 193 |
""" |
| 194 |
if seqs.description: |
| 195 |
for line in seqs.description.splitlines(): |
| 196 |
print(";" + line, file=fout) |
| 197 |
for s in seqs: |
| 198 |
writeseq(fout, s) |
| 199 |
|
| 200 |
|
| 201 |
def writeseq(afile: TextIO, seq: Seq) -> None: |
| 202 |
"""Write a single sequence in fasta format. |
| 203 |
|
| 204 |
Args: |
| 205 |
afile -- A writable stream. |
| 206 |
seq -- A Seq instance |
| 207 |
""" |
| 208 |
header = seq.description or seq.name or "" |
| 209 |
# We prepend '>' to the first header line |
| 210 |
# Additional lines start with ';' to indicate comment lines |
| 211 |
if header: |
| 212 |
headings = header.splitlines() |
| 213 |
print(">" + headings[0], file=afile) |
| 214 |
if len(headings) > 1: |
| 215 |
for h in headings[1:]: |
| 216 |
print(";" + h, file=afile) |
| 217 |
else: |
| 218 |
print(">", file=afile) |
| 219 |
L = len(seq) |
| 220 |
line_length = 80 |
| 221 |
for n in range(1 + L // line_length): |
| 222 |
print(seq[n * line_length : (n + 1) * line_length], file=afile) |
| 223 |
print(file=afile) |