Skip to content

Possible fix for Python 3.7 RuntimeError in MMCIF2Dict - #1835

Merged
peterjc merged 2 commits into
biopython:masterfrom
chris-rands:testRuntimeErrorFix
Oct 30, 2018
Merged

peterjc merged 2 commits into
biopython:masterfrom
chris-rands:testRuntimeErrorFix

Conversation

@chris-rands

Copy link
Copy Markdown
Contributor

This pull request might address issue #1693 (see also #1635), but it is untested, please don't consider merging until the tests are complete.

  • 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.)

@chris-rands

Copy link
Copy Markdown
Contributor Author

@peterjc a new failure, now across all Python versions:

ERROR: test_SeqIO
----------------------------------------------------------------------
Traceback (most recent call last):
  File "run_tests.py", line 459, in runTest
    suite = loader.loadTestsFromName(name)
  File "/opt/python/3.6.3/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "/home/travis/build/biopython/biopython/Tests/test_SeqIO.py", line 499, in <module>
    records = list(SeqIO.parse(handle, t_format))
  File "/home/travis/build/biopython/biopython/build/lib.linux-x86_64-3.6/Bio/SeqIO/__init__.py", line 647, in parse
    for r in i:
  File "/home/travis/build/biopython/biopython/build/lib.linux-x86_64-3.6/Bio/SeqIO/PdbIO.py", line 468, in CifAtomIterator
    struct = MMCIFParser().get_structure(pdb_id, buffer)
  File "/home/travis/build/biopython/biopython/build/lib.linux-x86_64-3.6/Bio/PDB/MMCIFParser.py", line 64, in get_structure
    self._build_structure(structure_id)
  File "/home/travis/build/biopython/biopython/build/lib.linux-x86_64-3.6/Bio/PDB/MMCIFParser.py", line 78, in _build_structure
    atom_id_list = mmcif_dict["_atom_site.label_atom_id"]
KeyError: '_atom_site.label_atom_id'

It looks like the test failure relates to testing for an empty handle, but I have no familiarity with the PDB module I'm afraid, and I'm confused as to how the test didn't fail before but does not.

@peterjc

peterjc commented Oct 26, 2018

Copy link
Copy Markdown
Member

Good question, I don't immediately see it either. Wild guess, might this work instead (continue vs return)?

            try:
                token = next(tokens)
            except StopIteration:
                continue  # for Python 3.7 and PEP 479

@chris-rands

Copy link
Copy Markdown
Contributor Author

continue (or break) fail since there isn't yet a loop a this point.

Some formats are excused from these empty handle tests, I don't know if cif-atom (where the test appears to crash) should be in that category. Either way, it doesn't explain why this test didn't fail previously.

@jgreener64

jgreener64 commented Oct 29, 2018 •

Copy link
Copy Markdown
Contributor

Is the issue on Python 3.7 the call to next?

If so, the code could be refactored to remove this call:

tokens = self._tokenize(handle)
i = 0
n = 0
for ti, token in enumerate(tokens):
    if ti == 0:
        self[token[0:5]] = token[5:]
        continue
    if token.lower() == "loop_":
        ...

NB I haven't checked this works.

@chris-rands

Copy link
Copy Markdown
Contributor Author

I think I mostly understand now. The current implementation actually has a subtle bug, which coincidentally allows it correctly handle the empty file test case! Consider the following toy example in Py 3.6:

class A(list):
    it = iter([0])
    def __init__(self):
        while True:
            self.append(next(self.it))

class B(list):
    it = iter([0])
    def __init__(self):
        while True:
            try:
                self.append(next(self.it))
            except StopIteration:
                return

def wrapper(MyClass):
    lst = MyClass()
    print('lst', lst)
    for item in lst:
        print('iterating')
        yield item

print('A...')
print(list(wrapper(A)))
print('\nB...')
print(list(wrapper(B)))

Outputs:

A...
[]

B...
lst [0]
iterating
[0]

For A, the output is wrong, it always produces an empty list. However, for the test case we always want an empty iterable here so it works by accident. For B the output is correct in the sense that the wrapper function doesn't prematurely terminate, but in our test case this fails because no-one thought to handle the empty file case I assume.

So if I'm right then refactoring the code into a for loop should lead to the same KeyError? @jgreener64

@peterjc Is that clear? I think the solution is either exclude the relevant formats from the test cases here if empty files are not allowed, or by addressing the KeyError if empty files are allowed?

@peterjc

peterjc commented Oct 29, 2018

Copy link
Copy Markdown
Member

That sounds sensible @chris-rands.

@StefansM Should the CIF formats added to SeqIO in #1635 accept empty files as meaning no sequence (like FASTA files), or an error (like an XML format)?

@StefansM

Copy link
Copy Markdown
Contributor

I don't think that empty mmCIF files make any sense. It's been a while since I took a proper look at the spec, but I think valid mmCIF files must contain at least a data_ block.

I think MMCIF2Dict should raise an exception (probably a ValueError, or some subclass EmptyFileEncounteredError or similar) when it encounters a file with no tokens. While we're at it, I think that PDBParser should do the same. In the meantime, adding the cif-* parsers to the whitelist in test_SeqIO makes sense to me.

@jgreener64

Copy link
Copy Markdown
Contributor

Your analysis seems sound @chris-rands but if tokens is empty then the for loop never executes, so I don't think it would throw a KeyError.

@chris-rands
chris-rands requested a review from peterjc as a code owner October 29, 2018 20:41
@chris-rands

chris-rands commented Oct 29, 2018 •

Copy link
Copy Markdown
Contributor Author

@jgreener64 It does raise a KeyError with the for loop suggested as the resulting dict is empty, much like the earlier test failure.

@peterjc @StefansM Hopefully the build passes now, but travis isn't checking Python 3.7 for some reason? Is the added commit sufficient? If we want to add a custom traceback for empty files across various formats and appropriate unit tests, perhaps they could form a separate PR?

@jgreener64

Copy link
Copy Markdown
Contributor

It does raise a KeyError with the for loop suggested as the resulting dict is empty, much like the earlier test failure.

Ah I see, fair enough.

@codecov

codecov Bot commented Oct 29, 2018

Copy link
Copy Markdown

Codecov Report

Merging #1835 into master will increase coverage by 0.04%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1835      +/-   ##
==========================================
+ Coverage   85.41%   85.46%   +0.04%     
==========================================
  Files         301      301              
  Lines       49304    49308       +4     
==========================================
+ Hits        42113    42140      +27     
+ Misses       7191     7168      -23
Impacted Files Coverage Δ
Bio/PDB/MMCIF2Dict.py 100% <100%> (ø) ⬆️
Bio/SeqIO/PdbIO.py 95.68% <0%> (+0.03%) ⬆️
Bio/PDB/PDBParser.py 89.83% <0%> (+1.69%) ⬆️
Bio/motifs/matrix.py 81.13% <0%> (+5.16%) ⬆️

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 e041090...db48081. Read the comment docs.

@peterjc

peterjc commented Oct 30, 2018

Copy link
Copy Markdown
Member

TravisCI does not currently have Python 3.7 available, but we are using it on AppVeyors (Windows).

@peterjc
peterjc merged commit 868b63d into biopython:master Oct 30, 2018
@chris-rands
chris-rands deleted the testRuntimeErrorFix branch October 30, 2018 10:00
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.

4 participants