Skip to content

Can we improve the speed of "SimpleFastaParser"? #1805

Closed

Description

@chris-rands

Setup

I am testing with Biopython version, Python version, and operating
system as follows:

>>> import sys; print(sys.version)
3.6.6 (default, Jun 27 2018, 13:11:40) 
[GCC 8.1.1 20180531]
>>> import platform; print(platform.python_implementation()); print(platform.platform())
CPython
Linux-4.17.9-1-ARCH-x86_64-with-arch-Arch-Linux
>>> import Bio; print(Bio.__version__)
1.73.dev0

Behaviour

I noticed that SimpleFastaParser uses a lot of idioms like while True: line = handle.readline(). Probably when the code was written this was the best way, but I think it is faster and more idiomatic now to iterate over the file handles in for loops, so I did some timings and wrote a possible alternative implementation. My conclusion is that the suggested new implementation might significantly improve performance in terms of speed (not tested memory usage, although I would expect it to be similar), but I may have missed something of course.

SimpleFastaParser is not just used stand-alone it is called by FastaIterator (which is used in SeqIO), so this impacts a lot of code.

(Probably, the same logic applies for FastaTwoLineParser).

Timings on my setup:

Timings: 1 large sequence
old simple parser 74.16620713099837
new simple parser 58.59408786240965
regular parser 73.79975877702236

Timings: 1,000,000 small sequences
old simple parser 43.25301963556558
new simple parser 33.491335636004806
regular parser 199.85498186200857

Timings on other systems would also be useful if this is worth taking forwards?

Steps to reproduce

from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio import SeqIO

SEQ = 'ATCGN'* 10 + '\n'

with open('chr1.fa', 'w') as out_f:
    out_f.write('>1\n')
    for _ in range(4979128):  # roughly the size of human chromosome 1, nearly 250Mb 
        out_f.write(SEQ)

in_file = 'chr1.fa'

def old_parser():
    with open(in_file) as handle:
        for record in SimpleFastaParser(handle):
            yield record

def new_parser():
    with open(in_file) as handle:
        # Skip any text before the first record (e.g. blank lines, comments)
        for line in handle:
            if line[0] == '>':
                title = line[1:].rstrip()
                break

        # Main work
        # Remove trailing whitespace, and any internal spaces
        # (and any embedded \r which are possible in mangled files
        # when not opened in universal read lines mode)
        lines = []
        for line in handle:
            if line[0] == '>':
                if lines:
                    yield title, ''.join(lines).replace(" ", "").replace("\r", "")
                    lines = []
                title = line[1:].rstrip()
                continue
            lines.append(line.rstrip())
    if lines:
        yield title, ''.join(lines).replace(" ", "").replace("\r", "")

def regular_parser():
    for record in SeqIO.parse(in_file, 'fasta'):
        yield record

assert list(old_parser()) == list(new_parser())

from timeit import timeit

def timings():
    print('old simple parser', timeit('list(old_parser())', setup='from __main__ import old_parser', number = 20))
    print('new simple parser', timeit('list(new_parser())', setup='from __main__ import new_parser', number = 20))
    print('regular parser', timeit('list(regular_parser())', setup='from __main__ import regular_parser', number = 20))

print('Timings: 1 large sequence')
timings()

with open('chrUnknown.fa', 'w') as out_f:
    for i in range(1000000):
        out_f.write('>{}\n'.format(i))
        out_f.write(SEQ)

in_file = 'chrUnknown.fa'

assert list(old_parser()) == list(new_parser())

print('\nTimings: 1,000,000 small sequences')
timings()

Activity

  1. peterjc commented on Sep 25, 2018

    @peterjc
    Member

    This is certainly worth looking into, but you'd need to present the alternative implementations in a fair test - as written the old_parser wrapper is adding an overhead which is not present in new_parser. That may be clouding the results.

    It would be clearer to import and use SimpleFastaParser directly as one thing tested, and write your alternative implementation (with the same argument as inputs) as the other thing to be tested.

  2. chris-rands commented on Sep 25, 2018

    @chris-rands
    ContributorAuthor

    Thanks Peter, good point, I re-wrote the testing, is this fair? There is still a time difference on my system at least.

    Timings:

    Timings: 1 large sequence
    old simple parser 72.41819965466857
    new simple parser 56.1086101513356
    regular parser 72.40061821881682
    
    Timings: 1,000,000 small sequences
    old simple parser 41.45167845394462
    new simple parser 33.38985333312303
    regular parser 198.26396819204092
    

    Implementation:

    from Bio.SeqIO.FastaIO import SimpleFastaParser
    from Bio import SeqIO
    
    SEQ = 'ATCGN'* 10 + '\n'
    
    # Creating fasta files
    with open('chr1.fa', 'w') as out_f:
        out_f.write('>1\n')
        for _ in range(4979128):  # roughly the size of human chromosome 1, nearly 250Mb 
            out_f.write(SEQ)
    
    with open('chrUnknown.fa', 'w') as out_f:
        for i in range(1000000):
            out_f.write('>{}\n'.format(i))
            out_f.write(SEQ)
    
    # New parser
    def new_parser(handle):
        # Skip any text before the first record (e.g. blank lines, comments)
        for line in handle:
            if line[0] == '>':
                title = line[1:].rstrip()
                break
    
        # Main work
        # Remove trailing whitespace, and any internal spaces
        # (and any embedded \r which are possible in mangled files
        # when not opened in universal read lines mode)
        lines = []
        for line in handle:
            if line[0] == '>':
                if lines:
                    yield title, ''.join(lines).replace(" ", "").replace("\r", "")
                    lines = []
                title = line[1:].rstrip()
                continue
            lines.append(line.rstrip())
        if lines:
            yield title, ''.join(lines).replace(" ", "").replace("\r", "")
    
    def use_parser(parser):
        with open(in_file) as handle:
            return list(parser(handle))
    
    def use_seqIO_parse():
        return list(SeqIO.parse(in_file, 'fasta'))
    
    def sanity_check():
        if use_parser(SimpleFastaParser) != use_parser(new_parser):
            raise Exception('Old and new parsers produce different outputs!') 
    
    from timeit import timeit
    
    def timings():
        print('old simple parser', timeit('use_parser(SimpleFastaParser)', setup='from Bio.SeqIO.FastaIO import SimpleFastaParser; from __main__ import use_parser', number = 20))
        print('new simple parser', timeit('use_parser(new_parser)', setup='from __main__ import new_parser, use_parser', number = 20))
        print('regular parser', timeit('use_seqIO_parse()', setup='from __main__ import use_seqIO_parse', number = 20))
    
    print('Timings: 1 large sequence')
    in_file = 'chr1.fa'
    sanity_check()
    timings()
    
    print('\nTimings: 1,000,000 small sequences')
    in_file = 'chrUnknown.fa'
    sanity_check()
    timings()
    

    EDIT: IPython 6.3.1 on Python 3.6.6 timings with the %timeit magic:

    In [2]: in_file = 'chr1.fa'
    
    In [3]: %timeit use_parser(SimpleFastaParser)
    3.63 s +- 7.88 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
    
    In [4]: %timeit use_parser(new_parser)
    2.79 s +- 2.7 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
    
    In [5]: in_file = 'chrUnknown.fa'
    
    In [6]: %timeit use_parser(SimpleFastaParser)
    2.11 s +- 13.6 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
    
    In [7]: %timeit use_parser(new_parser)
    1.65 s +- 3.55 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
    
  3. peterjc commented on Sep 26, 2018

    @peterjc
    Member

    OK, that seems worth doing - a small but measurable performance gain (at least on your system) from using for line in handle: rather than line = handle.readline() - could you submit this as a pull request please?

    I forget now how many variants I originally tried, but it is entirely possible that the performance balance has shifted from Python 2.7 to recent Python 3.x, and we'll be dropping Python 2.7 support in 2020 - so performance on recent Python 3 is the priority now.

  4. peterjc commented on Sep 28, 2018

    @peterjc
    Member

    Fixed via #1808, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions