Package Bio :: Package AlignIO
[hide private]
[frames] | no frames]

Source Code for Package Bio.AlignIO

  1  # Copyright 2008-2016 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   
  6  """Multiple sequence alignment input/output as alignment objects. 
  7   
  8  The Bio.AlignIO interface is deliberately very similar to Bio.SeqIO, and in 
  9  fact the two are connected internally.  Both modules use the same set of file 
 10  format names (lower case strings).  From the user's perspective, you can read 
 11  in a PHYLIP file containing one or more alignments using Bio.AlignIO, or you 
 12  can read in the sequences within these alignmenta using Bio.SeqIO. 
 13   
 14  Bio.AlignIO is also documented at http://biopython.org/wiki/AlignIO and by 
 15  a whole chapter in our tutorial: 
 16   
 17  * `HTML Tutorial`_ 
 18  * `PDF Tutorial`_ 
 19   
 20  .. _`HTML Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.html 
 21  .. _`PDF Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.pdf 
 22   
 23  Input 
 24  ----- 
 25  For the typical special case when your file or handle contains one and only 
 26  one alignment, use the function Bio.AlignIO.read().  This takes an input file 
 27  handle (or in recent versions of Biopython a filename as a string), format 
 28  string and optional number of sequences per alignment.  It will return a single 
 29  MultipleSeqAlignment object (or raise an exception if there isn't just one 
 30  alignment): 
 31   
 32  >>> from Bio import AlignIO 
 33  >>> align = AlignIO.read("Phylip/interlaced.phy", "phylip") 
 34  >>> print(align) 
 35  SingleLetterAlphabet() alignment with 3 rows and 384 columns 
 36  -----MKVILLFVLAVFTVFVSS---------------RGIPPE...I-- CYS1_DICDI 
 37  MAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTL...VAA ALEU_HORVU 
 38  ------MWATLPLLCAGAWLLGV--------PVCGAAELSVNSL...PLV CATH_HUMAN 
 39   
 40  For the general case, when the handle could contain any number of alignments, 
 41  use the function Bio.AlignIO.parse(...) which takes the same arguments, but 
 42  returns an iterator giving MultipleSeqAlignment objects (typically used in a 
 43  for loop). If you want random access to the alignments by number, turn this 
 44  into a list: 
 45   
 46  >>> from Bio import AlignIO 
 47  >>> alignments = list(AlignIO.parse("Emboss/needle.txt", "emboss")) 
 48  >>> print(alignments[2]) 
 49  SingleLetterAlphabet() alignment with 2 rows and 120 columns 
 50  -KILIVDDQYGIRILLNEVFNKEGYQTFQAANGLQALDIVTKER...--- ref_rec 
 51  LHIVVVDDDPGTCVYIESVFAELGHTCKSFVRPEAAEEYILTHP...HKE gi|94967506|receiver 
 52   
 53  Most alignment file formats can be concatenated so as to hold as many 
 54  different multiple sequence alignments as possible.  One common example 
 55  is the output of the tool seqboot in the PHLYIP suite.  Sometimes there 
 56  can be a file header and footer, as seen in the EMBOSS alignment output. 
 57   
 58  Output 
 59  ------ 
 60  Use the function Bio.AlignIO.write(...), which takes a complete set of 
 61  Alignment objects (either as a list, or an iterator), an output file handle 
 62  (or filename in recent versions of Biopython) and of course the file format:: 
 63   
 64    from Bio import AlignIO 
 65    alignments = ... 
 66    count = SeqIO.write(alignments, "example.faa", "fasta") 
 67   
 68  If using a handle make sure to close it to flush the data to the disk:: 
 69   
 70    from Bio import AlignIO 
 71    alignments = ... 
 72    with open("example.faa", "w") as handle: 
 73      count = SeqIO.write(alignments, handle, "fasta") 
 74   
 75  In general, you are expected to call this function once (with all your 
 76  alignments) and then close the file handle.  However, for file formats 
 77  like PHYLIP where multiple alignments are stored sequentially (with no file 
 78  header and footer), then multiple calls to the write function should work as 
 79  expected when using handles. 
 80   
 81  If you are using a filename, the repeated calls to the write functions will 
 82  overwrite the existing file each time. 
 83   
 84  Conversion 
 85  ---------- 
 86  The Bio.AlignIO.convert(...) function allows an easy interface for simple 
 87  alignment file format conversions. Additionally, it may use file format 
 88  specific optimisations so this should be the fastest way too. 
 89   
 90  In general however, you can combine the Bio.AlignIO.parse(...) function with 
 91  the Bio.AlignIO.write(...) function for sequence file conversion. Using 
 92  generator expressions provides a memory efficient way to perform filtering or 
 93  other extra operations as part of the process. 
 94   
 95  File Formats 
 96  ------------ 
 97  When specifying the file format, use lowercase strings.  The same format 
 98  names are also used in Bio.SeqIO and include the following: 
 99   
100    - clustal -   Output from Clustal W or X, see also the module Bio.Clustalw 
101      which can be used to run the command line tool from Biopython. 
102    - emboss    - EMBOSS tools' "pairs" and "simple" alignment formats. 
103    - fasta     - The generic sequence file format where each record starts with 
104      an identifer line starting with a ">" character, followed by 
105      lines of sequence. 
106    - fasta-m10 - For the pairswise alignments output by Bill Pearson's FASTA 
107      tools when used with the -m 10 command line option for machine 
108      readable output. 
109    - ig        - The IntelliGenetics file format, apparently the same as the 
110      MASE alignment format. 
111    - nexus     - Output from NEXUS, see also the module Bio.Nexus which can also 
112      read any phylogenetic trees in these files. 
113    - phylip    - Interlaced PHYLIP, as used by the PHLIP tools. 
114    - phylip-sequential - Sequential PHYLIP. 
115    - phylip-relaxed - PHYLIP like format allowing longer names. 
116    - stockholm - A richly annotated alignment file format used by PFAM. 
117   
118  Note that while Bio.AlignIO can read all the above file formats, it cannot 
119  write to all of them. 
120   
121  You can also use any file format supported by Bio.SeqIO, such as "fasta" or 
122  "ig" (which are listed above), PROVIDED the sequences in your file are all the 
123  same length. 
124  """ 
125   
126   
127  from __future__ import print_function 
128  from Bio._py3k import basestring 
129   
130  # TODO 
131  # - define policy on reading aligned sequences with gaps in 
132  #   (e.g. - and . characters) including how the alphabet interacts 
133  # 
134  # - Can we build the to_alignment(...) functionality 
135  #   into the generic Alignment class instead? 
136  # 
137  # - How best to handle unique/non unique record.id when writing. 
138  #   For most file formats reading such files is fine; The stockholm 
139  #   parser would fail. 
140  # 
141  # - MSF multiple alignment format, aka GCG, aka PileUp format (*.msf) 
142  #   http://www.bioperl.org/wiki/MSF_multiple_alignment_format 
143   
144  from Bio.Align import MultipleSeqAlignment 
145  from Bio.Align.Generic import Alignment 
146  from Bio.Alphabet import Alphabet, AlphabetEncoder, _get_base_alphabet 
147  from Bio.File import as_handle 
148   
149  from . import StockholmIO 
150  from . import ClustalIO 
151  from . import NexusIO 
152  from . import PhylipIO 
153  from . import EmbossIO 
154  from . import FastaIO 
155   
156  # Convention for format names is "mainname-subtype" in lower case. 
157  # Please use the same names as BioPerl and EMBOSS where possible. 
158   
159  _FormatToIterator = {  # "fasta" is done via Bio.SeqIO 
160                       "clustal": ClustalIO.ClustalIterator, 
161                       "emboss": EmbossIO.EmbossIterator, 
162                       "fasta-m10": FastaIO.FastaM10Iterator, 
163                       "nexus": NexusIO.NexusIterator, 
164                       "phylip": PhylipIO.PhylipIterator, 
165                       "phylip-sequential": PhylipIO.SequentialPhylipIterator, 
166                       "phylip-relaxed": PhylipIO.RelaxedPhylipIterator, 
167                       "stockholm": StockholmIO.StockholmIterator, 
168                       } 
169   
170  _FormatToWriter = {  # "fasta" is done via Bio.SeqIO 
171                       # "emboss" : EmbossIO.EmbossWriter, (unfinished) 
172                     "nexus": NexusIO.NexusWriter, 
173                     "phylip": PhylipIO.PhylipWriter, 
174                     "phylip-sequential": PhylipIO.SequentialPhylipWriter, 
175                     "phylip-relaxed": PhylipIO.RelaxedPhylipWriter, 
176                     "stockholm": StockholmIO.StockholmWriter, 
177                     "clustal": ClustalIO.ClustalWriter, 
178                     } 
179   
180   
181 -def write(alignments, handle, format):
182 """Write complete set of alignments to a file. 183 184 Arguments: 185 - alignments - A list (or iterator) of Alignment objects (ideally the 186 new MultipleSeqAlignment objects), or (if using Biopython 187 1.54 or later) a single alignment object. 188 - handle - File handle object to write to, or filename as string 189 (note older versions of Biopython only took a handle). 190 - format - lower case string describing the file format to write. 191 192 You should close the handle after calling this function. 193 194 Returns the number of alignments written (as an integer). 195 """ 196 from Bio import SeqIO 197 198 # Try and give helpful error messages: 199 if not isinstance(format, basestring): 200 raise TypeError("Need a string for the file format (lower case)") 201 if not format: 202 raise ValueError("Format required (lower case string)") 203 if format != format.lower(): 204 raise ValueError("Format string '%s' should be lower case" % format) 205 206 if isinstance(alignments, Alignment): 207 # This raised an exception in older versions of Biopython 208 alignments = [alignments] 209 210 with as_handle(handle, 'w') as fp: 211 # Map the file format to a writer class 212 if format in _FormatToWriter: 213 writer_class = _FormatToWriter[format] 214 count = writer_class(fp).write_file(alignments) 215 elif format in SeqIO._FormatToWriter: 216 # Exploit the existing SeqIO parser to do the dirty work! 217 # TODO - Can we make one call to SeqIO.write() and count the alignments? 218 count = 0 219 for alignment in alignments: 220 if not isinstance(alignment, Alignment): 221 raise TypeError("Expect a list or iterator of Alignment " 222 "objects, got: %r" % alignment) 223 SeqIO.write(alignment, fp, format) 224 count += 1 225 elif format in _FormatToIterator or format in SeqIO._FormatToIterator: 226 raise ValueError("Reading format '%s' is supported, but not writing" 227 % format) 228 else: 229 raise ValueError("Unknown format '%s'" % format) 230 231 assert isinstance(count, int), "Internal error - the underlying %s " \ 232 "writer should have returned the alignment count, not %s" \ 233 % (format, repr(count)) 234 235 return count
236 237 238 # This is a generator function!
239 -def _SeqIO_to_alignment_iterator(handle, format, alphabet=None, seq_count=None):
240 """Uses Bio.SeqIO to create an MultipleSeqAlignment iterator (PRIVATE). 241 242 Arguments: 243 - handle - handle to the file. 244 - format - string describing the file format. 245 - alphabet - optional Alphabet object, useful when the sequence type 246 cannot be automatically inferred from the file itself 247 (e.g. fasta, phylip, clustal) 248 - seq_count - Optional integer, number of sequences expected in each 249 alignment. Recommended for fasta format files. 250 251 If count is omitted (default) then all the sequences in the file are 252 combined into a single MultipleSeqAlignment. 253 """ 254 from Bio import SeqIO 255 assert format in SeqIO._FormatToIterator 256 257 if seq_count: 258 # Use the count to split the records into batches. 259 seq_record_iterator = SeqIO.parse(handle, format, alphabet) 260 261 records = [] 262 for record in seq_record_iterator: 263 records.append(record) 264 if len(records) == seq_count: 265 yield MultipleSeqAlignment(records, alphabet) 266 records = [] 267 if records: 268 raise ValueError("Check seq_count argument, not enough sequences?") 269 else: 270 # Must assume that there is a single alignment using all 271 # the SeqRecord objects: 272 records = list(SeqIO.parse(handle, format, alphabet)) 273 if records: 274 yield MultipleSeqAlignment(records, alphabet)
275 276
277 -def _force_alphabet(alignment_iterator, alphabet):
278 """Iterate over alignments, over-riding the alphabet (PRIVATE).""" 279 # Assume the alphabet argument has been pre-validated 280 given_base_class = _get_base_alphabet(alphabet).__class__ 281 for align in alignment_iterator: 282 if not isinstance(_get_base_alphabet(align._alphabet), 283 given_base_class): 284 raise ValueError("Specified alphabet %s clashes with " 285 "that determined from the file, %s" 286 % (repr(alphabet), repr(align._alphabet))) 287 for record in align: 288 if not isinstance(_get_base_alphabet(record.seq.alphabet), 289 given_base_class): 290 raise ValueError("Specified alphabet %s clashes with " 291 "that determined from the file, %s" 292 % (repr(alphabet), repr(record.seq.alphabet))) 293 record.seq.alphabet = alphabet 294 align._alphabet = alphabet 295 yield align
296 297
298 -def parse(handle, format, seq_count=None, alphabet=None):
299 """Iterate over an alignment file as MultipleSeqAlignment objects. 300 301 Arguments: 302 - handle - handle to the file, or the filename as a string 303 (note older versions of Biopython only took a handle). 304 - format - string describing the file format. 305 - alphabet - optional Alphabet object, useful when the sequence type 306 cannot be automatically inferred from the file itself 307 (e.g. fasta, phylip, clustal) 308 - seq_count - Optional integer, number of sequences expected in each 309 alignment. Recommended for fasta format files. 310 311 If you have the file name in a string 'filename', use: 312 313 >>> from Bio import AlignIO 314 >>> filename = "Emboss/needle.txt" 315 >>> format = "emboss" 316 >>> for alignment in AlignIO.parse(filename, format): 317 ... print("Alignment of length %i" % alignment.get_alignment_length()) 318 Alignment of length 124 319 Alignment of length 119 320 Alignment of length 120 321 Alignment of length 118 322 Alignment of length 125 323 324 If you have a string 'data' containing the file contents, use:: 325 326 from Bio import AlignIO 327 from StringIO import StringIO 328 my_iterator = AlignIO.parse(StringIO(data), format) 329 330 Use the Bio.AlignIO.read() function when you expect a single record only. 331 """ 332 from Bio import SeqIO 333 334 # Try and give helpful error messages: 335 if not isinstance(format, basestring): 336 raise TypeError("Need a string for the file format (lower case)") 337 if not format: 338 raise ValueError("Format required (lower case string)") 339 if format != format.lower(): 340 raise ValueError("Format string '%s' should be lower case" % format) 341 if alphabet is not None and not (isinstance(alphabet, Alphabet) or 342 isinstance(alphabet, AlphabetEncoder)): 343 raise ValueError("Invalid alphabet, %s" % repr(alphabet)) 344 if seq_count is not None and not isinstance(seq_count, int): 345 raise TypeError("Need integer for seq_count (sequences per alignment)") 346 347 with as_handle(handle, 'rU') as fp: 348 # Map the file format to a sequence iterator: 349 if format in _FormatToIterator: 350 iterator_generator = _FormatToIterator[format] 351 if alphabet is None: 352 i = iterator_generator(fp, seq_count) 353 else: 354 try: 355 # Initially assume the optional alphabet argument is supported 356 i = iterator_generator(fp, seq_count, alphabet=alphabet) 357 except TypeError: 358 # It isn't supported. 359 i = _force_alphabet(iterator_generator(fp, seq_count), 360 alphabet) 361 362 elif format in SeqIO._FormatToIterator: 363 # Exploit the existing SeqIO parser to the dirty work! 364 i = _SeqIO_to_alignment_iterator(fp, format, 365 alphabet=alphabet, 366 seq_count=seq_count) 367 else: 368 raise ValueError("Unknown format '%s'" % format) 369 370 # This imposes some overhead... wait until we drop Python 2.4 to fix it 371 for a in i: 372 yield a
373 374
375 -def read(handle, format, seq_count=None, alphabet=None):
376 """Turns an alignment file into a single MultipleSeqAlignment object. 377 378 Arguments: 379 - handle - handle to the file, or the filename as a string 380 (note older versions of Biopython only took a handle). 381 - format - string describing the file format. 382 - alphabet - optional Alphabet object, useful when the sequence type 383 cannot be automatically inferred from the file itself 384 (e.g. fasta, phylip, clustal) 385 - seq_count - Optional integer, number of sequences expected in each 386 alignment. Recommended for fasta format files. 387 388 If the handle contains no alignments, or more than one alignment, 389 an exception is raised. For example, using a PFAM/Stockholm file 390 containing one alignment: 391 392 >>> from Bio import AlignIO 393 >>> filename = "Clustalw/protein.aln" 394 >>> format = "clustal" 395 >>> alignment = AlignIO.read(filename, format) 396 >>> print("Alignment of length %i" % alignment.get_alignment_length()) 397 Alignment of length 411 398 399 If however you want the first alignment from a file containing 400 multiple alignments this function would raise an exception. 401 402 >>> from Bio import AlignIO 403 >>> filename = "Emboss/needle.txt" 404 >>> format = "emboss" 405 >>> alignment = AlignIO.read(filename, format) 406 Traceback (most recent call last): 407 ... 408 ValueError: More than one record found in handle 409 410 Instead use: 411 412 >>> from Bio import AlignIO 413 >>> filename = "Emboss/needle.txt" 414 >>> format = "emboss" 415 >>> alignment = next(AlignIO.parse(filename, format)) 416 >>> print("First alignment has length %i" % alignment.get_alignment_length()) 417 First alignment has length 124 418 419 You must use the Bio.AlignIO.parse() function if you want to read multiple 420 records from the handle. 421 """ 422 iterator = parse(handle, format, seq_count, alphabet) 423 try: 424 first = next(iterator) 425 except StopIteration: 426 first = None 427 if first is None: 428 raise ValueError("No records found in handle") 429 try: 430 second = next(iterator) 431 except StopIteration: 432 second = None 433 if second is not None: 434 raise ValueError("More than one record found in handle") 435 if seq_count: 436 assert len(first) == seq_count 437 return first
438 439
440 -def convert(in_file, in_format, out_file, out_format, alphabet=None):
441 """Convert between two alignment files, returns number of alignments. 442 443 - in_file - an input handle or filename 444 - in_format - input file format, lower case string 445 - output - an output handle or filename 446 - out_file - output file format, lower case string 447 - alphabet - optional alphabet to assume 448 449 **NOTE** - If you provide an output filename, it will be opened which will 450 overwrite any existing file without warning. This may happen if even the 451 conversion is aborted (e.g. an invalid out_format name is given). 452 """ 453 # TODO - Add optimised versions of important conversions 454 # For now just off load the work to SeqIO parse/write 455 with as_handle(in_file, 'rU') as in_handle: 456 # Don't open the output file until we've checked the input is OK: 457 alignments = parse(in_handle, in_format, None, alphabet) 458 459 # This will check the arguments and issue error messages, 460 # after we have opened the file which is a shame. 461 with as_handle(out_file, 'w') as out_handle: 462 count = write(alignments, out_handle, out_format) 463 464 return count
465 466 467 if __name__ == "__main__": 468 from Bio._utils import run_doctest 469 run_doctest() 470