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

Source Code for Module Bio.SeqIO.Interfaces

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