Skip to content

Enforce alphabet letters in Seq objects #1040

Closed

Description

@peterjc

Migrating from old RedMine issue https://redmine.open-bio.org/issues/2597 which I originally opened in September 2008

If a Seq object is created with an alphabet with a pre-defined set of letters (e.g. the IUPAC alphabets) then > I think Biopython should validate that the sequence does indeed only use those letters.

This will catch mis-use of ambiguous sequences with non-ambiguous alphabets, letters in an unexpected > case, and most importantly any unexpected symbols (e.g. from a parsing problem).

This will impose a performance overhead - which can be avoided if the user instead chooses to use a generic dna/rna/protein alphabet which does not list the letters expected.

Note that we will have to resolve Bug 2532 before doing this, as currently some parts of Biopython are mis-using the upper case only IUPAC alphabet objects with mixed case sequences.

I then attached a patch with comment:

Patch for Bio/Seq.py to check the alphabet letters

This is a simple approach to checking the letters - probably not the fastest. I think it is important that the exception gives some clue about why the Seq object was not created - either listing the first invalid character (as in this patch) or listing all invalid characters (which could be done using sets).

On the other hand, I'd like this check to be as fast as possible - perhaps even at the cost of a generic exception message like "Sequence contains letters which are not valid for the given alphabet".

Another comment from me on the old issue:

As recently noted on the mailing list, making the Seq alphabet check strict could be useful for file format validation with Bio.SeqIO or Bio.AlignIO, since the parse and read functions can be given an alphabet.

e.g. While this would be allowed:

from Bio import SeqIO
from Bio.Alphabet.IUPAC import extended_protein
from Bio.Alphabet import Gapped
from StringIO import StringIO
fasta_str = "\n\n\n>ID\nABCDEFGH-IPX\n" 
record = SeqIO.read(StringIO(fasta_str), "fasta", Gapped(extended_protein, "-"))

If the Seq object checked the alphabet letters, this would fail due to the minus sign:

record = SeqIO.read(StringIO(fasta_str), "fasta", extended_protein)

If the user doesn't care about the precise letters, they can use the default generic alphabet, e.g.

record = SeqIO.read(StringIO(fasta_str), "fasta")

or, to at least specify this is a protein sequence:

from Bio.Alphabet import generic_protein
record = SeqIO.read(StringIO(fasta_str), "fasta", generic_protein)

And comment from @etal

It would also be useful to be able to validate alphabets when constructing Seqs or SeqRecords from scratch.

Here's a proposal that I believe fits with most of what's been agreed to so far.

In Bio/Alphabet/init.py, replace _verify_alphabet with an efficiently implemented method on the Alphabet class and perhaps make it public:

def validate(self, sequence):
    """Raise a ValueError if sequence contains letters not allowed by alphabet.

    If alphabet does not define letters, it's all OK.
    ...
    """ 
    ok_letters = set(self.letters)
    if ok_letters:
        bad_letters = set(str(sequence)) - ok_letters
        if bad_letters:
            raise ValueError("Alphabet does not accept these letters: " 
                             + ''.join(bad_letters))

In the Seq class, optionally add a method 'check_alphabet' which wraps Alphabet.validate:

def check_alphabet(self):
    self.alphabet.validate(self.data)

In SeqIO.parse and SeqIO.read, add an option check_alphabet=False, which calls either Alphabet.validate(seq) or seq.check_alphabet(). If validation fails, the exception is propagated up.

I don't know how much this would affect performance, but it seems that users are willing to accept a small performance hit if they explicitly opt into validation. The extra 'if' statement may or may not be noticeable in the default case.

Activity

  1. souravsingh commented on Apr 26, 2017

    @souravsingh
    Contributor

    I think there is a patch for this issue.

  2. peterjc commented on Apr 26, 2017

    @peterjc
    MemberAuthor

    Yes, the original patch I attached to bugzilla was:

    Index: Seq.py
    ===================================================================
    RCS file: /home/repository/biopython/biopython/Bio/Seq.py,v
    retrieving revision 1.61
    diff -r1.61 Seq.py
    63c63,67
    < 
    ---
    >         if alphabet.letters :
    >             for letter in data :
    >                 if letter not in alphabet.letters :
    >                     raise ValueError("Letter %s not in %s" \
    >                                      % (repr(letter), repr(alphabet)))
    
  3. souravsingh commented on Apr 26, 2017

    @souravsingh
    Contributor

    Reading through the comments in bugzilla, I think the patch is working well. The issue can be closed if the patch is submitted, right?

  4. peterjc commented on Apr 26, 2017

    @peterjc
    MemberAuthor

    The code in that patch was the easy part. The hard part is should we add this? It would impose a speed overhead which would affect all the sequence parsers, which for FASTA and FASTQ are already slow in comparison to a string-based approach due to all the object overhead.

    Also, this is part of a larger more complex discussion about the design and direction of the alphabet support in Biopython. None of the currently active developers likes the current alphabet system which has many faults, so adding to it seems like a bad idea. If anything I think the consensus is to simplify the current model, but no one has been able to set aside time to put together a proposal or proof of principle for how to do this with minimum breakage of existing code. And personally, I would prioritise other things like improving our test coverage.

  5. kescobo commented on Jun 5, 2017

    @kescobo

    Coming here from mailing list issue - is there a way to (without dramatically increasing overhead) add something to an error message that gets spit when alphabets collide that points people to potential solutions?

  6. peterjc commented on Jun 5, 2017

    @peterjc
    MemberAuthor

    @kescobo Which error message? The one I was proposing adding Letter X not in XXX?

  7. kescobo commented on Jun 5, 2017

    @kescobo

    @peterjc Not sure - I haven't run into this problem before, but yes, Letter X not in XXX is a useful starting point for sure.

  8. mivade commented on May 3, 2019

    @mivade

    I found this issue while trying to understand why I can get away with nonsensical things like

    seq = Seq("afheilsafhielsaf", DNAAlphabet())
    seq.reverse_complement()
    Out[13]: Seq('ftsleidftsliedft', DNAAlphabet())

    I understand not wanting to add the overhead of always validating the input string, but can we get a keyword argument or something? It's quite common to have to write one's own validation routine when this kind of functionality should really be built in.

  9. peterjc commented on May 3, 2019

    @peterjc
    MemberAuthor

    Someone who has a use case for the alphabet objects? Note that DNAAlphabet() would be a generic DNA alphabet without a specified list of valid letters. You'd probably want an IUPAC alphabet, although those are currently upper case only - see #1716.

    I couldn't find a general issue on removing/simplifying the alphabet code, so created #2046 with links to other past discussion alluded to above.

  10. peterjc commented on Jul 24, 2020

    @peterjc
    MemberAuthor

    We're dropping Bio.Alphabets (see #2046), so this is moot now.

    Thank you @chebizarro for help with issue triage.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions