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