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