Package Bio :: Package SeqIO :: Module Interfaces
[hide private]
[frames] | no frames]

Source Code for Module Bio.SeqIO.Interfaces

  1  # Copyright 2006-2013 by Peter Cock.  All rights reserved. 
  2  # 
  3  # This file is part of the Biopython distribution and governed by your 
  4  # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". 
  5  # Please see the LICENSE file that should have been included as part of this 
  6  # package. 
  7  """Bio.SeqIO support module (not for general use). 
  8   
  9  Unless you are writing a new parser or writer for Bio.SeqIO, you should not 
 10  use this module.  It provides base classes to try and simplify things. 
 11  """ 
 12   
 13  from __future__ import print_function 
 14   
 15  import sys  # for checking if Python 2 
 16   
 17  from Bio.Alphabet import generic_alphabet 
 18  from Bio.Seq import Seq, MutableSeq 
 19  from Bio.SeqRecord import SeqRecord 
 20   
 21   
22 -class SequenceIterator(object):
23 """Base class for building SeqRecord iterators. 24 25 You should write a __next__ method to return SeqRecord objects. You may 26 wish to redefine the __init__ method as well. 27 """ 28
29 - def __init__(self, handle, alphabet=generic_alphabet):
30 """Create a SequenceIterator object. 31 32 Arguments: 33 - handle - input file 34 - alphabet - optional, e.g. Bio.Alphabet.generic_protein 35 36 This method MAY be overridden by any subclass, for example if you need 37 to process a header or accept additional arguments. 38 39 Note when subclassing: 40 - there should be a single non-optional argument, the handle. 41 - you do not have to require an alphabet. 42 - you can add additional optional arguments. 43 """ 44 self.handle = handle 45 self.alphabet = alphabet
46
47 - def __next__(self):
48 """Return the next record in the file. 49 50 This method's stub-implementation MUST be overridden by any subclass 51 to actually parse the file and return the next entry as a SeqRecord 52 object. 53 """ 54 raise NotImplementedError("The subclass should implement the __next__ method.")
55 56 if sys.version_info[0] < 3:
57 - def next(self):
58 """Python 2 style alias for Python 3 style __next__ method.""" 59 return self.__next__()
60
61 - def __iter__(self):
62 """Iterate over the entries as a SeqRecord objects. 63 64 Example usage for Fasta files:: 65 66 with open("example.fasta","r") as myFile: 67 myFastaReader = FastaIterator(myFile) 68 for record in myFastaReader: 69 print(record.id) 70 print(record.seq) 71 72 This method SHOULD NOT be overridden by any subclass. It should be 73 left as is, which will call the subclass implementation of __next__ 74 to actually parse the file. 75 """ 76 return iter(self.__next__, None)
77 78 79 # Function variant of the SequenceWriter method.
80 -def _get_seq_string(record):
81 """Use this to catch errors like the sequence being None (PRIVATE).""" 82 if not isinstance(record, SeqRecord): 83 raise TypeError("Expected a SeqRecord object") 84 if record.seq is None: 85 raise TypeError("SeqRecord (id=%s) has None for its sequence." 86 % record.id) 87 elif not isinstance(record.seq, (Seq, MutableSeq)): 88 raise TypeError("SeqRecord (id=%s) has an invalid sequence." 89 % record.id) 90 return str(record.seq)
91 92 93 # Function variant of the SequenceWriter method.
94 -def _clean(text):
95 """Use this to avoid getting newlines in the output (PRIVATE).""" 96 return text.replace("\n", " ").replace("\r", " ").replace(" ", " ")
97 98
99 -class SequenceWriter(object):
100 """Base class for building SeqRecord writers. 101 102 Interlaced file formats (e.g. Clustal) should subclass directly. 103 104 Sequential file formats (e.g. Fasta, GenBank) should subclass the 105 SequentialSequenceWriter class instead. 106 """ 107
108 - def __init__(self, handle):
109 """Create the writer object. 110 111 Use the method write_file() to actually record your sequence records. 112 """ 113 self.handle = handle
114
115 - def _get_seq_string(self, record):
116 """Use this to catch errors like the sequence being None (PRIVATE).""" 117 if not isinstance(record, SeqRecord): 118 raise TypeError("Expected a SeqRecord object") 119 if record.seq is None: 120 raise TypeError("SeqRecord (id=%s) has None for its sequence." 121 % record.id) 122 elif not isinstance(record.seq, (Seq, MutableSeq)): 123 raise TypeError("SeqRecord (id=%s) has an invalid sequence." 124 % record.id) 125 return str(record.seq)
126
127 - def clean(self, text):
128 """Use this to avoid getting newlines in the output.""" 129 return text.replace("\n", " ").replace("\r", " ").replace(" ", " ")
130
131 - def write_file(self, records):
132 """Use this to write an entire file containing the given records. 133 134 records - A list or iterator returning SeqRecord objects 135 136 Should return the number of records (as an integer). 137 138 This method can only be called once. 139 """ 140 # Note when implementing this, your writer class should NOT close the 141 # file at the end, but the calling code should. 142 raise NotImplementedError("This object should be subclassed")
143 ##################################################### 144 # You SHOULD subclass this # 145 ##################################################### 146 147
148 -class SequentialSequenceWriter(SequenceWriter):
149 """Base class for sequence writers. This class should be subclassed. 150 151 It is intended for sequential file formats with an (optional) 152 header, repeated records, and an (optional) footer. 153 154 In this case (as with interlaced file formats), the user may 155 simply call the write_file() method and be done. 156 157 However, they may also call the write_header(), followed 158 by multiple calls to write_record() and/or write_records() 159 followed finally by write_footer(). 160 161 Users must call write_header() and write_footer() even when 162 the file format concerned doesn't have a header or footer. 163 This is to try and make life as easy as possible when 164 switching the output format. 165 166 Note that write_header() cannot require any assumptions about 167 the number of records. 168 """ 169
170 - def __init__(self, handle):
171 """Initialize the class.""" 172 self.handle = handle 173 self._header_written = False 174 self._record_written = False 175 self._footer_written = False
176
177 - def write_header(self):
178 assert not self._header_written, "You have aleady called write_header()" 179 assert not self._record_written, "You have aleady called write_record() or write_records()" 180 assert not self._footer_written, "You have aleady called write_footer()" 181 self._header_written = True
182 188
189 - def write_record(self, record):
190 """Write a single record to the output file. 191 192 record - a SeqRecord object 193 194 Once you have called write_header() you can call write_record() 195 and/or write_records() as many times as needed. Then call 196 write_footer() and close(). 197 """ 198 assert self._header_written, "You must call write_header() first" 199 assert not self._footer_written, "You have already called write_footer()" 200 self._record_written = True 201 raise NotImplementedError("This object should be subclassed")
202 ##################################################### 203 # You SHOULD subclass this # 204 ##################################################### 205
206 - def write_records(self, records):
207 """Write multiple record to the output file. 208 209 records - A list or iterator returning SeqRecord objects 210 211 Once you have called write_header() you can call write_record() 212 and/or write_records() as many times as needed. Then call 213 write_footer() and close(). 214 215 Returns the number of records written. 216 """ 217 # Default implementation: 218 assert self._header_written, "You must call write_header() first" 219 assert not self._footer_written, "You have already called write_footer()" 220 count = 0 221 for record in records: 222 self.write_record(record) 223 count += 1 224 # Mark as true, even if there where no records 225 self._record_written = True 226 return count
227
228 - def write_file(self, records):
229 """Use this to write an entire file containing the given records. 230 231 records - A list or iterator returning SeqRecord objects 232 233 This method can only be called once. Returns the number of records 234 written. 235 """ 236 self.write_header() 237 count = self.write_records(records) 238 self.write_footer() 239 return count
240