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  __docformat__ = "restructuredtext en" 
 20   
 21   
22 -class SequenceIterator(object):
23 """Base class for building SeqRecord iterators. 24 25 You should write a next() method to return SeqRecord 26 objects. You may wish to redefine the __init__ 27 method as well. 28 """
29 - def __init__(self, handle, alphabet=generic_alphabet):
30 """Create a SequenceIterator object. 31 32 - handle - input file 33 - alphabet - optional, e.g. Bio.Alphabet.generic_protein 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 # You may want to subclass this, for example # 45 # to read through the file to find the first record,# 46 # or if additional arguments are required. # 47 ##################################################### 48
49 - def __next__(self):
50 """Return the next record in the file. 51 52 This method should be replaced by any derived class to do something useful.""" 53 raise NotImplementedError("This object should be subclassed")
54 ##################################################### 55 # You SHOULD subclass this, to split the file up # 56 # into your individual records, and convert these # 57 # into useful objects, e.g. return SeqRecord object # 58 ##################################################### 59 60 if sys.version_info[0] < 3:
61 - def next(self):
62 """Python 2 style alias for Python 3 style __next__ method.""" 63 return self.__next__()
64
65 - def __iter__(self):
66 """Iterate over the entries as a SeqRecord objects. 67 68 Example usage for Fasta files:: 69 70 with open("example.fasta","r") as myFile: 71 myFastaReader = FastaIterator(myFile) 72 for record in myFastaReader: 73 print(record.id) 74 print(record.seq) 75 """ 76 return iter(self.__next__, None)
77 78
79 -class SequenceWriter(object):
80 """This class should be subclassed. 81 82 Interlaced file formats (e.g. Clustal) should subclass directly. 83 84 Sequential file formats (e.g. Fasta, GenBank) should subclass 85 the SequentialSequenceWriter class instead. 86 """
87 - def __init__(self, handle):
88 """Creates the writer object. 89 90 Use the method write_file() to actually record your sequence records.""" 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 # Note when implementing this, your writer class should NOT close the 118 # file at the end, but the calling code should. 119 raise NotImplementedError("This object should be subclassed")
120 ##################################################### 121 # You SHOULD subclass this # 122 ##################################################### 123 124
125 -class SequentialSequenceWriter(SequenceWriter):
126 """This class should be subclassed. 127 128 It is intended for sequential file formats with an (optional) 129 header, repeated records, and an (optional) footer. 130 131 In this case (as with interlaced file formats), the user may 132 simply call the write_file() method and be done. 133 134 However, they may also call the write_header(), followed 135 by multiple calls to write_record() and/or write_records() 136 followed finally by write_footer(). 137 138 Users must call write_header() and write_footer() even when 139 the file format concerned doesn't have a header or footer. 140 This is to try and make life as easy as possible when 141 switching the output format. 142 143 Note that write_header() cannot require any assumptions about 144 the number of records. 145 """
146 - def __init__(self, handle):
147 self.handle = handle 148 self._header_written = False 149 self._record_written = False 150 self._footer_written = False
151
152 - def write_header(self):
153 assert not self._header_written, "You have aleady called write_header()" 154 assert not self._record_written, "You have aleady called write_record() or write_records()" 155 assert not self._footer_written, "You have aleady called write_footer()" 156 self._header_written = True
157 163
164 - def write_record(self, record):
165 """Write a single record to the output file. 166 167 record - a SeqRecord object 168 169 Once you have called write_header() you can call write_record() 170 and/or write_records() as many times as needed. Then call 171 write_footer() and close().""" 172 assert self._header_written, "You must call write_header() first" 173 assert not self._footer_written, "You have already called write_footer()" 174 self._record_written = True 175 raise NotImplementedError("This object should be subclassed")
176 ##################################################### 177 # You SHOULD subclass this # 178 ##################################################### 179
180 - def write_records(self, records):
181 """Write multiple record to the output file. 182 183 records - A list or iterator returning SeqRecord objects 184 185 Once you have called write_header() you can call write_record() 186 and/or write_records() as many times as needed. Then call 187 write_footer() and close(). 188 189 Returns the number of records written. 190 """ 191 # Default implementation: 192 assert self._header_written, "You must call write_header() first" 193 assert not self._footer_written, "You have already called write_footer()" 194 count = 0 195 for record in records: 196 self.write_record(record) 197 count += 1 198 # Mark as true, even if there where no records 199 self._record_written = True 200 return count
201
202 - def write_file(self, records):
203 """Use this to write an entire file containing the given records. 204 205 records - A list or iterator returning SeqRecord objects 206 207 This method can only be called once. Returns the number of records 208 written. 209 """ 210 self.write_header() 211 count = self.write_records(records) 212 self.write_footer() 213 return count
214