Debian Codegraph @

weblogo/seq_io/genbank_io.py

raw
1 #!/usr/bin/env python
2
3
4 """Read GenBank flat files.
5
6 Currently only reads sequence data and not annotations.
7
8 """
9
10 from typing import Iterator, Optional, TextIO
11
12 from ..seq import Alphabet, Seq, SeqList
13 from ..utils import isblank
14
15 names = ("genbank",)
16 extensions = ("gb", "genbank", "gbk")
17
18
19 def read(fin: TextIO, alphabet: Optional[Alphabet] = None) -> SeqList:
20 """Read and parse a file of genbank records.
21
22 Args:
23 fin -- A stream or file to read
24 alphabet -- The expected alphabet of the data, if given
25
26 Returns:
27 SeqList -- A list of sequences
28
29 Raises:
30 ValueError -- If the file is unparsable
31 """
32 seqs = [s for s in iterseq(fin, alphabet)]
33 return SeqList(seqs)
34
35
36 def iterseq(fin: TextIO, alphabet: Optional[Alphabet] = None) -> Iterator[Seq]:
37 """Iterate over genbank records
38
39 Args:
40 fin -- A stream or file to read
41 alphabet -- The expected alphabet of the data, if given
42
43 Yields:
44 Seq -- One alphabetic sequence at a time.
45
46 Raises:
47 ValueError -- If the file is unparsable
48 """
49 alphabet = Alphabet(alphabet)
50
51 header, block, data = range(3)
52 state = header
53 seq: list = []
54 for L, line in enumerate(fin):
55 if isblank(line):
56 continue
57 if state == header:
58 if not line.startswith("LOCUS"):
59 raise ValueError("Cannot find start of record at line %d" % L)
60 state = block
61 elif state == block:
62 if line.startswith("ORIGIN") or line.startswith("//"):
63 state = data
64 elif state == data:
65 if line.startswith("//"):
66 yield Seq("".join(seq), alphabet)
67 seq = []
68 state = block
69 else:
70 seq.extend(line.split()[1:])