Skip to content

ThreeLetterProtein alphabet can be removed? #1681

Closed

Description

@mdehoon

Bio/Alphabet/__init__.py defines a ThreeLetterProtein alphabet consisting of three-letter amino acids:

class ThreeLetterProtein(Alphabet):
    """Three letter protein alphabet."""

    size = 3
    letters = [
        "Ala", "Asx", "Cys", "Asp", "Glu", "Phe", "Gly", "His", "Ile",
        "Lys", "Leu", "Met", "Asn", "Pro", "Gln", "Arg", "Ser", "Thr",
        "Sec", "Val", "Trp", "Xaa", "Tyr", "Glx",
        ]

    def _upper(self):
        raise NotImplementedError("We don't have an uppercase three letter "
                                  "protein alphabet.")

    def _lower(self):
        raise NotImplementedError("We don't have a lowercase three letter "
                                  "protein alphabet.")

Currently this is only used in Bio/SeqUtils/__init__.py to check if a Seq object has this alphabet:

$ grep -r ThreeLetterProtein *
Bio/SeqUtils/__init__.py:        elif isinstance(base_alphabet, Alphabet.ThreeLetterProtein):
Bio/Alphabet/__init__.py:class ThreeLetterProtein(Alphabet):
    if isinstance(seq, (Seq, MutableSeq)):
        base_alphabet = Alphabet._get_base_alphabet(seq.alphabet)
...
        elif isinstance(base_alphabet, Alphabet.ThreeLetterProtein):

but I don't see how a Seq object can have such an alphabet in a meaningful way:

>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import ThreeLetterProtein
>>> seq = Seq(["Arg"], ThreeLetterProtein())
...
TypeError: The sequence data given to a Seq object should be a string (not another Seq object etc)

and if we pass the sequence as a single string:

>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import ThreeLetterProtein
>>> seq = Seq("Arg", ThreeLetterProtein())

then indexing doesn't work correctly:

>>> seq[0]
'A'
# our alanine has become an arginine

I guess that the ThreeLetterProtein is a leftover from the past, and can be removed.

