File: _protein.py

package info (click to toggle)
python-skbio 0.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 9,312 kB
  • sloc: python: 60,482; ansic: 672; makefile: 224
file content (299 lines) | stat: -rw-r--r-- 9,660 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# ----------------------------------------------------------------------------

import numpy as np

from skbio.util._decorator import classproperty, overrides
from ._grammared_sequence import GrammaredSequence, _motifs as parent_motifs


class Protein(GrammaredSequence):
    r"""Store protein sequence data and optional associated metadata.

    Parameters
    ----------
    sequence : str, Sequence, or 1D np.ndarray (np.uint8 or '\|S1')
        Characters representing the protein sequence itself.
    metadata : dict, optional
        Arbitrary metadata which applies to the entire sequence.
    positional_metadata : Pandas DataFrame consumable, optional
        Arbitrary per-character metadata. For example, quality data from
        sequencing reads. Must be able to be passed directly to the Pandas
        DataFrame constructor.
    interval_metadata : IntervalMetadata
        Arbitrary interval metadata which applies to intervals within
        a sequence to store interval features (such as protein domains).
    lowercase : bool or str, optional
        If ``True``, lowercase sequence characters will be converted to
        uppercase characters in order to be valid IUPAC Protein characters. If
        ``False``, no characters will be converted. If a str, it will be
        treated as a key into the positional metadata of the object. All
        lowercase characters will be converted to uppercase, and a ``True``
        value will be stored in a boolean array in the positional metadata
        under the key.
    validate : bool, optional
        If ``True``, validation will be performed to ensure that all sequence
        characters are in the IUPAC protein character set. If ``False``,
        validation will not be performed. Turning off validation will improve
        runtime performance. If invalid characters are present, however, there
        is **no guarantee that operations performed on the resulting object
        will work or behave as expected.** Only turn off validation if you are
        certain that the sequence characters are valid. To store sequence data
        that is not IUPAC-compliant, use ``Sequence``.

    See Also
    --------
    GrammaredSequence

    Notes
    -----
    According to the IUPAC notation [1]_ , a protein sequence may contain the
    following 20 definite characters (canonical amino acids):

    +-----+---------+--------------+
    |Code |3-letter |Amino acid    |
    +=====+=========+==============+
    |``A``|Ala      |Alanine       |
    +-----+---------+--------------+
    |``C``|Cys      |Cysteine      |
    +-----+---------+--------------+
    |``D``|Asp      |Aspartic acid |
    +-----+---------+--------------+
    |``E``|Glu      |Glutamic acid |
    +-----+---------+--------------+
    |``F``|Phe      |Phenylalanine |
    +-----+---------+--------------+
    |``G``|Gly      |Glycine       |
    +-----+---------+--------------+
    |``H``|His      |Histidine     |
    +-----+---------+--------------+
    |``I``|Ile      |Isoleucine    |
    +-----+---------+--------------+
    |``K``|Lys      |Lysine        |
    +-----+---------+--------------+
    |``L``|Leu      |Leucine       |
    +-----+---------+--------------+
    |``M``|Met      |Methionine    |
    +-----+---------+--------------+
    |``N``|Asn      |Asparagine    |
    +-----+---------+--------------+
    |``P``|Pro      |Proline       |
    +-----+---------+--------------+
    |``Q``|Gln      |Glutamine     |
    +-----+---------+--------------+
    |``R``|Arg      |Arginine      |
    +-----+---------+--------------+
    |``S``|Ser      |Serine        |
    +-----+---------+--------------+
    |``T``|Thr      |Threonine     |
    +-----+---------+--------------+
    |``V``|Val      |Valine        |
    +-----+---------+--------------+
    |``W``|Trp      |Tryptophan    |
    +-----+---------+--------------+
    |``Y``|Tyr      |Tyrosine      |
    +-----+---------+--------------+

    And the following four degenerate characters, each of which representing
    two or more amino acids:

    +-----+---------+------------+
    |Code |3-letter |Amino acids |
    +=====+=========+============+
    |``B``|Asx      |D or N      |
    +-----+---------+------------+
    |``Z``|Glx      |E or Q      |
    +-----+---------+------------+
    |``J``|Xle      |I or L      |
    +-----+---------+------------+
    |``X``|Xaa      |All 20      |
    +-----+---------+------------+

    Plus one stop character: ``*`` (Ter), and two gap characters: ``-`` and ``.``.

    Characters other than the above 27 are not allowed. If you intend to use
    additional characters to represent non-canonical amino acids, such as ``U``
    (Sec, Selenocysteine) and ``O`` (Pyl, Pyrrolysine), you may create a custom
    alphabet using ``GrammaredSequence``. Directly modifying the alphabet of
    ``Protein`` may break functions that rely on the IUPAC alphabet.

    It should be noted that some functions do not support certain characters.
    For example, the BLOSUM and PAM substitution matrices do not support ``J``
    (Xle). In such circumstances, unsupported characters will be replaced with
    ``X`` to represent any of the canonical amino acids.

    References
    ----------
    .. [1] Nomenclature for incompletely specified bases in nucleic acid
       sequences: recommendations 1984.
       Nucleic Acids Res. May 10, 1985; 13(9): 3021-3030.
       A Cornish-Bowden

    Examples
    --------
    >>> from skbio import Protein
    >>> Protein('PAW')
    Protein
    --------------------------
    Stats:
        length: 3
        has gaps: False
        has degenerates: False
        has definites: True
        has stops: False
    --------------------------
    0 PAW

    Convert lowercase characters to uppercase:

    >>> Protein('paW', lowercase=True)
    Protein
    --------------------------
    Stats:
        length: 3
        has gaps: False
        has degenerates: False
        has definites: True
        has stops: False
    --------------------------
    0 PAW

    """

    __stop_codes = None

    @classproperty
    def _stop_codes(cls):
        if cls.__stop_codes is None:
            stops = cls.stop_chars
            cls.__stop_codes = np.asarray([ord(s) for s in stops])
        return cls.__stop_codes

    @classproperty
    @overrides(GrammaredSequence)
    def alphabet(cls):
        return super(Protein, cls).alphabet | cls.stop_chars

    @classproperty
    @overrides(GrammaredSequence)
    def definite_chars(cls):
        return set("ACDEFGHIKLMNOPQRSTUVWY")

    @classproperty
    @overrides(GrammaredSequence)
    def noncanonical_chars(cls):
        return set("OU")

    @classproperty
    @overrides(GrammaredSequence)
    def degenerate_map(cls):
        return {
            "B": set("DN"),
            "Z": set("EQ"),
            "J": set("IL"),
            "X": set("ACDEFGHIKLMNOPQRSTUVWY"),
        }

    @classproperty
    def stop_chars(cls):
        """Return characters representing translation stop codons.

        Returns
        -------
        set
            Characters representing translation stop codons.

        """
        return set("*")

    @classproperty
    @overrides(GrammaredSequence)
    def gap_chars(cls):
        return set("-.")

    @classproperty
    @overrides(GrammaredSequence)
    def default_gap_char(cls):
        return "-"

    @classproperty
    @overrides(GrammaredSequence)
    def wildcard_char(cls):
        return "X"

    @property
    def _motifs(self):
        return _motifs

    def stops(self):
        """Find positions containing stop characters in the protein sequence.

        Returns
        -------
        1D np.ndarray (bool)
            Boolean vector where ``True`` indicates a stop character is present
            at that position in the protein sequence.

        See Also
        --------
        has_stops

        Examples
        --------
        >>> from skbio import Protein
        >>> s = Protein('PAW')
        >>> s.stops()
        array([False, False, False], dtype=bool)
        >>> s = Protein('PAW*E*')
        >>> s.stops()
        array([False, False, False,  True, False,  True], dtype=bool)

        """
        return np.in1d(self._bytes, self._stop_codes)

    def has_stops(self):
        """Determine if the sequence contains one or more stop characters.

        Returns
        -------
        bool
            Indicates whether there are one or more occurrences of stop
            characters in the protein sequence.

        Examples
        --------
        >>> from skbio import Protein
        >>> s = Protein('PAW')
        >>> s.has_stops()
        False
        >>> s = Protein('PAW*E*')
        >>> s.has_stops()
        True

        """
        return bool(self.stops().any())

    @overrides(GrammaredSequence)
    def _repr_stats(self):
        """Define custom statistics to display in the sequence's repr."""
        stats = super(Protein, self)._repr_stats()
        stats.append(("has stops", "%r" % self.has_stops()))
        return stats


_motifs = parent_motifs.copy()


@_motifs("N-glycosylation")
def _motif_nitro_glycosylation(sequence, min_length, ignore):
    """Identify N-glycosylation runs."""
    return sequence.find_with_regex("(N[^PX][ST][^PX])", ignore=ignore)


# Leave this at the bottom
_motifs.interpolate(Protein, "find_motifs")