Skip to content

Speed up simple FASTA parsers - #1808

Merged
peterjc merged 4 commits into
biopython:masterfrom
chris-rands:issue1805
Sep 28, 2018
Merged

peterjc merged 4 commits into
biopython:masterfrom
chris-rands:issue1805

Conversation

@chris-rands

Copy link
Copy Markdown
Contributor

This pull request addresses issue #1805

Basically, the PR replaces .readline() calls by iterating over file handles for FASTA parsing with the SimpleFastaParser and FastaTwoLineParser . This speeds up the parsers, at least on my system, maybe someone else can test this independently also?

Here are timings before the PR, suggesting a speed improvement for the new implementation:

Timings: 1 large sequence
old simple parser 76.89216220937669
new simple parser 57.97007081564516
regular parser 76.77094562910497

Timings: 1,000,000 small sequences
old simple parser 43.77311799954623
new simple parser 34.3902100995183
regular parser 206.45853164047003

Timings 1,000,000 small sequences, 2 line parsers
old simple two-line parser 43.24465982336551
new simple two-line parser 23.533120669424534

Here are timings after the PR, old and new timings should be the same here since the new methods are now implemented (I am not sure why they are not for the 2-line parser case, but there is still a speed improvement):

Timings: 1 large sequence
old simple parser 58.63168554287404
new simple parser 58.73430686816573
regular parser 58.55501845944673

Timings: 1,000,000 small sequences
old simple parser 34.61581619922072
new simple parser 34.34436380956322
regular parser 191.3278057463467

Timings 1,000,000 small sequences, 2 line parsers
old simple two-line parser 34.29244772717357
new simple two-line parser 23.71209624875337

The code is on pastebin for reproducibility:
https://pastebin.com/MmhBVfFu

  • I hereby agree to dual licence this and any previous contributions under both
    the Biopython License Agreement AND the BSD 3-Clause License.

  • I have read the CONTRIBUTING.rst file and understand that AppVeyor and
    TravisCI will be used to confirm the Biopython unit tests and flake8 style
    checks pass with these changes.

  • I have added my name to the alphabetical contributors listings in the files
    NEWS.rst and CONTRIB.rst as part of this pull request, am listed
    already, or do not wish to be listed. (This acknowledgement is optional.)

Comment thread Bio/SeqIO/FastaIO.py Outdated
lines.append(line.rstrip())

assert False, "Should not reach this line"
if lines:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this if statement should not be conditional - consider empty sequences (zero length), e.g.

>empty with a blank line afterwards

and:

>empty with no line afterwards

These are both valid but corner case FASTA files.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I did't know, is this tested in the suite? I'm not sure why the tests are failing?

@peterjc

peterjc commented Sep 26, 2018

Copy link
Copy Markdown
Member

It looks like the empty sequence edge case was not directly being picked up on in our test suite (that would be worth adding explicitly), rather they are failing here:

======================================================================
ERROR: test_generated (test_SeqIO_QualityIO.TestWriteRead)
Write and read back odd SeqRecord objects
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/build/biopython/biopython/Tests/test_SeqIO_QualityIO.py", line 492, in test_generated
    truncation_expected(format))
  File "/home/travis/build/biopython/biopython/Tests/test_SeqIO_QualityIO.py", line 129, in compare_records
    raise ValueError("%i vs %i records" % (len(old_list), len(new_list)))
ValueError: 8 vs 6 records
----------------------------------------------------------------------

Have you been able to run the test suite locally? See the testing chapter in the Tutorial...
http://biopython.org/DIST/docs/tutorial/Tutorial.html

@chris-rands

chris-rands commented Sep 26, 2018 •

Copy link
Copy Markdown
Contributor Author

I can add a few the empty sequence edge cases, I assume test_SeqIO_FastaIO.py would be the right place for these unit tests.

Yes I ran the full test suite locally but wanted to check them here also; sometimes I get additional test failures locally that are not replicated here, this is one of those cases:

======================================================================
ERROR: test_generated (test_SeqIO_QualityIO.TestWriteRead)
Write and read back odd SeqRecord objects
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/biopython/Tests/test_SeqIO_QualityIO.py", line 492, in test_generated
    truncation_expected(format))
  File "/path/biopython/Tests/test_SeqIO_QualityIO.py", line 129, in compare_records
    raise ValueError("%i vs %i records" % (len(old_list), len(new_list)))
