Skip to content

Update of CodonTable - #1501

Merged
peterjc merged 5 commits into
biopython:masterfrom
MarkusPiotrowski:D401_data
Feb 23, 2018
Merged

peterjc merged 5 commits into
biopython:masterfrom
MarkusPiotrowski:D401_data

Conversation

@MarkusPiotrowski

@MarkusPiotrowski MarkusPiotrowski commented Jan 9, 2018 •

Copy link
Copy Markdown
Contributor
  • Small changes in update_ncbi_codon_table.py to give a PEP8 compliant output
  • Added codon tables 27 - 31 in Bio.Data.CodonTable.py (and some coding style issues)
  • Removed a bunch of assert statements in Bio.Data.Codon.Table.py. They were moved to test_CodonTable.py
  • Complete re-write of test_CodonTable.py to use the unittest framework. Added tests for each codon table.
  • Small change in Seq.py to raise a warning or exception when codon tables with 'dual coding' stop codons are used (see NCBI Genetic Code Tables 27 to 31 + ambiguous codons #1224). The use of such tables during translation will generally raise a BiopythonWarning. If to_stop=True a ValueError is raised.
  • Small update in test_Seq.py to include these cases.
  • Small update in NEWS.rst for the addition of the new codon tables.

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 am happy be thanked by name in the NEWS.rst and CONTRIB.rst files,
and have added myself to those files as part of this pull request.

@MarkusPiotrowski

MarkusPiotrowski commented Jan 9, 2018 •

Copy link
Copy Markdown
Contributor Author

@peterjc Can we turn off W503? PEP8 allows line breaks after and before binary operators and in fact it recommends line breaks before:

Following the tradition from mathematics usually results in more readable code:

# Yes: easy to match operators with operands
ncome = (gross_wages
        + taxable_interest
        + (dividends - qualified_dividends)
        - ira_deduction
        - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

Knuth's style here means: line break before the binary operator
See also here: https://bugs.python.org/issue26763 and python/peps#186

Comment thread Scripts/update_ncbi_codon_table.py Outdated

def line_wrap(text, indent=0, max_len=78):
def line_wrap(text, indent=0, max_len=78, string=False):
"""Return a wrapped line if lenght is larger max_len."""

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.

Typo (lenght)

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.

Also might be worth expanding the docstring to explain the use of the new string argument - I can see you use this to split string arguments over multiple lines, but it would only work if the strings are single quote delimited.

(The implementation is fine given it is specific to this helper script, but making this more explicit seems safer for future users of this code.)

# Start of auto-generated output from Scripts/update_ncbi_codon_table.py #
##########################################################################

"""[1:])

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.

Personally I found the five separate print statements clearer, but don't have a strong view on this change.

Comment thread Bio/Seq.py Outdated
>>> translate(coding_dna3, table=27) # Table 27: TGA -> STOP or W
'MARKW'

It will howver raise a BiopythonWarning (not shown)

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.

Typo (howver)

Comment thread NEWS.rst Outdated
The restriction enzyme list in Bio.Restriction has been updated to the
November 2017 release of REBASE.

New codon tables 27-31 from NCBI were added to Bio.Data.CodonTable.

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.

Also mention these include some codons with unambiguous bases which can dependent on context encode an amino acid or a stop codon?

@peterjc

peterjc commented Jan 10, 2018

Copy link
Copy Markdown
Member

You actually add all the missing tables 27-31, which is good. I've noted some minor things like typos, otherwise this looks fine.

Good work on reworking the test suite. Personally I would have split that into a second commit (making it easier to test the functional changes vs the test changes), but I take it you have confirmed the old tests still pass?

@peterjc peterjc left a comment

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.

After the conversion to a proper unit test, you also need to remove Tests/output/test_CodonTable from the old print-and-compare test.

(See also the couple of typos I noted, and suggestion to document the string argument in the line wrapping function).

@MarkusPiotrowski

Copy link
Copy Markdown
Contributor Author

@peterjc Thank you, I will do the required changes. Regarding the tests, I think I included all the test from the old file in the new version. To be sure I will run the old testfile on this branch (I did in the beginning, but not at the final stage).

I also mailed to the e-mail list, asking for opinions how to deal with the problematic tables.

Do you have an opinion regarding W503? As mentioned above I think we should turn it off, it violates the true meaning of PEP8 regarding line breaks for dual operators.

@peterjc

peterjc commented Jan 10, 2018 •

Copy link
Copy Markdown
Member

I am sympathetic to line breaks before binary operators, and would be happy to adopt W504 in place of W503 to enforce this - but that is not yet merged into pydocstyle/flake8:

PyCQA/pycodestyle#502

Given W503 is now not on the default pydocstyle ignore list, and not compatible with the updated PEP8, I am happy for us to ignore it. Please update Bio/.flake8 as part of this pull request (as a separate commit).

Update: Confusingly flake8 does have W504, even if pycodestyle does not.
https://gitlab.com/pycqa/flake8/issues/397

@MarkusPiotrowski

Copy link
Copy Markdown
Contributor Author

@peterjc +1 for agreeing to ignore W503. However, we need to do this separately, otherwise this PR will always fail the style checks on TravisCI ...

@peterjc

peterjc commented Jan 10, 2018

Copy link
Copy Markdown
Member

Sure, we can ignore W503 as its own PR (and merge that quickly), that's probably a better plan.

@peterjc

peterjc commented Jan 11, 2018

Copy link
Copy Markdown
Member

Cross reference pull request #1503

@MarkusPiotrowski

Copy link
Copy Markdown
Contributor Author

That's strange, obviously Python 2 has problems with line continuation in doctests?

Failed example:
    translate(coding_dna3, table=27, to_stop=True)
Expected:
    Traceback (most recent call last):
       ...
    ValueError: This table contains at least one stop codon ('TGA') which codes
    for both 'STOP' and an amino acid ('W'). You can not use 'to_stop=True'
    with this table.
Got:
    Traceback (most recent call last):
      File "/opt/python/pypy-5.7.1/lib-python/2.7/doctest.py", line 1315, in __run
        compileflags, 1) in test.globs
      File "<doctest Bio.Seq.translate[14]>", line 1, in <module>
        translate(coding_dna3, table=27, to_stop=True)
      File "/home/travis/build/biopython/biopython/build/lib.linux-x86_64-2.7/Bio/Seq.py", line 2574, in translate
        gap=gap)
      File "/home/travis/build/biopython/biopython/build/lib.linux-x86_64-2.7/Bio/Seq.py", line 2399, in _translate_str
        .format(codon, forward_table[codon]))
    ValueError: This table contains at least one stop codon ('TGA') which codes for both 'STOP' and an amino acid ('W'). You can not use 'to_stop=True' with this table.

I ran Seq.py both from within IDLE and from the commandline under Python 2.7.14 without problems.

I'm going to use ELLIPSIS

@codecov

codecov Bot commented Jan 12, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #1501 into master will increase coverage by 0.05%.
The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #1501      +/-   ##
==========================================
+ Coverage   84.79%   84.84%   +0.05%     
==========================================
  Files         323      323              
  Lines       49398    49383      -15     
==========================================
+ Hits        41885    41901      +16     
+ Misses       7513     7482      -31
Impacted Files Coverage Δ
Bio/Seq.py 98.48% <100%> (+0.01%) ⬆️
Bio/Data/CodonTable.py 97.89% <100%> (+9.98%) ⬆️

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 ffa934b...3736a4e. Read the comment docs.

@peterjc

peterjc commented Jan 12, 2018

Copy link
Copy Markdown
Member

If ellipsis doesn't work, just put the very long line directly in the doctest - crude but effective?

@peterjc

peterjc commented Jan 12, 2018

Copy link
Copy Markdown
Member

@bow bow left a comment

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.

@MarkusPiotrowski The changes look good! I have two comments: one for the code style and another for a (seemingly) remote but not impossible case.

Comment thread Scripts/update_ncbi_codon_table.py Outdated
version = ''
for line in open("gc.prt").readlines():
if not version and line.startswith("-- Version"):
version = line.split('Version')[1].strip()

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.

How likely is it that Version occurs more than once? I've found it is often better to be explicit with the number of expected split()s. In this case, if we only expect it once, I think simply doing .split('Version', 1) makes the code more robust.

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.

OK

Comment thread Bio/Seq.py Outdated
BiopythonWarning)
break
except KeyError:
pass # KeyError is the expected behaviour for most tables

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.

This may be more of a style thing, but I often feel that except <Exception>: pass can be better rewritten to convey intent.

How about something like this?

for codon in stop_codons:
    if codon not in forward_table:
        continue
    if to_stop:
        <raise exception>
    <warn>

We can even remove the continue clause:

for codon in {c for c in stop_codons if c in forward_table}:
    if to_stop:
        <raise exception>
    <warn>

This would raise the exception on the first ambiguous codons if to_stop is True, but would raise warnings for all the ambiguous codons otherwise.

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.

A wrong understanding of 'EAFP' from my side. I take you second approach, but adding a break, otherwise the warning may be raised several times for the same codon table.

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.

Unfortunately, this doesn't work. codon in forward_table gives a TypeError for ambiguous tables, while forward_table[codon] works nicely (either returning an amino acid or raising a KeyError, as expected).
I don't know if this is a bug or intended, the __getitem__ method in AmbiguousForwardTable is quite complex...
So if you don't insist, I would let it as it is.
Example:

>>> from Bio.Data import CodonTable
>>> table = CodonTable.ambiguous_dna_by_id[1]
>>> table.forward_table['ATG']
'M'
>>> 'ATG' in table.forward_table

Traceback (most recent call last):
  File "<pyshell#61>", line 1, in <module>
    'ATG' in table.forward_table
  File "C:\Program Files\Anaconda32\lib\site-packages\Bio\Data\CodonTable.py", line 375, in __getitem__
    self.ambiguous_nucleotide)
  File "C:\Program Files\Anaconda32\lib\site-packages\Bio\Data\CodonTable.py", line 209, in list_possible_proteins
    c1, c2, c3 = codon
TypeError: 'int' object is not iterable

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.

Aha, I had thought earlier forward_table should behave like a plain dict. That is apparently not the case.

The error we're seeing is because forward_table (or rather, its class) doesn't define a __contains__ method, which makes the in operation resort to using __getitem__ but using integers instead of ATG.

Without an expected __contains__ behavior, I can understand that the exception <E>: pass style is the one that does what we want ~ so let's keep it that way for now.

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.

Given it is dictionary like, do you think is the expected behaviour of the missing __contains__method clearly defined? If so we could add it?

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.

I'm thinking about adding it. I'll see how it works

@MarkusPiotrowski

MarkusPiotrowski commented Jan 18, 2018 •

Copy link
Copy Markdown
Contributor Author

That was a bit too quick, lookups which return TranslationError should probably also give a positive membership testing. These are cases where ambiguous codons can either code for amino acid and STOP or code for several amino acids but there is no letter for this combination of amino acids. With my current implementation, 'xxx' in forward_table will return False in these cases (which always allows you to do if 'xxx' in forward_table: return forward_table['xxx'] without raising an error). However, since these codons do code for amino acids (but can't be translated for some reason) ['xxx'] in forward_table should probably return True (even if forward_table['xxx'] would then raise a TranslationError). Of course this should then be mentioned in the docstring of the ___contains___.
@peterjc @bow Your view?

@peterjc

peterjc commented Jan 18, 2018

Copy link
Copy Markdown
Member

Some of the past design choices were likely practical for implementation (e.g. the X fall back for traditionally ambiguous codons where it could be several amino acids)

@bow

bow commented Jan 18, 2018

Copy link
Copy Markdown
Member

I feel the latest change is ok as is. If 'xxx' in forward_table returns True, then it's more intuitive to have forward_table['xxx'] return an actual value rather than raise an exception, despite the more nuanced interpretation that 'xxx' codes for an amino acid but can not be translated somehow.

If we ever want to tackle these corner cases, I don't think making the codon table behave as if it were a dict is the way to go. Instead we just treat it as a simple container object without __getitem__ or get, that maybe has its own get_amino_acid is better. We could also still make it like a dict, but instead of ever raising a TranslationError, instead we either return values that mean the AA translation is known or unknown (so the in operator evaluating to True would still mean forward_table[_] always return a value).

But these feel like overengineering ~ I'm happy with the latest changes as is.

@MarkusPiotrowski

Copy link
Copy Markdown
Contributor Author

@peterjc Sorry, I don't understand your last comment.

@peterjc

peterjc commented Jan 23, 2018

Copy link
Copy Markdown
Member

@MarkusPiotrowski I meant it took me a while to understand the codon tables, and when they did and didn't raise a KeyError. For reference, this was originally used in Bio.Translate, which we deprecated and removed in Biopython 1.57, last release here:

https://github.com/biopython/biopython/blob/biopython-156/Bio/Translate.py

Comment thread Bio/Seq.py Outdated
"Such codons will be translated as amino acid."
.format(codon, forward_table[codon]),
BiopythonWarning)
break

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 had to study this for loop with the break some time to understand what it does. How about something like:

dual_coding = [c for c in stop_codons if c in forward_table]
if dual_coding:
    if to_stop:
        raise ValueError("You cannot use 'tostop=True' with this table as it "
                         "contains %i codons which can be both stop and an "
                         "amino acid." % len(dual_coding))
    warnings.warn("This table contains %i codons which code for both "
                  "stop and an amino acid. Such codons will be translated ",
                  "as the amino acid." % len(dual_coding), BiopythonWarning)

(You could equally use c = dual_coding[0] and keep the existing proposed messages, which are helpfully explicit with an example codon)

@peterjc

peterjc commented Feb 23, 2018

Copy link
Copy Markdown
Member

Sorry, I forgot about this. Thanks for that final polish.

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.

3 participants