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