ValueError: 8 vs 6 records

======================================================================
ERROR: test_doctests (test_Tutorial.TutorialTestCase)
Run tutorial doctests.
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/biopython/Tests/test_Tutorial.py", line 258, in test_doctests
    (len(failures), ", ".join(failures)))
ValueError: 1 Tutorial doctests failed: test_chapter_phylo_line_00074

I also get some UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 13090: ordinal not in range(128) failures, but I think they are un-related to this commit.

Anyway, I will look more into this and get back to you here

@chris-rands

Copy link
Copy Markdown
Contributor Author

Think I fixed it (at least locally the rogue test passed). But is this valid FASTA? It was an example like this that was tripping up my previous code

><unknown id> <unknown description>
><unknown id> <unknown description>
A

@codecov

codecov Bot commented Sep 26, 2018

Copy link
Copy Markdown

Codecov Report

Merging #1808 into master will decrease coverage by <.01%.
The diff coverage is 86.2%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1808      +/-   ##
==========================================
- Coverage   85.33%   85.33%   -0.01%     
==========================================
  Files         301      301              
  Lines       49205    49197       -8     
==========================================
- Hits        41991    41984       -7     
+ Misses       7214     7213       -1
Impacted Files Coverage Δ
Bio/SeqIO/FastaIO.py 70.4% <86.2%> (-1.03%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 51f69c4...4769cb0. Read the comment docs.

@chris-rands

chris-rands commented Sep 27, 2018 •

Copy link
Copy Markdown
Contributor Author

With the methods now implemented it's much easier to do the timings by comparing the master branch to this new-unmerged one. It shows a clear speed increase for the new implementation, using SeqIO.parse() I calculate the time decrease with the new approach is: ~24% for the large chromosome and ~7% for the small chromosomes.*

I think all that remains now probably is adding more unit tests?

Original branch:

Timings: 1 large sequence
3.78 s +- 17.5 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
3.79 s +- 19.8 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)

Timings: 1,000,000 small sequences
2.11 s +- 4.52 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
10.2 s +- 12.1 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
1.26 s +- 803 us per loop (mean +- std. dev. of 7 runs, 1 loop each)

New branch:

Timings: 1 large sequence
2.88 s +- 7.47 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
2.89 s +- 10.5 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)

Timings: 1,000,000 small sequences
1.69 s +- 5.54 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
9.49 s +- 16.5 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)
1.16 s +- 1.84 ms per loop (mean +- std. dev. of 7 runs, 1 loop each)

Code:

Python 3.6.6 (default, Jun 27 2018, 13:11:40) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from Bio.SeqIO.FastaIO import SimpleFastaParser, FastaTwoLineParser
   ...: 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-1):
   ...:         out_f.write('>{}\n'.format(i))
   ...:         out_f.write(SEQ)
   ...:     out_f.write('>Last\n')
   ...:     out_f.write(SEQ.rstrip()) # avoid new-line at end-of-file
   ...: 
   ...: 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'))
   ...: 
   ...: 

In [2]: print('Timings: 1 large sequence')
   ...: in_file = 'chr1.fa'
   ...: %timeit use_parser(SimpleFastaParser)
   ...: %timeit use_seqIO_parse()
   ...: 
   ...: print('\nTimings: 1,000,000 small sequences')
   ...: in_file = 'chrUnknown.fa'
   ...: %timeit use_parser(SimpleFastaParser)
   ...: %timeit use_seqIO_parse()
   ...: %timeit use_parser(FastaTwoLineParser)
   ...: 
   ...:

*

>>> round((3.79 - 2.89) / 3.79 * 100)
24
>>> round((10.2 - 9.49) / 10.2 * 100)
7

@peterjc

peterjc commented Sep 27, 2018

Copy link
Copy Markdown
Member

RE:

><unknown id> <unknown description>
><unknown id> <unknown description>
A

Yes, I consider that to be a pathological but valid FASTA file containing a zero length sequence followed by a single letter sequence.

The <unknown id> and <unknown description> bits are a historical legacy in Biopython with regrettable default values - specifically having a space in the default ID really annoys me because of how spaces in FASTA and FASTQ descriptions are used to mark the end of the ID.

@peterjc

peterjc commented Sep 27, 2018

Copy link
Copy Markdown
Member

Can you check if your unicode problem has been reported already, and if so can you add anything useful to one of these open issues?
https://github.com/biopython/biopython/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+unicode

If it is a new issue, please log it.

@peterjc

peterjc commented Sep 27, 2018

Copy link
Copy Markdown
Member

My initial testing - note that 60 or 80 bases per line is more common so I've used that - but this was based on your example:

import os
SEQ_LINE = 'ATCGN'* 80 + '\n'

# Make test files                                                                                                                                              
if not os.path.isfile('one_big.fa'):
    with open('one_big.fa', 'w') as out_f:
        out_f.write('>1\n')
        for _ in range(5000000):
            out_f.write(SEQ_LINE)

if not os.path.isfile('many_medium.fa'):
    with open('many_medium.fa', 'w') as out_f:
        for i in range(1000000):
            out_f.write('>{}\n'.format(i))
            for _ in range(5):
                out_f.write(SEQ_LINE)

if not os.path.isfile('lots_small.fa'):
    with open('lots_small.fa', 'w') as out_f:
        for i in range(5000000-1):
            out_f.write('>{}\n'.format(i))
            out_f.write(SEQ_LINE)
        out_f.write('>Last\n')
        # avoid new-line at end-of-file - corner case to test 
        out_f.write(SEQ_LINE.rstrip())                                                                  

Then the test script,

from timeit import timeit

def use_parser(function_name, filename):
    with open(filename) as handle:
        return sum(1 for _ in function_name(handle))


print('Timings: 1 large sequence')
print(timeit('sum(1 for _ in SimpleFastaParser(open("chr1.fa")))',
             setup='from Bio.SeqIO.FastaIO import SimpleFastaParser',
             number = 20))
print('Timings: 1,000,000 medium sequences')
print(timeit('sum(1 for _ in SimpleFastaParser(open("many_medium.fa")))',
             setup='from Bio.SeqIO.FastaIO import SimpleFastaParser',
             number = 20))
print('Timings: 5,000,000 small sequences')
print(timeit('sum(1 for _ in SimpleFastaParser(open("lots_small.fa")))',
             setup='from Bio.SeqIO.FastaIO import SimpleFastaParser',
             number = 20))

Using the master branch on macOS Python 3.7.0rc1,

$ python3 prof.py 
Timings: 1 large sequence
53.643027125
Timings: 1,000,000 medium sequences
151.03412170000001
Timings: 5,000,000 small sequences
197.739021662

Using your branch on macOS Python 3.7.0rc1, definitely faster in all three:

$ python3 prof.py 
Timings: 1 large sequence
45.046140553
Timings: 1,000,000 medium sequences
139.18455809
Timings: 5,000,000 small sequences
167.565322556

TODO: At least Python 2.7 testing, ideally also PyPy testing, hopefully tomorrow...

@chris-rands

Copy link
Copy Markdown
Contributor Author

Thank you Peter! I ran your script on python 3 and python 2. My timings are very different but the new implementation still performs better.

I ran the scripts several times (and in different orders) because I found it hard to believe the python 2 timings, but they remained fairly consistent (not caching I guess). Actually I found that just iterating over the file handle was a lot faster in 2 than 3, which is surprising, and likely something specific to the server I'm running on I guess.

Master branch on python 3.6.6, Arch-Linux:

$ python3 prof.py 
Timings: 1 large sequence
213.88335552904755
Timings: 1,000,000 medium sequences
184.40232768841088
Timings: 5,000,000 small sequences
277.8726044809446

Unmerged branch on python 3.6.6, Arch-Linux:

$ python3 prof.py 
Timings: 1 large sequence
190.6445388859138
Timings: 1,000,000 medium sequences
156.47698998171836
Timings: 5,000,000 small sequences
228.40243513602763

Master branch on python 2.7.15, Arch-Linux:

$ python2 prof.py 
Timings: 1 large sequence
278.568771124
Timings: 1,000,000 medium sequences
252.035916805
Timings: 5,000,000 small sequences
346.000877857

Unmerged branch on python 2.7.15, Arch-Linux:

$ python2 prof.py 
Timings: 1 large sequence
110.950079203
Timings: 1,000,000 medium sequences
70.3632860184
Timings: 5,000,000 small sequences
131.09875679

@chris-rands

Copy link
Copy Markdown
Contributor Author

RE the unicode problem, it's not obvious to me, I'll look into it separately and respond in the relevant issue (or create a new one)

@peterjc

peterjc commented Sep 28, 2018