Activity

  1. peterjc commented on Jun 7, 2018

    @peterjc
    Member

    From memory it works with MutableSeq (array based) but not Seq (string based and therefore only for single-letter alphabets), but I don't see this being used in the test suite which puzzles me. I thought the GA code might have used this...

    CC @MarkusPiotrowski as we had some discussion about three-letter alphabet use in pairwise2 not that long ago.

  2. mdehoon commented on Jun 7, 2018

    @mdehoon
    ContributorAuthor

    @peterjc It is possible to use a three-letter alphabet with MutableSeq, but it's super fragile:

    >>> from Bio.Seq import MutableSeq
    >>> from Bio.Alphabet import ThreeLetterProtein
    >>> seq = MutableSeq(["Arg"], ThreeLetterProtein())
    >>> seq[0]
    'Arg'
    >>> seq = seq.toseq()
    >>> seq
    Seq('Arg', ThreeLetterProtein())
    >>> seq[0]
    'A'

    turning our arginine into alanine again.

  3. peterjc commented on Jun 7, 2018

    @peterjc
    Member

    You're making a strong case for either deprecating and removing ThreeLetterProtein, or that it needs some love and attention to fix it - or at least make it less broken.

    On the bright side, the recently added multiplication support seems to work fine:

    >>> from Bio.Seq import MutableSeq
    >>> from Bio.Alphabet import ThreeLetterProtein
    >>> seq = MutableSeq(["Arg"], ThreeLetterProtein())
    >>> seq
    MutableSeq('Arg', ThreeLetterProtein())
    >>> seq * 4
    MutableSeq('ArgArgArgArg', ThreeLetterProtein())
    >>> seq *= 4
    >>> seq
    MutableSeq('ArgArgArgArg', ThreeLetterProtein())
    >>> seq[0]
    'Arg'

    Given our agreed long term goal of making the Seq object (and by extension the other Seq-like objects) more like the Python string, removing this seems simpler.

  4. peterjc commented on Jun 7, 2018

    @peterjc
    Member

    One of the first fixes should be to the MutableSeq's __repr__ method to show using arrays, unless it is a single character alphabet where a string-like representation is OK.

    Another fix worth considering would be to reject a three-letter-alphabet in Seq's __init__ method. That would mean clear failures on things like mutable_seq.toseq() which as in the examples above silently corrupts the data.

  5. mdehoon commented on Jun 8, 2018

    @mdehoon
    ContributorAuthor

    I think MutableSeq should not accept arrays at all. It is undocumented behavior, it's inconsistent with Seq objects, and it lets you put anything into a MutableSeq object:

    >>> from Bio.Seq import MutableSeq
    >>> m = MutableSeq(['A', 'T', 'U', 'Arg', 'Lys', None, 4, 5.0, ('A', 'C')])
    >>> 
    >>> from Bio.Seq import MutableSeq
    >>> m = MutableSeq(3.0)
    >>> 
  6. MarkusPiotrowski commented on Jun 8, 2018

    @MarkusPiotrowski
    Contributor

    Regarding pairwise2: It accepts input of list, so you can use sequences whose elements are not single characters (@mdehoon you probably overread this in one of my messages regarding pairwise2 and aligner) E.g. one user wanted to align sequences that contained modified bases like N97 or 8DX. This is possible with pairwise2 (@peterjc and would also give a nice looking alignment once we merged #1505).
    So you could use three letter protein sequences with pairwise2 when you apply them as lists. This will not work with the current Seq objects, because they return strings, even when you have used a list to make the object.

  7. mdehoon commented on Jun 8, 2018

    @mdehoon
    ContributorAuthor

    @MarkusPiotrowski To use lists as input for pairwise2, I guess you don't need the ThreeLetterProtein alphabet?

  8. MarkusPiotrowski commented on Jun 8, 2018

    @MarkusPiotrowski
    Contributor

    Regarding the ThreeLetterProtein alphabet I would be in favour of fixing of the bugs. I mean, a three letter protein alphabet can be useful, e.g. for a three letter translation (a feature that all sequence editor programs contain). And we may also see the time, when a 26 letter alphabet is not longer enough to represent all possible members of the molecule group, think of methylated bases, artificial molecules like PNAs, naturally occuring or artificially modified amino acids, etc.
    Having said this, is a list support in sequence objects something one should think of?
    I know, this is against the agreed aim to make sequences more string-like. My personal view is that sequence objects should be nearer to the biological molecule they represent, e.g. shouldn't they have additional attributes like "circular" or "single stranded"? However, I'm not a professional bioinformatician, just a plant biologist who likes programming, so my view is from a different angle.

  9. MarkusPiotrowski commented on Jun 8, 2018

    @MarkusPiotrowski
    Contributor

    @mdehoon pairwise2 and ThreeLetterProtein alphabet: No, you don't need it and you can't use it, because the Seq object will represent the sequence as a string. If the seq object would return a list (in case of alphabets where the members are not single characters), you could use them.

  10. chris-rands commented on Jun 8, 2018

    @chris-rands
    Contributor

    Regarding the inputs accepted for MutableSeq, I think it should accept arrays as it does currently, because if it doesn't this will break the more efficient integer multiplication methods Peter and I just implemented.

    But perhaps MutableSeq could also perform some additional isinstance check in __init__ (like Seq does). The current the assumption that input is either a string or array is not robust. As mdehoon says currently MutableSeq accepts anything and clearly this makes no sense for some types, like integers:

    >>> from Bio.Seq import MutableSeq
    >>> seq = MutableSeq(1)
    >>> seq
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/home/cegg/rands/.local/lib/python3.6/site-packages/Bio/Seq.py", line 1836, in __repr__
        if len(self) > 60:
      File "/home/cegg/rands/.local/lib/python3.6/site-packages/Bio/Seq.py", line 1933, in __len__
        return len(self.data)
    TypeError: object of type 'int' has no len()
    >>> 
    
  11. mdehoon commented on Jun 8, 2018

    @mdehoon
    ContributorAuthor

    @MarkusPiotrowski I am aware that pairwise2 can accept lists as input, but that makes the alignment much slower. For example, with a DNA sequence of 200 nucleotides, I am getting these timings:
    Bio.Align.PairwiseAligner (using a string): 4 seconds
    Bio.pairwise2 (using a string): 21 seconds
    Bio.pairwise2 (using a list): 166 seconds
    So I would use a different character for modified bases, and run the alignment using a string as input.
    If the time comes that a 26 letter alphabet is not sufficient, then using arrays of integers will be much faster than using lists.

  12. mdehoon commented on Jun 8, 2018

    @mdehoon
    ContributorAuthor

    @chris-rands It's trivial to fix that without having to accept arrays as input.

  13. chris-rands commented on Jun 8, 2018

    @chris-rands
    Contributor

    @mdehoon Yes the fix would be trivial for integer multiplication like return self.__class__(str(self) * other, self.alphabet) instead of this. However, this would be less efficient that the current implementation working with arrays directly. That might be a worthwhile trade-off to simplify things, you and Peter would know better than me of course!

  14. mdehoon commented on Jun 8, 2018

    @mdehoon
    ContributorAuthor

    @chris-rands You could do

    s = self.__class__('', self.alphabet)
    s.data = self.data * other
    return s
  15. MarkusPiotrowski commented on Jun 8, 2018

    @MarkusPiotrowski
    Contributor

    @mdehoon I think we have (many?) users who use Biopython only occasionally. They have their local sequences/formats, etc. Often they use Biopython for a single task (e.g. alignments) and don't care to much about implementation details. You can of course tell them to convert their sequences into single letters, but isn't 5mC a clearer code than any one-letter abbreviation (are their any official single-letter abbreviations for methylated bases?)? Looking from a naive user perspective, non-single-letter sequences (and accordingly alphabets) would be great. Conversion into memory/speed optimized formats can appear under the hood.

  16. 17 remaining items

  17. peterjc commented on Jun 30, 2018

    @peterjc
    Member

    In that example it would be reasonable to get a TypeError for incompatible alphabets.

  18. mdehoon commented on Jun 30, 2018

    @mdehoon
    ContributorAuthor

    I would expect Biopython to be a bit more intelligent there. Now this example would require something like

    >>> m3_1 = MutableSeq("".join([IUPACData.protein_letters_3to1[aa] for aa in m3]), IUPAC.IUPACProtein())
    >>> m1 + m3_1
    MutableSeq('MVRK', IUPACProtein())

    which is way too complicated.

    Not to mention that this will happen:

    >>> m3 == m3_1
    False
  19. mdehoon commented on Jul 24, 2018

    @mdehoon
    ContributorAuthor

    @MarkusPiotrowski Yesterday I had a chance to meet up with @peterjc , and we discussed the issue of alphabets in Biopython. Because of the complexity of alphabets and their use in Biopython, we felt that it may be a good idea to have a PEP (Python Enhancement Proposal)-like discussion to define the purpose of alphabets and their technical implementation in Biopython. This would mean that somebody who is in favor of having alphabets in Biopython would work out a proposal with all the details to allow developers and users to think through the implications. Since alphabets have been under discussion for more than 10 years, we are thinking to put a time limit to the proposal (e.g., until January 1st, 2020), meaning that if no agreement on the proposal is reached by then, alphabets would be removed from Biopython. This would give people who are in favor of alphabets to make their case, while guaranteeing that a conclusion will be reached (either a well-defined and usable alphabet, or no alphabet) within the next ~1.5 years. Details are up for discussion; I'll post this to the mailing list also to keep everybody informed.

  20. fabianegli commented on Jan 16, 2019

    @fabianegli
    Contributor

    The study of post translational modifications (PTM) is prevalent and we will see an increase of applications that involve sequences with PTMs. The expansion of alphabets and Biopython's ability to cope with them in a straight forward manner is paramount. There are hundreds of PTMs and coding them in multi-letter codes seems to be problematic for some underlying software Biopython uses for alignments.

    Alphabets have long been a pain in the computer world, but it has been mostly alleviated by the use of UTF-8. I propose UTF-8 as Biopythons internal alphabet encoding and consequently to safe sequences as UTF-8 strings. The character space, to the best of my knowledge, is big enough to encode all the known post-translational modifications.

    Did the PEP-like discussion start somewhere? If so it should be linked here.

  21. peterjc commented on Jan 16, 2019

    @peterjc
    Member

    TL;DR - there is no PEP-like proposal for alphabets as yet. Michael wants to remove the currently alphabet objects completely (but bits of the wider codebase still need somewhere to record DNA / RNA / protein), while I lean towards a drastic simplification to just an enum-like type system.

    Technical input from someone wanting to work with modified bases / residues would be welcome. Taking advantage of unicode might work better than 3-letter codes.

    Longer recap:

    Here @mdehoon proposed writing a PEP-like proposal for the alphabets,

    https://mailman.open-bio.org/pipermail/biopython/2018-August/016524.html

    Dear all,

    While sequence objects in Biopython have an associated alphabet, the purpose of alphabets in Biopython is currently not well-defined.
    I can imagine these three interpretations of their purpose:
    To define how the sequence data is stored internally in a Seq object (i.e. what kind of objects are in seq.data);
    To define conceptually what the Seq object contains (e.g. this is a protein, or this is DNA, or this is DNA with or without methylation);
    To define how a Seq object should be presented to the user (e.g. as a single-letter string, a three-letter string, or something else).
    (and there may be others that I have overlooked).

    To justify having alphabets as a part of Biopython, their purpose should be clearly defined.
    Because of the complexity of alphabets and their use in Biopython, we felt that it may be a good idea to have a PEP (Python Enhancement Proposal)-like discussion to define the purpose of alphabets and their technical implementation in Biopython. This would mean that somebody who is in favor of having alphabets in Biopython would work out a proposal with all the details to allow developers and users to think through the implications.

    Here you can find a description of PEPs and what should go in them:

    https://www.python.org/dev/peps/pep-0001/

    Not all of it is applicable to Biopython, but it may serve as a general guideline.

    The Alphabet BEP (Biopython Enhancement Proposal) could be hosted on the Biopython website so that everybody can follow the discussion.
    Since alphabets have been under discussion for more than 10 years, we are thinking to put a time limit to the proposal (e.g., until January 1st, 2020), meaning that if no agreement on the proposal is reached by then, alphabets would be removed from Biopython. This would give people who are in favor of alphabets to make their case, while guaranteeing that a conclusion will be reached (either a well-defined and usable alphabet, or no alphabet) within the next ~1.5 years.

    Any volunteers? Seq objects and therefore their alphabets are a key feature of Biopython, and working through a BEP can give you the opportunity to help design a major part of Biopython.

    Best,
    -Michiel

    The thread continued in October, but there have been no concrete proposals.

    https://mailman.open-bio.org/pipermail/biopython/2018-October/016555.html

    Michiel advocates starting by removing the alphabets:

    https://mailman.open-bio.org/pipermail/biopython/2018-October/016559.html

    Hi Peter,
    To keep things manageable, I would suggest to remove Bio.Alphabet first, before considering to introduce a new system to replace it.
    Also, after removing Bio.Alphabet, we may have a better idea if and how it should be replaced.
    Best,-Michiel

    My most recent reply,

    https://mailman.open-bio.org/pipermail/biopython/2018-October/016560.html

    HI Michiel,

    My point was that something has to replace Bio.Alphabet
    for some of the existing use cases - including various file
    formats in SeqIO and AlignIO which record DNA, RNA
    vs Protein. e.g.

    https://github.com/biopython/biopython/blob/biopython-172/Bio/AlignIO/NexusIO.py#L129
    https://github.com/biopython/biopython/blob/biopython-172/Bio/SeqIO/InsdcIO.py#L613
    https://github.com/biopython/biopython/blob/biopython-172/Bio/SeqIO/SeqXmlIO.py#L348

    This could be a new convention for where to store this
    in the SeqRecord, or as I am currently exploring, a
    simplified alphabet attribute of the Seq object.

    This effort should uncover any other roadblocks to a
    removal or another replacement alphabet system would
    face - and might help with coming up with a better idea.

    Peter

    Removal or simplification to a simple enum type system as on https://github.com/peterjc/biopython/tree/alpha_lite would not in itself help with representing modified bases or residues, where 3-letter codes kind of work in MutableSeq but are not well supported.

    Moving to expressing modified bases or residues using unicode (and in particular UTF8) might work well (it should even allowing emoji in sequences), as this has the enormous positives that each symbol has length one when viewed as a (unicode) string. And we've a long term goal that the Seq object behave more and more like the Python (unicode) string, and ultimately perhaps subclass it.

    This idea could probably be done with the current alphabet objects, or a simplified alphabet type enum, or no alphabet attribute.

  22. mdehoon commented on Jan 18, 2019

    @mdehoon
    ContributorAuthor

    @fabianegli @peterjc
    UTF8 would be slow, because the number of bytes used to store a character varies. Then if s is a Seq object,

    >>> c = s[1000000]

    requires evaluating one million characters to find out where s[1000000] starts.

  23. fabianegli commented on Jan 18, 2019

    @fabianegli
    Contributor

    @mdehoon This is already quite technical. The pros and cons of the use of UTF-8 as sequence encoding are probably better discussed in a new issue. If you care to open one please do so, if none is opened, I should find time to do that within the coming days.

  24. peterjc commented on Jan 18, 2019

    @peterjc
    Member

    Currently on Python 3 the Seq object is using a Python unicode string, so we are implicitly using the system default encoding, i.e. it already is usually stored UTF-8.

    On the bright side, almost all the biological sequences we use currently are plain ASCII, and Python 3 handles those very efficiently as unicode strings - we ought not to need to worry about performance for now.

    If we start dealing with entire chromosomes/genomes with non-ASCII, it might be a problem (e.g. methylation state - but there you could probably still pick an ASCII-IUPAC-DNA + other ASCII character alphabet).

    +1 on opening a new issue for storing non-IUPAC characters using non-ASCII characters available.

  25. mdehoon commented on Jan 21, 2019

    @mdehoon
    ContributorAuthor

    @peterjc As far as I know, Python3 does not use UTF-8 internally.

  26. peterjc commented on Jan 21, 2019

    @peterjc
    Member

    I may have misunderstood something then, or am being imprecise with my language and the terms (unicode, encoding, UTF-8 etc):
    https://docs.python.org/3/howto/unicode.html

  27. peterjc commented on Feb 14, 2019

    @peterjc
    Member

    Somewhat relevant news from the PyPy project, https://twitter.com/pypyproject/status/1095971192513708032

    unicode-utf8 just got merged! Unicode strings are now internally represented as utf-8 in PyPy, with an optional extra index data structure to make indexing O(1). We'll write a blog post about it eventually.

  28. fabianegli commented on Feb 16, 2019

    @fabianegli
    Contributor

    Accessing char at pos x in a string is also O(1) in Python 3 (see https://www.python.org/dev/peps/pep-0393/). Although memory usage for UTF-8 strings is higher than for ASCII. The code point size in Python is fixed - check out wide and narrow builds. This is also the case - to some extent - in the new PyPy, when the additional index is used for the linear time access. Thus I anticipate that, if at all, memory usage is a more serious concern than speed, if it is one at all.

  29. fabianegli commented on Feb 20, 2019

    @fabianegli
    Contributor

    After following this issue and considering the implications of my proposal to use UTF-8 to extended alphabets and encodings for bio-sequences, I am currently setting up a project to investigate this proposal. I chose to make the process public to speed it up and allow stakeholders to influence the project or collaborate. Here is the link to the (still rudimentary) repository: https://github.com/fabianegli/bioenc

  30. peterjc commented on Jul 22, 2020

    @peterjc
    Member

    Closing as part of #2046 - we're now in the process of removing all of Bio.Alphabet now.

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