Back to index

python-biopython  1.60
__init__.py
Go to the documentation of this file.
00001 # Copyright 2006-2010 by Peter Cock.  All rights reserved.
00002 # This code is part of the Biopython distribution and governed by its
00003 # license.  Please see the LICENSE file that should have been included
00004 # as part of this package.
00005 #
00006 #Nice link:
00007 # http://www.ebi.ac.uk/help/formats_frame.html
00008 
00009 """Sequence input/output as SeqRecord objects.
00010 
00011 Bio.SeqIO is also documented at U{http://biopython.org/wiki/SeqIO} and by
00012 a whole chapter in our tutorial:
00013  - U{http://biopython.org/DIST/docs/tutorial/Tutorial.html}
00014  - U{http://biopython.org/DIST/docs/tutorial/Tutorial.pdf}
00015 
00016 Input
00017 =====
00018 The main function is Bio.SeqIO.parse(...) which takes an input file handle
00019 (or in recent versions of Biopython alternatively a filename as a string),
00020 and format string.  This returns an iterator giving SeqRecord objects:
00021 
00022     >>> from Bio import SeqIO
00023     >>> for record in SeqIO.parse("Fasta/f002", "fasta"):
00024     ...     print record.id, len(record)
00025     gi|1348912|gb|G26680|G26680 633
00026     gi|1348917|gb|G26685|G26685 413
00027     gi|1592936|gb|G29385|G29385 471
00028 
00029 Note that the parse() function will invoke the relevant parser for the
00030 format with its default settings.  You may want more control, in which case
00031 you need to create a format specific sequence iterator directly.
00032 
00033 Input - Single Records
00034 ======================
00035 If you expect your file to contain one-and-only-one record, then we provide
00036 the following 'helper' function which will return a single SeqRecord, or
00037 raise an exception if there are no records or more than one record:
00038 
00039     >>> from Bio import SeqIO
00040     >>> record = SeqIO.read("Fasta/f001", "fasta")
00041     >>> print record.id, len(record)
00042     gi|3318709|pdb|1A91| 79
00043 
00044 This style is useful when you expect a single record only (and would
00045 consider multiple records an error).  For example, when dealing with GenBank
00046 files for bacterial genomes or chromosomes, there is normally only a single
00047 record.  Alternatively, use this with a handle when downloading a single
00048 record from the internet.
00049 
00050 However, if you just want the first record from a file containing multiple
00051 record, use the iterator's next() method:
00052 
00053     >>> from Bio import SeqIO
00054     >>> record = SeqIO.parse("Fasta/f002", "fasta").next()
00055     >>> print record.id, len(record)
00056     gi|1348912|gb|G26680|G26680 633
00057 
00058 The above code will work as long as the file contains at least one record.
00059 Note that if there is more than one record, the remaining records will be
00060 silently ignored.
00061 
00062 
00063 Input - Multiple Records
00064 ========================
00065 For non-interlaced files (e.g. Fasta, GenBank, EMBL) with multiple records
00066 using a sequence iterator can save you a lot of memory (RAM).  There is
00067 less benefit for interlaced file formats (e.g. most multiple alignment file
00068 formats).  However, an iterator only lets you access the records one by one.
00069 
00070 If you want random access to the records by number, turn this into a list:
00071 
00072     >>> from Bio import SeqIO
00073     >>> records = list(SeqIO.parse("Fasta/f002", "fasta"))
00074     >>> len(records)
00075     3
00076     >>> print records[1].id
00077     gi|1348917|gb|G26685|G26685
00078 
00079 If you want random access to the records by a key such as the record id,
00080 turn the iterator into a dictionary:
00081 
00082     >>> from Bio import SeqIO
00083     >>> record_dict = SeqIO.to_dict(SeqIO.parse("Fasta/f002", "fasta"))
00084     >>> len(record_dict)
00085     3
00086     >>> print len(record_dict["gi|1348917|gb|G26685|G26685"])
00087     413
00088 
00089 However, using list() or the to_dict() function will load all the records
00090 into memory at once, and therefore is not possible on very large files.
00091 Instead, for *some* file formats Bio.SeqIO provides an indexing approach
00092 providing dictionary like access to any record. For example,
00093 
00094     >>> from Bio import SeqIO
00095     >>> record_dict = SeqIO.index("Fasta/f002", "fasta")
00096     >>> len(record_dict)
00097     3
00098     >>> print len(record_dict["gi|1348917|gb|G26685|G26685"])
00099     413
00100 
00101 Many but not all of the supported input file formats can be indexed like
00102 this. For example "fasta", "fastq", "qual" and even the binary format "sff"
00103 work, but alignment formats like "phylip", "clustalw" and "nexus" will not.
00104 
00105 In most cases you can also use SeqIO.index to get the record from the file
00106 as a raw string (not a SeqRecord). This can be useful for example to extract
00107 a sub-set of records from a file where SeqIO cannot output the file format
00108 (e.g. the plain text SwissProt format, "swiss") or where it is important to
00109 keep the output 100% identical to the input). For example,
00110 
00111     >>> from Bio import SeqIO
00112     >>> record_dict = SeqIO.index("Fasta/f002", "fasta")
00113     >>> len(record_dict)
00114     3
00115     >>> print record_dict.get_raw("gi|1348917|gb|G26685|G26685").decode()
00116     >gi|1348917|gb|G26685|G26685 human STS STS_D11734.
00117     CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATCTTACTCTTTC
00118     ATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTTTACAGATGTGAAACTTTCAA
00119     GAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAAACCTGATGCTTTTATAAGCCATTGTGATTA
00120     GGATGACTGTTACAGGCTTAGCTTTGTGTGAAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGT
00121     TCATATTACTNTAAGTTCTATAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGG
00122     AATTGNTTTGCCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA
00123     <BLANKLINE>
00124     >>> print record_dict["gi|1348917|gb|G26685|G26685"].format("fasta")
00125     >gi|1348917|gb|G26685|G26685 human STS STS_D11734.
00126     CGGAGCCAGCGAGCATATGCTGCATGAGGACCTTTCTATCTTACATTATGGCTGGGAATC
00127     TTACTCTTTCATCTGATACCTTGTTCAGATTTCAAAATAGTTGTAGCCTTATCCTGGTTT
00128     TACAGATGTGAAACTTTCAAGAGATTTACTGACTTTCCTAGAATAGTTTCTCTACTGGAA
00129     ACCTGATGCTTTTATAAGCCATTGTGATTAGGATGACTGTTACAGGCTTAGCTTTGTGTG
00130     AAANCCAGTCACCTTTCTCCTAGGTAATGAGTAGTGCTGTTCATATTACTNTAAGTTCTA
00131     TAGCATACTTGCNATCCTTTANCCATGCTTATCATANGTACCATTTGAGGAATTGNTTTG
00132     CCCTTTTGGGTTTNTTNTTGGTAAANNNTTCCCGGGTGGGGGNGGTNNNGAAA
00133     <BLANKLINE>
00134 
00135 Here the original file and what Biopython would output differ in the line
00136 wrapping. Also note that under Python 3, the get_raw method will return a
00137 bytes string, hence the use of decode to turn it into a (unicode) string.
00138 This is uncessary on Python 2.
00139 
00140 
00141 Input - Alignments
00142 ==================
00143 You can read in alignment files as alignment objects using Bio.AlignIO.
00144 Alternatively, reading in an alignment file format via Bio.SeqIO will give
00145 you a SeqRecord for each row of each alignment:
00146 
00147     >>> from Bio import SeqIO
00148     >>> for record in SeqIO.parse("Clustalw/hedgehog.aln", "clustal"):
00149     ...     print record.id, len(record)
00150     gi|167877390|gb|EDS40773.1| 447
00151     gi|167234445|ref|NP_001107837. 447
00152     gi|74100009|gb|AAZ99217.1| 447
00153     gi|13990994|dbj|BAA33523.2| 447
00154     gi|56122354|gb|AAV74328.1| 447
00155 
00156 Output
00157 ======
00158 Use the function Bio.SeqIO.write(...), which takes a complete set of
00159 SeqRecord objects (either as a list, or an iterator), an output file handle
00160 (or in recent versions of Biopython an output filename as a string) and of
00161 course the file format::
00162 
00163     from Bio import SeqIO
00164     records = ...
00165     SeqIO.write(records, "example.faa", "fasta")
00166 
00167 Or, using a handle::
00168 
00169     from Bio import SeqIO
00170     records = ...
00171     handle = open("example.faa", "w")
00172     SeqIO.write(records, handle, "fasta")
00173     handle.close()
00174 
00175 You are expected to call this function once (with all your records) and if
00176 using a handle, make sure you close it to flush the data to the hard disk.
00177 
00178 
00179 Output - Advanced
00180 =================
00181 The effect of calling write() multiple times on a single file will vary
00182 depending on the file format, and is best avoided unless you have a strong
00183 reason to do so.
00184 
00185 If you give a filename, then each time you call write() the existing file
00186 will be overwriten. For sequential files formats (e.g. fasta, genbank) each
00187 "record block" holds a single sequence.  For these files it would probably
00188 be safe to call write() multiple times by re-using the same handle.
00189 
00190 
00191 However, trying this for certain alignment formats (e.g. phylip, clustal,
00192 stockholm) would have the effect of concatenating several multiple sequence
00193 alignments together.  Such files are created by the PHYLIP suite of programs
00194 for bootstrap analysis, but it is clearer to do this via Bio.AlignIO instead.
00195 
00196 
00197 Conversion
00198 ==========
00199 The Bio.SeqIO.convert(...) function allows an easy interface for simple
00200 file format conversions. Additionally, it may use file format specific
00201 optimisations so this should be the fastest way too.
00202 
00203 In general however, you can combine the Bio.SeqIO.parse(...) function with
00204 the Bio.SeqIO.write(...) function for sequence file conversion. Using
00205 generator expressions or generator functions provides a memory efficient way
00206 to perform filtering or other extra operations as part of the process.
00207 
00208 
00209 File Formats
00210 ============
00211 When specifying the file format, use lowercase strings.  The same format
00212 names are also used in Bio.AlignIO and include the following:
00213 
00214  - abif    - Applied Biosystem's sequencing trace format
00215  - ace     - Reads the contig sequences from an ACE assembly file.
00216  - embl    - The EMBL flat file format. Uses Bio.GenBank internally.
00217  - fasta   - The generic sequence file format where each record starts with
00218              an identifer line starting with a ">" character, followed by
00219              lines of sequence.
00220  - fastq   - A "FASTA like" format used by Sanger which also stores PHRED
00221              sequence quality values (with an ASCII offset of 33).
00222  - fastq-sanger - An alias for "fastq" for consistency with BioPerl and EMBOSS
00223  - fastq-solexa - Original Solexa/Illumnia variant of the FASTQ format which
00224              encodes Solexa quality scores (not PHRED quality scores) with an
00225              ASCII offset of 64.
00226  - fastq-illumina - Solexa/Illumina 1.3 to 1.7 variant of the FASTQ format
00227              which encodes PHRED quality scores with an ASCII offset of 64
00228              (not 33). Note as of version 1.8 of the CASAVA pipeline Illumina
00229              will produce FASTQ files using the standard Sanger encoding.
00230  - genbank - The GenBank or GenPept flat file format.
00231  - gb      - An alias for "genbank", for consistency with NCBI Entrez Utilities
00232  - ig      - The IntelliGenetics file format, apparently the same as the
00233              MASE alignment format.
00234  - imgt    - An EMBL like format from IMGT where the feature tables are more
00235              indented to allow for longer feature types.
00236  - phd     - Output from PHRED, used by PHRAP and CONSED for input.
00237  - pir     - A "FASTA like" format introduced by the National Biomedical
00238              Research Foundation (NBRF) for the Protein Information Resource
00239              (PIR) database, now part of UniProt.
00240  - seqxml  - SeqXML, simple XML format described in Schmitt et al (2011).
00241  - sff     - Standard Flowgram Format (SFF), typical output from Roche 454.
00242  - sff-trim - Standard Flowgram Format (SFF) with given trimming applied.
00243  - swiss   - Plain text Swiss-Prot aka UniProt format.
00244  - tab     - Simple two column tab separated sequence files, where each
00245              line holds a record's identifier and sequence. For example,
00246              this is used as by Aligent's eArray software when saving
00247              microarray probes in a minimal tab delimited text file.
00248  - qual    - A "FASTA like" format holding PHRED quality values from
00249              sequencing DNA, but no actual sequences (usually provided
00250              in separate FASTA files).
00251  - uniprot-xml - The UniProt XML format (replacement for the SwissProt plain
00252              text format which we call "swiss")
00253 
00254 Note that while Bio.SeqIO can read all the above file formats, it cannot
00255 write to all of them.
00256 
00257 You can also use any file format supported by Bio.AlignIO, such as "nexus",
00258 "phlip" and "stockholm", which gives you access to the individual sequences
00259 making up each alignment as SeqRecords.
00260 """
00261 
00262 # For using with statement in Python 2.5 or Jython
00263 from __future__ import with_statement
00264 
00265 __docformat__ = "epytext en" #not just plaintext
00266 
00267 #TODO
00268 # - define policy on reading aligned sequences with gaps in
00269 #   (e.g. - and . characters) including how the alphabet interacts
00270 #
00271 # - How best to handle unique/non unique record.id when writing.
00272 #   For most file formats reading such files is fine; The stockholm
00273 #   parser would fail.
00274 #
00275 # - MSF multiple alignment format, aka GCG, aka PileUp format (*.msf)
00276 #   http://www.bioperl.org/wiki/MSF_multiple_alignment_format
00277 
00278 """
00279 FAO BioPython Developers
00280 ========================
00281 The way I envision this SeqIO system working as that for any sequence file
00282 format we have an iterator that returns SeqRecord objects.
00283 
00284 This also applies to interlaced fileformats (like clustal - although that
00285 is now handled via Bio.AlignIO instead) where the file cannot be read record
00286 by record.  You should still return an iterator, even if the implementation
00287 could just as easily return a list.
00288 
00289 These file format specific sequence iterators may be implemented as:
00290 * Classes which take a handle for __init__ and provide the __iter__ method
00291 * Functions that take a handle, and return an iterator object
00292 * Generator functions that take a handle, and yield SeqRecord objects
00293 
00294 It is then trivial to turn this iterator into a list of SeqRecord objects,
00295 an in memory dictionary, or a multiple sequence alignment object.
00296 
00297 For building the dictionary by default the id propery of each SeqRecord is
00298 used as the key.  You should always populate the id property, and it should
00299 be unique in most cases. For some file formats the accession number is a good
00300 choice.  If the file itself contains ambiguous identifiers, don't try and
00301 dis-ambiguate them - return them as is.
00302 
00303 When adding a new file format, please use the same lower case format name
00304 as BioPerl, or if they have not defined one, try the names used by EMBOSS.
00305 
00306 See also http://biopython.org/wiki/SeqIO_dev
00307 
00308 --Peter
00309 """
00310 
00311 
00312 from Bio.File import as_handle
00313 from Bio.SeqRecord import SeqRecord
00314 from Bio.Align import MultipleSeqAlignment
00315 from Bio.Alphabet import Alphabet, AlphabetEncoder, _get_base_alphabet
00316 
00317 import AbiIO
00318 import AceIO
00319 import FastaIO
00320 import IgIO #IntelliGenetics or MASE format
00321 import InsdcIO #EMBL and GenBank
00322 import PhdIO
00323 import PirIO
00324 import SeqXmlIO
00325 import SffIO
00326 import SwissIO
00327 import TabIO
00328 import QualityIO #FastQ and qual files
00329 import UniprotIO
00330 
00331 
00332 #Convention for format names is "mainname-subtype" in lower case.
00333 #Please use the same names as BioPerl or EMBOSS where possible.
00334 #
00335 #Note that this simple system copes with defining
00336 #multiple possible iterators for a given format/extension
00337 #with the -subtype suffix
00338 #
00339 #Most alignment file formats will be handled via Bio.AlignIO
00340 
00341 _FormatToIterator = {"fasta" : FastaIO.FastaIterator,
00342                      "gb" : InsdcIO.GenBankIterator,
00343                      "genbank" : InsdcIO.GenBankIterator,
00344                      "genbank-cds" : InsdcIO.GenBankCdsFeatureIterator,
00345                      "embl" : InsdcIO.EmblIterator,
00346                      "embl-cds" : InsdcIO.EmblCdsFeatureIterator,
00347                      "imgt" : InsdcIO.ImgtIterator,
00348                      "ig" : IgIO.IgIterator,
00349                      "swiss" : SwissIO.SwissIterator,
00350                      "phd" : PhdIO.PhdIterator,
00351                      "ace" : AceIO.AceIterator,
00352                      "tab" : TabIO.TabIterator,
00353                      "pir" : PirIO.PirIterator,
00354                      "fastq" : QualityIO.FastqPhredIterator,
00355                      "fastq-sanger" : QualityIO.FastqPhredIterator,
00356                      "fastq-solexa" : QualityIO.FastqSolexaIterator,
00357                      "fastq-illumina" : QualityIO.FastqIlluminaIterator,
00358                      "qual" : QualityIO.QualPhredIterator,
00359                      "sff": SffIO.SffIterator,
00360                      #Not sure about this in the long run:
00361                      "sff-trim": SffIO._SffTrimIterator,
00362                      "uniprot-xml": UniprotIO.UniprotIterator,
00363                      "seqxml" : SeqXmlIO.SeqXmlIterator,
00364                      "abi": AbiIO.AbiIterator,
00365                      "abi-trim": AbiIO._AbiTrimIterator,
00366                      }
00367 
00368 _FormatToWriter = {"fasta" : FastaIO.FastaWriter,
00369                    "gb" : InsdcIO.GenBankWriter,
00370                    "genbank" : InsdcIO.GenBankWriter,
00371                    "embl" : InsdcIO.EmblWriter,
00372                    "imgt" : InsdcIO.ImgtWriter,
00373                    "tab" : TabIO.TabWriter,
00374                    "fastq" : QualityIO.FastqPhredWriter,
00375                    "fastq-sanger" : QualityIO.FastqPhredWriter,
00376                    "fastq-solexa" : QualityIO.FastqSolexaWriter,
00377                    "fastq-illumina" : QualityIO.FastqIlluminaWriter,
00378                    "phd" : PhdIO.PhdWriter,
00379                    "qual" : QualityIO.QualPhredWriter,
00380                    "sff" : SffIO.SffWriter,
00381                    "seqxml" : SeqXmlIO.SeqXmlWriter,
00382                    }
00383 
00384 _BinaryFormats = ["sff", "sff-trim", "abi", "abi-trim"]
00385 
00386 
00387 def write(sequences, handle, format):
00388     """Write complete set of sequences to a file.
00389 
00390      - sequences - A list (or iterator) of SeqRecord objects, or (if using
00391                    Biopython 1.54 or later) a single SeqRecord.
00392      - handle    - File handle object to write to, or filename as string
00393                    (note older versions of Biopython only took a handle).
00394      - format    - lower case string describing the file format to write.
00395 
00396     You should close the handle after calling this function.
00397 
00398     Returns the number of records written (as an integer).
00399     """
00400     from Bio import AlignIO
00401 
00402     #Try and give helpful error messages:
00403     if not isinstance(format, basestring):
00404         raise TypeError("Need a string for the file format (lower case)")
00405     if not format:
00406         raise ValueError("Format required (lower case string)")
00407     if format != format.lower():
00408         raise ValueError("Format string '%s' should be lower case" % format)
00409 
00410     if isinstance(sequences, SeqRecord):
00411         #This raised an exception in order version of Biopython
00412         sequences = [sequences]
00413 
00414     if format in _BinaryFormats:
00415         mode = 'wb'
00416     else:
00417         mode = 'w'
00418 
00419     with as_handle(handle, mode) as fp:
00420         #Map the file format to a writer class
00421         if format in _FormatToWriter:
00422             writer_class = _FormatToWriter[format]
00423             count = writer_class(fp).write_file(sequences)
00424         elif format in AlignIO._FormatToWriter:
00425             #Try and turn all the records into a single alignment,
00426             #and write that using Bio.AlignIO
00427             alignment = MultipleSeqAlignment(sequences)
00428             alignment_count = AlignIO.write([alignment], fp, format)
00429             assert alignment_count == 1, \
00430                     "Internal error - the underlying writer " \
00431                     " should have returned 1, not %s" % repr(alignment_count)
00432             count = len(alignment)
00433             del alignment_count, alignment
00434         elif format in _FormatToIterator or format in AlignIO._FormatToIterator:
00435             raise ValueError("Reading format '%s' is supported, but not writing"
00436                              % format)
00437         else:
00438             raise ValueError("Unknown format '%s'" % format)
00439 
00440         assert isinstance(count, int), "Internal error - the underlying %s " \
00441                "writer should have returned the record count, not %s" \
00442                % (format, repr(count))
00443 
00444     return count
00445 
00446 def parse(handle, format, alphabet=None):
00447     r"""Turns a sequence file into an iterator returning SeqRecords.
00448 
00449      - handle   - handle to the file, or the filename as a string
00450                   (note older verions of Biopython only took a handle).
00451      - format   - lower case string describing the file format.
00452      - alphabet - optional Alphabet object, useful when the sequence type
00453                   cannot be automatically inferred from the file itself
00454                   (e.g. format="fasta" or "tab")
00455 
00456     Typical usage, opening a file to read in, and looping over the record(s):
00457 
00458     >>> from Bio import SeqIO
00459     >>> filename = "Fasta/sweetpea.nu"
00460     >>> for record in SeqIO.parse(filename, "fasta"):
00461     ...    print "ID", record.id
00462     ...    print "Sequence length", len(record)
00463     ...    print "Sequence alphabet", record.seq.alphabet
00464     ID gi|3176602|gb|U78617.1|LOU78617
00465     Sequence length 309
00466     Sequence alphabet SingleLetterAlphabet()
00467 
00468     For file formats like FASTA where the alphabet cannot be determined, it
00469     may be useful to specify the alphabet explicitly:
00470 
00471     >>> from Bio import SeqIO
00472     >>> from Bio.Alphabet import generic_dna
00473     >>> filename = "Fasta/sweetpea.nu"
00474     >>> for record in SeqIO.parse(filename, "fasta", generic_dna):
00475     ...    print "ID", record.id
00476     ...    print "Sequence length", len(record)
00477     ...    print "Sequence alphabet", record.seq.alphabet
00478     ID gi|3176602|gb|U78617.1|LOU78617
00479     Sequence length 309
00480     Sequence alphabet DNAAlphabet()
00481 
00482     If you have a string 'data' containing the file contents, you must
00483     first turn this into a handle in order to parse it:
00484 
00485     >>> data = ">Alpha\nACCGGATGTA\n>Beta\nAGGCTCGGTTA\n"
00486     >>> from Bio import SeqIO
00487     >>> from StringIO import StringIO
00488     >>> for record in SeqIO.parse(StringIO(data), "fasta"):
00489     ...     print record.id, record.seq
00490     Alpha ACCGGATGTA
00491     Beta AGGCTCGGTTA
00492 
00493     Use the Bio.SeqIO.read(...) function when you expect a single record
00494     only.
00495     """
00496     #NOTE - The above docstring has some raw \n characters needed
00497     #for the StringIO example, hense the whole docstring is in raw
00498     #string mode (see the leading r before the opening quote).
00499     from Bio import AlignIO
00500 
00501     #Hack for SFF, will need to make this more general in future
00502     if format in _BinaryFormats :
00503         mode = 'rb'
00504     else:
00505         mode = 'rU'
00506 
00507     #Try and give helpful error messages:
00508     if not isinstance(format, basestring):
00509         raise TypeError("Need a string for the file format (lower case)")
00510     if not format:
00511         raise ValueError("Format required (lower case string)")
00512     if format != format.lower():
00513         raise ValueError("Format string '%s' should be lower case" % format)
00514     if alphabet is not None and not (isinstance(alphabet, Alphabet) or \
00515                                      isinstance(alphabet, AlphabetEncoder)):
00516         raise ValueError("Invalid alphabet, %s" % repr(alphabet))
00517 
00518     with as_handle(handle, mode) as fp:
00519         #Map the file format to a sequence iterator:
00520         if format in _FormatToIterator:
00521             iterator_generator = _FormatToIterator[format]
00522             if alphabet is None:
00523                 i = iterator_generator(fp)
00524             else:
00525                 try:
00526                     i = iterator_generator(fp, alphabet=alphabet)
00527                 except TypeError:
00528                     i = _force_alphabet(iterator_generator(fp), alphabet)
00529         elif format in AlignIO._FormatToIterator:
00530             #Use Bio.AlignIO to read in the alignments
00531             i = (r for alignment in AlignIO.parse(fp, format,
00532                                                   alphabet=alphabet)
00533                  for r in alignment)
00534         else:
00535             raise ValueError("Unknown format '%s'" % format)
00536         #This imposes some overhead... wait until we drop Python 2.4 to fix it
00537         for r in i:
00538             yield r
00539 
00540 def _force_alphabet(record_iterator, alphabet):
00541     """Iterate over records, over-riding the alphabet (PRIVATE)."""
00542     #Assume the alphabet argument has been pre-validated
00543     given_base_class = _get_base_alphabet(alphabet).__class__
00544     for record in record_iterator:
00545         if isinstance(_get_base_alphabet(record.seq.alphabet),
00546                       given_base_class):
00547             record.seq.alphabet = alphabet
00548             yield record
00549         else:
00550             raise ValueError("Specified alphabet %s clashes with "\
00551                              "that determined from the file, %s" \
00552                              % (repr(alphabet), repr(record.seq.alphabet)))
00553 
00554 def read(handle, format, alphabet=None):
00555     """Turns a sequence file into a single SeqRecord.
00556 
00557      - handle   - handle to the file, or the filename as a string
00558                   (note older verions of Biopython only took a handle).
00559      - format   - string describing the file format.
00560      - alphabet - optional Alphabet object, useful when the sequence type
00561                   cannot be automatically inferred from the file itself
00562                   (e.g. format="fasta" or "tab")
00563 
00564     This function is for use parsing sequence files containing
00565     exactly one record.  For example, reading a GenBank file:
00566 
00567     >>> from Bio import SeqIO
00568     >>> record = SeqIO.read("GenBank/arab1.gb", "genbank")
00569     >>> print "ID", record.id
00570     ID AC007323.5
00571     >>> print "Sequence length", len(record)
00572     Sequence length 86436
00573     >>> print "Sequence alphabet", record.seq.alphabet
00574     Sequence alphabet IUPACAmbiguousDNA()
00575 
00576     If the handle contains no records, or more than one record,
00577     an exception is raised.  For example:
00578 
00579     >>> from Bio import SeqIO
00580     >>> record = SeqIO.read("GenBank/cor6_6.gb", "genbank")
00581     Traceback (most recent call last):
00582         ...
00583     ValueError: More than one record found in handle
00584 
00585     If however you want the first record from a file containing
00586     multiple records this function would raise an exception (as
00587     shown in the example above).  Instead use:
00588 
00589     >>> from Bio import SeqIO
00590     >>> record = SeqIO.parse("GenBank/cor6_6.gb", "genbank").next()
00591     >>> print "First record's ID", record.id
00592     First record's ID X55053.1
00593 
00594     Use the Bio.SeqIO.parse(handle, format) function if you want
00595     to read multiple records from the handle.
00596     """
00597     iterator = parse(handle, format, alphabet)
00598     try:
00599         first = iterator.next()
00600     except StopIteration:
00601         first = None
00602     if first is None:
00603         raise ValueError("No records found in handle")
00604     try:
00605         second = iterator.next()
00606     except StopIteration:
00607         second = None
00608     if second is not None:
00609         raise ValueError("More than one record found in handle")
00610     return first
00611 
00612 def to_dict(sequences, key_function=None):
00613     """Turns a sequence iterator or list into a dictionary.
00614 
00615      - sequences  - An iterator that returns SeqRecord objects,
00616                     or simply a list of SeqRecord objects.
00617      - key_function - Optional callback function which when given a
00618                     SeqRecord should return a unique key for the dictionary.
00619 
00620     e.g. key_function = lambda rec : rec.name
00621     or,  key_function = lambda rec : rec.description.split()[0]
00622 
00623     If key_function is ommitted then record.id is used, on the assumption
00624     that the records objects returned are SeqRecords with a unique id.
00625 
00626     If there are duplicate keys, an error is raised.
00627 
00628     Example usage, defaulting to using the record.id as key:
00629 
00630     >>> from Bio import SeqIO
00631     >>> filename = "GenBank/cor6_6.gb"
00632     >>> format = "genbank"
00633     >>> id_dict = SeqIO.to_dict(SeqIO.parse(filename, format))
00634     >>> print sorted(id_dict)
00635     ['AF297471.1', 'AJ237582.1', 'L31939.1', 'M81224.1', 'X55053.1', 'X62281.1']
00636     >>> print id_dict["L31939.1"].description
00637     Brassica rapa (clone bif72) kin mRNA, complete cds.
00638 
00639     A more complex example, using the key_function argument in order to
00640     use a sequence checksum as the dictionary key:
00641 
00642     >>> from Bio import SeqIO
00643     >>> from Bio.SeqUtils.CheckSum import seguid
00644     >>> filename = "GenBank/cor6_6.gb"
00645     >>> format = "genbank"
00646     >>> seguid_dict = SeqIO.to_dict(SeqIO.parse(filename, format),
00647     ...               key_function = lambda rec : seguid(rec.seq))
00648     >>> for key, record in sorted(seguid_dict.iteritems()):
00649     ...     print key, record.id
00650     /wQvmrl87QWcm9llO4/efg23Vgg AJ237582.1
00651     BUg6YxXSKWEcFFH0L08JzaLGhQs L31939.1
00652     SabZaA4V2eLE9/2Fm5FnyYy07J4 X55053.1
00653     TtWsXo45S3ZclIBy4X/WJc39+CY M81224.1
00654     l7gjJFE6W/S1jJn5+1ASrUKW/FA X62281.1
00655     uVEYeAQSV5EDQOnFoeMmVea+Oow AF297471.1
00656 
00657     This approach is not suitable for very large sets of sequences, as all
00658     the SeqRecord objects are held in memory. Instead, consider using the
00659     Bio.SeqIO.index() function (if it supports your particular file format).
00660     """
00661     if key_function is None:
00662         key_function = lambda rec : rec.id
00663 
00664     d = dict()
00665     for record in sequences:
00666         key = key_function(record)
00667         if key in d:
00668             raise ValueError("Duplicate key '%s'" % key)
00669         d[key] = record
00670     return d
00671 
00672 def index(filename, format, alphabet=None, key_function=None):
00673     """Indexes a sequence file and returns a dictionary like object.
00674 
00675      - filename - string giving name of file to be indexed
00676      - format   - lower case string describing the file format
00677      - alphabet - optional Alphabet object, useful when the sequence type
00678                   cannot be automatically inferred from the file itself
00679                   (e.g. format="fasta" or "tab")
00680      - key_function - Optional callback function which when given a
00681                   SeqRecord identifier string should return a unique
00682                   key for the dictionary.
00683 
00684     This indexing function will return a dictionary like object, giving the
00685     SeqRecord objects as values:
00686 
00687     >>> from Bio import SeqIO
00688     >>> records = SeqIO.index("Quality/example.fastq", "fastq")
00689     >>> len(records)
00690     3
00691     >>> sorted(records)
00692     ['EAS54_6_R1_2_1_413_324', 'EAS54_6_R1_2_1_443_348', 'EAS54_6_R1_2_1_540_792']
00693     >>> print records["EAS54_6_R1_2_1_540_792"].format("fasta")
00694     >EAS54_6_R1_2_1_540_792
00695     TTGGCAGGCCAAGGCCGATGGATCA
00696     <BLANKLINE>
00697     >>> "EAS54_6_R1_2_1_540_792" in records
00698     True
00699     >>> print records.get("Missing", None)
00700     None
00701 
00702     If the file is BGZF compressed, this is detected automatically. Ordinary
00703     GZIP files are not supported:
00704 
00705     >>> from Bio import SeqIO
00706     >>> records = SeqIO.index("Quality/example.fastq.bgz", "fastq")
00707     >>> len(records)
00708     3
00709     >>> print records["EAS54_6_R1_2_1_540_792"].seq
00710     TTGGCAGGCCAAGGCCGATGGATCA
00711 
00712     Note that this psuedo dictionary will not support all the methods of a
00713     true Python dictionary, for example values() is not defined since this
00714     would require loading all of the records into memory at once.
00715 
00716     When you call the index function, it will scan through the file, noting
00717     the location of each record. When you access a particular record via the
00718     dictionary methods, the code will jump to the appropriate part of the
00719     file and then parse that section into a SeqRecord.
00720 
00721     Note that not all the input formats supported by Bio.SeqIO can be used
00722     with this index function. It is designed to work only with sequential
00723     file formats (e.g. "fasta", "gb", "fastq") and is not suitable for any
00724     interlaced file format (e.g. alignment formats such as "clustal").
00725 
00726     For small files, it may be more efficient to use an in memory Python
00727     dictionary, e.g.
00728 
00729     >>> from Bio import SeqIO
00730     >>> records = SeqIO.to_dict(SeqIO.parse(open("Quality/example.fastq"), "fastq"))
00731     >>> len(records)
00732     3
00733     >>> sorted(records)
00734     ['EAS54_6_R1_2_1_413_324', 'EAS54_6_R1_2_1_443_348', 'EAS54_6_R1_2_1_540_792']
00735     >>> print records["EAS54_6_R1_2_1_540_792"].format("fasta")
00736     >EAS54_6_R1_2_1_540_792
00737     TTGGCAGGCCAAGGCCGATGGATCA
00738     <BLANKLINE>
00739 
00740     As with the to_dict() function, by default the id string of each record
00741     is used as the key. You can specify a callback function to transform
00742     this (the record identifier string) into your prefered key. For example:
00743 
00744     >>> from Bio import SeqIO
00745     >>> def make_tuple(identifier):
00746     ...     parts = identifier.split("_")
00747     ...     return int(parts[-2]), int(parts[-1])
00748     >>> records = SeqIO.index("Quality/example.fastq", "fastq",
00749     ...                       key_function=make_tuple)
00750     >>> len(records)
00751     3
00752     >>> sorted(records)
00753     [(413, 324), (443, 348), (540, 792)]
00754     >>> print records[(540, 792)].format("fasta")
00755     >EAS54_6_R1_2_1_540_792
00756     TTGGCAGGCCAAGGCCGATGGATCA
00757     <BLANKLINE>
00758     >>> (540, 792) in records
00759     True
00760     >>> "EAS54_6_R1_2_1_540_792" in records
00761     False
00762     >>> print records.get("Missing", None)
00763     None
00764 
00765     Another common use case would be indexing an NCBI style FASTA file,
00766     where you might want to extract the GI number from the FASTA identifer
00767     to use as the dictionary key.
00768 
00769     Notice that unlike the to_dict() function, here the key_function does
00770     not get given the full SeqRecord to use to generate the key. Doing so
00771     would impose a severe performance penalty as it would require the file
00772     to be completely parsed while building the index. Right now this is
00773     usually avoided.
00774 
00775     See also: Bio.SeqIO.index_db() and Bio.SeqIO.to_dict()
00776     """
00777     #Try and give helpful error messages:
00778     if not isinstance(filename, basestring):
00779         raise TypeError("Need a filename (not a handle)")
00780     if not isinstance(format, basestring):
00781         raise TypeError("Need a string for the file format (lower case)")
00782     if not format:
00783         raise ValueError("Format required (lower case string)")
00784     if format != format.lower():
00785         raise ValueError("Format string '%s' should be lower case" % format)
00786     if alphabet is not None and not (isinstance(alphabet, Alphabet) or \
00787                                      isinstance(alphabet, AlphabetEncoder)):
00788         raise ValueError("Invalid alphabet, %s" % repr(alphabet))
00789 
00790     #Map the file format to a sequence iterator:
00791     import _index #Lazy import
00792     return _index._IndexedSeqFileDict(filename, format, alphabet, key_function)
00793 
00794 def index_db(index_filename, filenames=None, format=None, alphabet=None,
00795                key_function=None):
00796     """Index several sequence files and return a dictionary like object.
00797 
00798     The index is stored in an SQLite database rather than in memory (as in the
00799     Bio.SeqIO.index(...) function).
00800 
00801      - index_filename - Where to store the SQLite index
00802      - filenames - list of strings specifying file(s) to be indexed, or when
00803                   indexing a single file this can be given as a string.
00804                   (optional if reloading an existing index, but must match)
00805      - format   - lower case string describing the file format
00806                   (optional if reloading an existing index, but must match)
00807      - alphabet - optional Alphabet object, useful when the sequence type
00808                   cannot be automatically inferred from the file itself
00809                   (e.g. format="fasta" or "tab")
00810      - key_function - Optional callback function which when given a
00811                   SeqRecord identifier string should return a unique
00812                   key for the dictionary.
00813 
00814     This indexing function will return a dictionary like object, giving the
00815     SeqRecord objects as values:
00816 
00817     >>> from Bio.Alphabet import generic_protein
00818     >>> from Bio import SeqIO
00819     >>> files = ["GenBank/NC_000932.faa", "GenBank/NC_005816.faa"]
00820     >>> def get_gi(name):
00821     ...     parts = name.split("|")
00822     ...     i = parts.index("gi")
00823     ...     assert i != -1
00824     ...     return parts[i+1]
00825     >>> idx_name = ":memory:" #use an in memory SQLite DB for this test
00826     >>> records = SeqIO.index_db(idx_name, files, "fasta", generic_protein, get_gi)
00827     >>> len(records)
00828     95
00829     >>> records["7525076"].description
00830     'gi|7525076|ref|NP_051101.1| Ycf2 [Arabidopsis thaliana]'
00831     >>> records["45478717"].description
00832     'gi|45478717|ref|NP_995572.1| pesticin [Yersinia pestis biovar Microtus str. 91001]'
00833 
00834     In this example the two files contain 85 and 10 records respectively.
00835 
00836     BGZF compressed files are supported, and detected automatically. Ordinary
00837     GZIP compressed files are not supported.
00838 
00839     See also: Bio.SeqIO.index() and Bio.SeqIO.to_dict()
00840     """
00841     #Try and give helpful error messages:
00842     if not isinstance(index_filename, basestring):
00843         raise TypeError("Need a string for the index filename")
00844     if isinstance(filenames, basestring):
00845         #Make the API a little more friendly, and more similar
00846         #to Bio.SeqIO.index(...) for indexing just one file.
00847         filenames = [filenames]
00848     if filenames is not None and not isinstance(filenames, list):
00849         raise TypeError("Need a list of filenames (as strings), or one filename")
00850     if format is not None and not isinstance(format, basestring):
00851         raise TypeError("Need a string for the file format (lower case)")
00852     if format and format != format.lower():
00853         raise ValueError("Format string '%s' should be lower case" % format)
00854     if alphabet is not None and not (isinstance(alphabet, Alphabet) or \
00855                                      isinstance(alphabet, AlphabetEncoder)):
00856         raise ValueError("Invalid alphabet, %s" % repr(alphabet))
00857 
00858     #Map the file format to a sequence iterator:
00859     import _index #Lazy import
00860     return _index._SQLiteManySeqFilesDict(index_filename, filenames, format,
00861                                           alphabet, key_function)
00862 
00863 
00864 def convert(in_file, in_format, out_file, out_format, alphabet=None):
00865     """Convert between two sequence file formats, return number of records.
00866 
00867      - in_file - an input handle or filename
00868      - in_format - input file format, lower case string
00869      - out_file - an output handle or filename
00870      - out_format - output file format, lower case string
00871      - alphabet - optional alphabet to assume
00872 
00873     NOTE - If you provide an output filename, it will be opened which will
00874     overwrite any existing file without warning. This may happen if even
00875     the conversion is aborted (e.g. an invalid out_format name is given).
00876 
00877     For example, going from a filename to a handle:
00878 
00879     >>> from Bio import SeqIO
00880     >>> from StringIO import StringIO
00881     >>> handle = StringIO("")
00882     >>> SeqIO.convert("Quality/example.fastq", "fastq", handle, "fasta")
00883     3
00884     >>> print handle.getvalue()
00885     >EAS54_6_R1_2_1_413_324
00886     CCCTTCTTGTCTTCAGCGTTTCTCC
00887     >EAS54_6_R1_2_1_540_792
00888     TTGGCAGGCCAAGGCCGATGGATCA
00889     >EAS54_6_R1_2_1_443_348
00890     GTTGCTTCTGGCGTGGGTGGGGGGG
00891     <BLANKLINE>
00892     """
00893     #Hack for SFF, will need to make this more general in future
00894     if in_format in _BinaryFormats :
00895         in_mode = 'rb'
00896     else :
00897         in_mode = 'rU'
00898 
00899     #Don't open the output file until we've checked the input is OK?
00900     if out_format in ["sff", "sff_trim"] :
00901         out_mode = 'wb'
00902     else :
00903         out_mode = 'w'
00904 
00905     #This will check the arguments and issue error messages,
00906     #after we have opened the file which is a shame.
00907     from _convert import _handle_convert #Lazy import
00908     with as_handle(in_file, in_mode) as in_handle:
00909         with as_handle(out_file, out_mode) as out_handle:
00910             count = _handle_convert(in_handle, in_format,
00911                                     out_handle, out_format,
00912                                     alphabet)
00913     return count
00914 
00915 def _test():
00916     """Run the Bio.SeqIO module's doctests.
00917 
00918     This will try and locate the unit tests directory, and run the doctests
00919     from there in order that the relative paths used in the examples work.
00920     """
00921     import doctest
00922     import os
00923     if os.path.isdir(os.path.join("..", "..", "Tests")):
00924         print "Runing doctests..."
00925         cur_dir = os.path.abspath(os.curdir)
00926         os.chdir(os.path.join("..", "..", "Tests"))
00927         doctest.testmod()
00928         os.chdir(cur_dir)
00929         del cur_dir
00930         print "Done"
00931     elif os.path.isdir(os.path.join("Tests", "Fasta")):
00932         print "Runing doctests..."
00933         cur_dir = os.path.abspath(os.curdir)
00934         os.chdir(os.path.join("Tests"))
00935         doctest.testmod()
00936         os.chdir(cur_dir)
00937         del cur_dir
00938         print "Done"
00939 
00940 if __name__ == "__main__":
00941     #Run the doctests
00942     _test()