Copy link
Copy Markdown
Member

My timings on macOS, Python 2.7.10, master branch:

$ python prof.py 
Timings: 1 large sequence
59.3511388302
Timings: 1,000,000 medium sequences
221.688102007
Timings: 5,000,000 small sequences
282.628316164

My timings on macOS, Python 2.7.10, your branch:

$ python prof.py 
Timings: 1 large sequence
32.8169391155
Timings: 1,000,000 medium sequences
86.7953760624
Timings: 5,000,000 small sequences
112.881361961

Again, consistently faster. Next, a PyPy comparison...

@peterjc

peterjc commented Sep 28, 2018

Copy link
Copy Markdown
Member

My timings on macOS, using https://bitbucket.org/pypy/pypy/downloads/pypy2-v6.0.0-osx64.tar.bz2 and the master branch:

Timings: 1 large sequence
52.4669089317
Timings: 1,000,000 medium sequences
119.042057991
Timings: 5,000,000 small sequences
122.2268641

And your branch,

Timings: 1 large sequence
51.452051878
Timings: 1,000,000 medium sequences
121.389673948
Timings: 5,000,000 small sequences
125.54364109

It would seem thanks to PyPy's optimisations on the fly, the two FASTA parsers come out about even.

@peterjc
peterjc merged commit 8ef1e35 into biopython:master Sep 28, 2018
@peterjc

peterjc commented Sep 28, 2018

Copy link
Copy Markdown
Member

Merged, thank you!

@chris-rands

Copy link
Copy Markdown
Contributor Author

I did some timings previously of SeqIO.parse() (which uses SimpleFastaParser) but for completeness here are some further timings on Linux now that this PR and #1810 have been merged.

SeqIO.parse() is the main way users parse FASTA files so these timings are of most practical relevance. The new implementation for Biopython 1.73 is always faster than the previous implementation for Biopython 1.72 under these testing conditions.

Timings:

Python version: sys.version_info(major=3, minor=6, micro=6, releaselevel='final', serial=0)
Biopython version: 1.73.dev0

Timings: 1 large sequence
193.24775595590472
Timings: 1,000,000 medium sequences
326.8254526471719
Timings: 5,000,000 small sequences
925.6927637113258

and...

Python version: sys.version_info(major=3, minor=6, micro=6, releaselevel='final', serial=0)
Biopython version: 1.72

Timings: 1 large sequence
216.363718775101
Timings: 1,000,000 medium sequences
352.7969301017001
Timings: 5,000,000 small sequences
1004.3156771864742

Code:

import os
import sys
import Bio

SEQ_LINE = 'ATCGN'* 80 + '\n'

# Make test files                                                                                                                                              
if not os.path.isfile('one_big.fa'):
    with open('one_big.fa', 'w') as out_f:
        out_f.write('>1\n')
        for _ in range(5000000):
            out_f.write(SEQ_LINE)

if not os.path.isfile('many_medium.fa'):
    with open('many_medium.fa', 'w') as out_f:
        for i in range(1000000):
            out_f.write('>{}\n'.format(i))
            for _ in range(5):
                out_f.write(SEQ_LINE)

if not os.path.isfile('lots_small.fa'):
    with open('lots_small.fa', 'w') as out_f:
        for i in range(5000000-1):
            out_f.write('>{}\n'.format(i))
            out_f.write(SEQ_LINE)
        out_f.write('>Last\n')
        # avoid new-line at end-of-file - corner case to test 
        out_f.write(SEQ_LINE.rstrip())                                                                  

from timeit import timeit

def use_parser(function_name, filename):
    with open(filename) as handle:
        return sum(1 for _ in function_name(handle))

print('Python version: {}\n'
      'Biopython version: {}\n'.
       format(sys.version_info, Bio.__version__))

print('Timings: 1 large sequence')
print(timeit('sum(1 for _ in SeqIO.parse("one_big.fa", "fasta"))',
             setup='from Bio import SeqIO',
             number = 20))
print('Timings: 1,000,000 medium sequences')
print(timeit('sum(1 for _ in SeqIO.parse("many_medium.fa", "fasta"))',
             setup='from Bio import SeqIO',
             number = 20))
print('Timings: 5,000,000 small sequences')
print(timeit('sum(1 for _ in SeqIO.parse("lots_small.fa", "fasta"))',
             setup='from Bio import SeqIO',
             number = 20))

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants