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