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

Source Code for Package Bio.AlignIO

  1  # Copyright 2008-2017 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.Alphabet import Alphabet, AlphabetEncoder, _get_base_alphabet 
146  from Bio.File import as_handle 
147   
148  from . import StockholmIO 
149  from . import ClustalIO 
150  from . import NexusIO 
151  from . import PhylipIO 
152  from . import EmbossIO 
153  from . import FastaIO 
154  from . import MafIO 
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                       "maf": MafIO.MafIterator, 
164                       "nexus": NexusIO.NexusIterator, 
165                       "phylip": PhylipIO.PhylipIterator, 
166                       "phylip-sequential": PhylipIO.SequentialPhylipIterator, 
167                       "phylip-relaxed": PhylipIO.RelaxedPhylipIterator, 
168                       "stockholm": StockholmIO.StockholmIterator, 
169                       } 
170   
171  _FormatToWriter = {  # "fasta" is done via Bio.SeqIO 
172                       # "emboss" : EmbossIO.EmbossWriter, (unfinished) 
173                     "maf": MafIO.MafWriter, 
174                     "nexus": NexusIO.NexusWriter, 
175                     "phylip": PhylipIO.PhylipWriter, 
176                     "phylip-sequential": PhylipIO.SequentialPhylipWriter, 
177                     "phylip-relaxed": PhylipIO.RelaxedPhylipWriter, 
178                     "stockholm": StockholmIO.StockholmWriter, 
179                     "clustal": ClustalIO.ClustalWriter, 
180                     } 
181   
182   
183 -def write(alignments, handle, format):
184 """Write complete set of alignments to a file. 185 186 Arguments: 187 - alignments - A list (or iterator) of MultipleSeqAlignment objects, 188 or a single alignment object. 189 - handle - File handle object to write to, or filename as string 190 (note older versions of Biopython only took a handle). 191 - format - lower case string describing the file format to write. 192 193 You should close the handle after calling this function. 194 195 Returns the number of alignments written (as an integer). 196 """ 197 from Bio import SeqIO 198 199 # Try and give helpful error messages: 200 if not isinstance(format, basestring): 201 raise TypeError("Need a string for the file format (lower case)") 202 if not format: 203 raise ValueError("Format required (lower case string)") 204 if format != format.lower(): 205 raise ValueError("Format string '%s' should be lower case" % format) 206 207 if isinstance(alignments, MultipleSeqAlignment): 208 # This raised an exception in older versions of Biopython 209 alignments = [alignments] 210 211 with as_handle(handle, 'w') as fp: 212 # Map the file format to a writer class 213 if format in _FormatToWriter: 214 writer_class = _FormatToWriter[format] 215 count = writer_class(fp).write_file(alignments) 216 elif format in SeqIO._FormatToWriter: 217 # Exploit the existing SeqIO parser to do the dirty work! 218 # TODO - Can we make one call to SeqIO.write() and count the alignments? 219 count = 0 220 for alignment in alignments: 221 if not isinstance(alignment, MultipleSeqAlignment): 222 raise TypeError("Expect a list or iterator of MultipleSeqAlignment " 223 "objects, got: %r" % alignment) 224 SeqIO.write(alignment, fp, format) 225 count += 1 226 elif format in _FormatToIterator or format in SeqIO._FormatToIterator: 227 raise ValueError("Reading format '%s' is supported, but not writing" 228 % format) 229 else: 230 raise ValueError("Unknown format '%s'" % format) 231 232 assert isinstance(count, int), "Internal error - the underlying %s " \ 233 "writer should have returned the alignment count, not %s" \ 234 % (format, repr(count)) 235 236 return count
237 238 239 # This is a generator function!
240 -def _SeqIO_to_alignment_iterator(handle, format, alphabet=None, seq_count=None):
241 """Uses Bio.SeqIO to create an MultipleSeqAlignment iterator (PRIVATE). 242 243 Arguments: 244 - handle - handle to the file. 245 - format - string describing the file format. 246 - alphabet - optional Alphabet object, useful when the sequence type 247 cannot be automatically inferred from the file itself 248 (e.g. fasta, phylip, clustal) 249 - seq_count - Optional integer, number of sequences expected in each 250 alignment. Recommended for fasta format files. 251 252 If count is omitted (default) then all the sequences in the file are 253 combined into a single MultipleSeqAlignment. 254 """ 255 from Bio import SeqIO 256 assert format in SeqIO._FormatToIterator 257 258 if seq_count: 259 # Use the count to split the records into batches. 260 seq_record_iterator = SeqIO.parse(handle, format, alphabet) 261 262 records = [] 263 for record in seq_record_iterator: 264 records.append(record) 265 if len(records) == seq_count: 266 yield MultipleSeqAlignment(records, alphabet) 267 records = [] 268 if records: 269 raise ValueError("Check seq_count argument, not enough sequences?") 270 else: 271 # Must assume that there is a single alignment using all 272 # the SeqRecord objects: 273 records = list(SeqIO.parse(handle, format, alphabet)) 274 if records: 275 yield MultipleSeqAlignment(records, alphabet)
276 277
278 -def _force_alphabet(alignment_iterator, alphabet):
279 """Iterate over alignments, over-riding the alphabet (PRIVATE).""" 280 # Assume the alphabet argument has been pre-validated 281 given_base_class = _get_base_alphabet(alphabet).__class__ 282 for align in alignment_iterator: 283 if not isinstance(_get_base_alphabet(align._alphabet), 284 given_base_class): 285 raise ValueError("Specified alphabet %s clashes with " 286 "that determined from the file, %s" 287 % (repr(alphabet), repr(align._alphabet))) 288 for record in align: 289 if not isinstance(_get_base_alphabet(record.seq.alphabet), 290 given_base_class): 291 raise ValueError("Specified alphabet %s clashes with " 292 "that determined from the file, %s" 293 % (repr(alphabet), repr(record.seq.alphabet))) 294 record.seq.alphabet = alphabet 295 align._alphabet = alphabet 296 yield align
297 298
299 -def parse(handle, format, seq_count=None, alphabet=None):
300 """Iterate over an alignment file as MultipleSeqAlignment objects. 301 302 Arguments: 303 - handle - handle to the file, or the filename as a string 304 (note older versions of Biopython only took a handle). 305 - format - string describing the file format. 306 - alphabet - optional Alphabet object, useful when the sequence type 307 cannot be automatically inferred from the file itself 308 (e.g. fasta, phylip, clustal) 309 - seq_count - Optional integer, number of sequences expected in each 310 alignment. Recommended for fasta format files. 311 312 If you have the file name in a string 'filename', use: 313 314 >>> from Bio import AlignIO 315 >>> filename = "Emboss/needle.txt" 316 >>> format = "emboss" 317 >>> for alignment in AlignIO.parse(filename, format): 318 ... print("Alignment of length %i" % alignment.get_alignment_length()) 319 Alignment of length 124 320 Alignment of length 119 321 Alignment of length 120 322 Alignment of length 118 323 Alignment of length 125 324 325 If you have a string 'data' containing the file contents, use:: 326 327 from Bio import AlignIO 328 from StringIO import StringIO 329 my_iterator = AlignIO.parse(StringIO(data), format) 330 331 Use the Bio.AlignIO.read() function when you expect a single record only. 332 """ 333 from Bio import SeqIO 334 335 # Try and give helpful error messages: 336 if not isinstance(format, basestring): 337 raise TypeError("Need a string for the file format (lower case)") 338 if not format: 339 raise ValueError("Format required (lower case string)") 340 if format != format.lower(): 341 raise ValueError("Format string '%s' should be lower case" % format) 342 if alphabet is not None and not (isinstance(alphabet, Alphabet) or 343 isinstance(alphabet, AlphabetEncoder)): 344 raise ValueError("Invalid alphabet, %s" % repr(alphabet)) 345 if seq_count is not None and not isinstance(seq_count, int): 346 raise TypeError("Need integer for seq_count (sequences per alignment)") 347 348 with as_handle(handle, 'rU') as fp: 349 # Map the file format to a sequence iterator: 350 if format in _FormatToIterator: 351 iterator_generator = _FormatToIterator[format] 352 if alphabet is None: 353 i = iterator_generator(fp, seq_count) 354 else: 355 try: 356 # Initially assume the optional alphabet argument is supported 357 i = iterator_generator(fp, seq_count, alphabet=alphabet) 358 except TypeError: 359 # It isn't supported. 360 i = _force_alphabet(iterator_generator(fp, seq_count), 361 alphabet) 362 363 elif format in SeqIO._FormatToIterator: 364 # Exploit the existing SeqIO parser to the dirty work! 365 i = _SeqIO_to_alignment_iterator(fp, format, 366 alphabet=alphabet, 367 seq_count=seq_count) 368 else: 369 raise ValueError("Unknown format '%s'" % format) 370 371 # This imposes some overhead... wait until we drop Python 2.4 to fix it 372 for a in i: 373 yield a
374 375
376 -def read(handle, format, seq_count=None, alphabet=None):
377 """Turns an alignment file into a single MultipleSeqAlignment object. 378 379 Arguments: 380 - handle - handle to the file, or the filename as a string 381 (note older versions of Biopython only took a handle). 382 - format - string describing the file format. 383 - alphabet - optional Alphabet object, useful when the sequence type 384 cannot be automatically inferred from the file itself 385 (e.g. fasta, phylip, clustal) 386 - seq_count - Optional integer, number of sequences expected in each 387 alignment. Recommended for fasta format files. 388 389 If the handle contains no alignments, or more than one alignment, 390 an exception is raised. For example, using a PFAM/Stockholm file 391 containing one alignment: 392 393 >>> from Bio import AlignIO 394 >>> filename = "Clustalw/protein.aln" 395 >>> format = "clustal" 396 >>> alignment = AlignIO.read(filename, format) 397 >>> print("Alignment of length %i" % alignment.get_alignment_length()) 398 Alignment of length 411 399 400 If however you want the first alignment from a file containing 401 multiple alignments this function would raise an exception. 402 403 >>> from Bio import AlignIO 404 >>> filename = "Emboss/needle.txt" 405 >>> format = "emboss" 406 >>> alignment = AlignIO.read(filename, format) 407 Traceback (most recent call last): 408 ... 409 ValueError: More than one record found in handle 410 411 Instead use: 412 413 >>> from Bio import AlignIO 414 >>> filename = "Emboss/needle.txt" 415 >>> format = "emboss" 416 >>> alignment = next(AlignIO.parse(filename, format)) 417 >>> print("First alignment has length %i" % alignment.get_alignment_length()) 418 First alignment has length 124 419 420 You must use the Bio.AlignIO.parse() function if you want to read multiple 421 records from the handle. 422 """ 423 iterator = parse(handle, format, seq_count, alphabet) 424 try: 425 first = next(iterator) 426 except StopIteration: 427 first = None 428 if first is None: 429 raise ValueError("No records found in handle") 430 try: 431 second = next(iterator) 432 except StopIteration: 433 second = None 434 if second is not None: 435 raise ValueError("More than one record found in handle") 436 if seq_count: 437 assert len(first) == seq_count 438 return first
439 440
441 -def convert(in_file, in_format, out_file, out_format, alphabet=None):
442 """Convert between two alignment files, returns number of alignments. 443 444 - in_file - an input handle or filename 445 - in_format - input file format, lower case string 446 - output - an output handle or filename 447 - out_file - output file format, lower case string 448 - alphabet - optional alphabet to assume 449 450 **NOTE** - If you provide an output filename, it will be opened which will 451 overwrite any existing file without warning. This may happen if even the 452 conversion is aborted (e.g. an invalid out_format name is given). 453 """ 454 # TODO - Add optimised versions of important conversions 455 # For now just off load the work to SeqIO parse/write 456 with as_handle(in_file, 'rU') as in_handle: 457 # Don't open the output file until we've checked the input is OK: 458 alignments = parse(in_handle, in_format, None, alphabet) 459 460 # This will check the arguments and issue error messages, 461 # after we have opened the file which is a shame. 462 with as_handle(out_file, 'w') as out_handle: 463 count = write(alignments, out_handle, out_format) 464 465 return count
466 467 468 if __name__ == "__main__": 469 from Bio._utils import run_doctest 470 run_doctest() 471