Guest User

Time Biopython fasta parsers

a guest
Sep 26th, 2018
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.37 KB | None | 0 0
  1. from Bio.SeqIO.FastaIO import SimpleFastaParser
  2. from Bio import SeqIO
  3.  
  4. SEQ = 'ATCGN'* 10 + '\n'
  5.  
  6. # Creating fasta files
  7. with open('chr1.fa', 'w') as out_f:
  8.     out_f.write('>1\n')
  9.     for _ in range(4979128):  # roughly the size of human chromosome 1, nearly 250Mb
  10.         out_f.write(SEQ)
  11.  
  12. with open('chrUnknown.fa', 'w') as out_f:
  13.     for i in range(1000000-1):
  14.         out_f.write('>{}\n'.format(i))
  15.         out_f.write(SEQ)
  16.     out_f.write('>Last\n')
  17.     out_f.write(SEQ.rstrip()) # avoid new-line at end-of-file
  18.  
  19. # New parser
  20. def new_parser(handle):
  21.     # Skip any text before the first record (e.g. blank lines, comments)
  22.     for line in handle:
  23.         if line[0] == '>':
  24.             title = line[1:].rstrip()
  25.             break
  26.  
  27.     # Main work
  28.     # Remove trailing whitespace, and any internal spaces
  29.     # (and any embedded \r which are possible in mangled files
  30.     # when not opened in universal read lines mode)
  31.     lines = []
  32.     for line in handle:
  33.         if line[0] == '>':
  34.             if lines:
  35.                 yield title, ''.join(lines).replace(" ", "").replace("\r", "")
  36.                 lines = []
  37.             title = line[1:].rstrip()
  38.             continue
  39.         lines.append(line.rstrip())
  40.     if lines:
  41.         yield title, ''.join(lines).replace(" ", "").replace("\r", "")
  42.  
  43. def use_parser(parser):
  44.     with open(in_file) as handle:
  45.         return list(parser(handle))
  46.  
  47. def use_seqIO_parse():
  48.     return list(SeqIO.parse(in_file, 'fasta'))
  49.  
  50. def sanity_check():
  51.     if use_parser(SimpleFastaParser) != use_parser(new_parser):
  52.         raise Exception('Old and new parsers produce different outputs!')
  53.  
  54. from timeit import timeit
  55.  
  56. def timings():
  57.     print('old simple parser', timeit('use_parser(SimpleFastaParser)', setup='from Bio.SeqIO.FastaIO import SimpleFastaParser; from __main__ import use_parser', number = 20))
  58.     print('new simple parser', timeit('use_parser(new_parser)', setup='from __main__ import new_parser, use_parser', number = 20))
  59.     print('regular parser', timeit('use_seqIO_parse()', setup='from __main__ import use_seqIO_parse', number = 20))
  60.  
  61. print('Timings: 1 large sequence')
  62. in_file = 'chr1.fa'
  63. sanity_check()
  64. timings()
  65.  
  66. print('\nTimings: 1,000,000 small sequences')
  67. in_file = 'chrUnknown.fa'
  68. sanity_check()
  69. timings()
  70.  
  71. # New two line parser
  72. def new_two_line_parser(handle):
  73.     for idx, line in enumerate(handle):
  74.         if idx % 2 == 0:  # header line
  75.             if line[0] != '>':
  76.                 if line.strip():
  77.                     raise ValueError("Expected FASTA record starting with '>' character. "
  78.                                      "Perhaps this file is using FASTA line wrapping? "
  79.                                      "Got: {}".format(line))  
  80.                 else:
  81.                     raise ValueError("Expected FASTA record starting with '>' character. "
  82.                                      "If using two-lines-per-record, there should be no "
  83.                                      "blank lines between records, or at the end of file.")
  84.             title = line[1:].rstrip()
  85.         else:  # sequence line
  86.             line = line.strip()
  87.             if not line:
  88.                 raise ValueError("Premature end of FASTA file (or this is not strict "
  89.                                  "two-line-per-record FASTA format), expected one line "
  90.                                  "of sequence following: '{}'".format(title))
  91.             elif line[0] == '>':
  92.                 raise ValueError("Two '>' FASTA lines in a row. Missing sequence line "
  93.                                  "if this is strict two-line-per-record FASTA format. "
  94.                                  "Have '>{}' and '{}'".format(title, line))  
  95.             yield title, line
  96.  
  97.     if idx % 2 == 0:
  98.         raise ValueError("Should be at end of file, but line= '{}'".format(line))        
  99.  
  100.  
  101. print('\nTimings 1,000,000 small sequences, 2 line parsers')
  102.  
  103. from Bio.SeqIO.FastaIO import FastaTwoLineParser
  104.  
  105. in_file = 'chrUnknown.fa'
  106. assert use_parser(FastaTwoLineParser) == use_parser(new_two_line_parser)
  107.  
  108. print('old simple two-line parser', timeit('use_parser(SimpleFastaParser)', setup='from Bio.SeqIO.FastaIO import SimpleFastaParser; from __main__ import use_parser', number = 20))
  109. print('new simple two-line parser', timeit('use_parser(new_two_line_parser)', setup='from __main__ import new_two_line_parser, use_parser', number = 20))
Advertisement
Add Comment
Please, Sign In to add comment