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