| 1 |
# Copyright (c) 2005 Gavin E. Crooks <[email protected]> |
| 2 |
# |
| 3 |
# This software is distributed under the MIT Open Source License. |
| 4 |
# <http://www.opensource.org/licenses/mit-license.html> |
| 5 |
# |
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a |
| 7 |
# copy of this software and associated documentation files (the "Software"), |
| 8 |
# to deal in the Software without restriction, including without limitation |
| 9 |
# the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 10 |
# and/or sell copies of the Software, and to permit persons to whom the |
| 11 |
# Software is furnished to do so, subject to the following conditions: |
| 12 |
# |
| 13 |
# The above copyright notice and this permission notice shall be included |
| 14 |
# in all copies or substantial portions of the Software. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 |
# THE SOFTWARE. |
| 23 |
# |
| 24 |
|
| 25 |
|
| 26 |
"""Alphabetic sequences and associated tools and data. |
| 27 |
|
| 28 |
Seq is a subclass of a python string with additional annotation and an alphabet. |
| 29 |
The characters in string must be contained in the alphabet. Various standard |
| 30 |
alphabets are provided. |
| 31 |
|
| 32 |
|
| 33 |
Classes :: |
| 34 |
|
| 35 |
Alphabet -- A subset of non-null ascii characters |
| 36 |
Seq -- An alphabetic string |
| 37 |
SeqList -- A collection of Seq's |
| 38 |
|
| 39 |
Alphabets :: |
| 40 |
|
| 41 |
o generic_alphabet -- A generic alphabet. Any printable ASCII character. |
| 42 |
o protein_alphabet -- IUCAP/IUB Amino Acid one letter codes. |
| 43 |
o nucleic_alphabet -- IUPAC/IUB Nucleic Acid codes 'ACGTURYSWKMBDHVN-' |
| 44 |
o dna_alphabet -- Same as nucleic_alphabet, with 'U' (Uracil) an |
| 45 |
alternative for 'T' (Thymidine). |
| 46 |
o rna_alphabet -- Same as nucleic_alphabet, with 'T' (Thymidine) an |
| 47 |
alternative for 'U' (Uracil). |
| 48 |
o reduced_nucleic_alphabet -- All ambiguous codes in 'nucleic_alphabet' are |
| 49 |
alternative to 'N' (aNy) |
| 50 |
o reduced_protein_alphabet -- All ambiguous ('BZJ') and non-canonical amino |
| 51 |
acids codes ( 'U', Selenocysteine and 'O', Pyrrolysine) in |
| 52 |
'protein_alphabet' are alternative to 'X'. |
| 53 |
o unambiguous_dna_alphabet -- 'ACGT' |
| 54 |
o unambiguous_rna_alphabet -- 'ACGU' |
| 55 |
o unambiguous_protein_alphabet -- The twenty canonical amino acid one letter |
| 56 |
codes, in alphabetic order, 'ACDEFGHIKLMNPQRSTVWY' |
| 57 |
|
| 58 |
Amino Acid Codes:: |
| 59 |
|
| 60 |
Code Alt. Meaning |
| 61 |
----------------- |
| 62 |
A Alanine |
| 63 |
B Aspartic acid or Asparagine |
| 64 |
C Cysteine |
| 65 |
D Aspartate |
| 66 |
E Glutamate |
| 67 |
F Phenylalanine |
| 68 |
G Glycine |
| 69 |
H Histidine |
| 70 |
I Isoleucine |
| 71 |
J Leucine or Isoleucine |
| 72 |
K Lysine |
| 73 |
L Leucine |
| 74 |
M Methionine |
| 75 |
N Asparagine |
| 76 |
O Pyrrolysine |
| 77 |
P Proline |
| 78 |
Q Glutamine |
| 79 |
R Arginine |
| 80 |
S Serine |
| 81 |
T Threonine |
| 82 |
U Selenocysteine |
| 83 |
V Valine |
| 84 |
W Tryptophan |
| 85 |
Y Tyrosine |
| 86 |
Z Glutamate or Glutamine |
| 87 |
X ? any |
| 88 |
* translation stop |
| 89 |
- .~ gap |
| 90 |
|
| 91 |
Nucleotide Codes:: |
| 92 |
|
| 93 |
Code Alt. Meaning |
| 94 |
------------------------------ |
| 95 |
A Adenosine |
| 96 |
C Cytidine |
| 97 |
G Guanine |
| 98 |
T Thymidine |
| 99 |
U Uracil |
| 100 |
R G A (puRine) |
| 101 |
Y T C (pYrimidine) |
| 102 |
K G T (Ketone) |
| 103 |
M A C (aMino group) |
| 104 |
S G C (Strong interaction) |
| 105 |
W A T (Weak interaction) |
| 106 |
B G T C (not A) (B comes after A) |
| 107 |
D G A T (not C) (D comes after C) |
| 108 |
H A C T (not G) (H comes after G) |
| 109 |
V G C A (not T, not U) (V comes after U) |
| 110 |
N X? A G C T (aNy) |
| 111 |
- .~ A gap |
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
Refs: |
| 117 |
http://www.chem.qmw.ac.uk/iupac/AminoAcid/A2021.html |
| 118 |
http://www.chem.qmw.ac.uk/iubmb/misc/naseq.html |
| 119 |
|
| 120 |
Authors: |
| 121 |
GEC 2004,2005 |
| 122 |
""" |
| 123 |
|
| 124 |
# TODO: Add this to docstring somewhere. |
| 125 |
# To replace all ambiguous nucleic code by 'N', replace alphabet and then n |
| 126 |
# normalize. |
| 127 |
# |
| 128 |
# >>> Seq( 'ACGT-RYKM', reduced_nucleic_alphabet).normalized() |
| 129 |
# 'ACGT-NNNN' |
| 130 |
|
| 131 |
import codecs |
| 132 |
from array import array |
| 133 |
from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, Union |
| 134 |
|
| 135 |
__all__ = [ |
| 136 |
"Alphabet", |
| 137 |
"Seq", |
| 138 |
"rna", |
| 139 |
"dna", |
| 140 |
"protein", |
| 141 |
"SeqList", |
| 142 |
"generic_alphabet", |
| 143 |
"protein_alphabet", |
| 144 |
"nucleic_alphabet", |
| 145 |
"dna_alphabet", |
| 146 |
"rna_alphabet", |
| 147 |
"reduced_nucleic_alphabet", |
| 148 |
"reduced_protein_alphabet", |
| 149 |
"unambiguous_dna_alphabet", |
| 150 |
"unambiguous_dna_alphabet", |
| 151 |
"unambiguous_rna_alphabet", |
| 152 |
"unambiguous_protein_alphabet", |
| 153 |
"generic_alphabet", |
| 154 |
] |
| 155 |
|
| 156 |
|
| 157 |
class Alphabet(object): |
| 158 |
"""An ordered subset of printable ascii characters. |
| 159 |
|
| 160 |
Status: |
| 161 |
Beta |
| 162 |
Authors: |
| 163 |
- GEC 2005 |
| 164 |
""" |
| 165 |
|
| 166 |
_letters: str |
| 167 |
_alternatives: Tuple[str, str] |
| 168 |
_ord_table: bytes |
| 169 |
_chr_table: str |
| 170 |
|
| 171 |
__slots__ = ["_letters", "_alternatives", "_ord_table", "_chr_table"] |
| 172 |
|
| 173 |
# We're immutable, so use __new__ not __init__ |
| 174 |
def __new__( |
| 175 |
cls, |
| 176 |
letters: Optional[Union["Alphabet", str]] = None, |
| 177 |
alternatives: Optional[Tuple[Tuple[str, str], ...]] = None, |
| 178 |
) -> "Alphabet": |
| 179 |
"""Create a new, immutable Alphabet. |
| 180 |
|
| 181 |
e.g. |
| 182 |
Alphabet( 'ACDEFGHIKLMNPQRSTVUWY', |
| 183 |
zip('acdefghiklmnpqrstvuwy', 'ACDEFGHIKLMNPQRSTVUWY') ) |
| 184 |
|
| 185 |
arguments: |
| 186 |
- letters -- the letters in the alphabet. The ordering determines |
| 187 |
the ordinal position of each character in this alphabet. |
| 188 |
- alt -- A list of (alternative, canonical) letters. The alternatives |
| 189 |
are given the same ordinal position as the canonical characters. |
| 190 |
e.g. (('?','X'),('x', 'X')) states that '?' and 'x' are synonomous |
| 191 |
with 'X'. Values that are not in 'letters' are ignored. Alternatives |
| 192 |
that are already in 'letters' are also ignored. If the same |
| 193 |
alternative character is used twice then the alternative is assigned |
| 194 |
to the canonical character that occurs first in 'letters'. The |
| 195 |
default is to assume that upper and lower case characters are |
| 196 |
equivalent, unless both cases are included in 'letters'. |
| 197 |
raises: |
| 198 |
ValueError : Repetitive or otherwise illegal set of letters. |
| 199 |
""" |
| 200 |
self = object.__new__(cls) |
| 201 |
|
| 202 |
# Printable Ascii characters |
| 203 |
ascii_letters = "".join([chr(__i) for __i in range(32, 128)]) |
| 204 |
|
| 205 |
if letters is None: |
| 206 |
letters = ascii_letters |
| 207 |
else: |
| 208 |
letters = str(letters) |
| 209 |
self._letters = letters |
| 210 |
|
| 211 |
equivalent_by_case = zip( |
| 212 |
"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 213 |
) |
| 214 |
|
| 215 |
if alternatives is None: |
| 216 |
alternatives = tuple(equivalent_by_case) |
| 217 |
|
| 218 |
# The ord_table maps between the ordinal position of a character in ascii |
| 219 |
# and the ordinal position in this alphabet. Characters not in the |
| 220 |
# alphabet are given a position of 255. The ord_table is stored as a |
| 221 |
# string. |
| 222 |
ord_table = bytearray( |
| 223 |
[ |
| 224 |
0xFF, |
| 225 |
] |
| 226 |
* 256 |
| 227 |
) |
| 228 |
for i, a in enumerate(letters): |
| 229 |
n = ord(a) |
| 230 |
if n == 0: |
| 231 |
raise ValueError("Alphabet cannot contain null character \\0") |
| 232 |
if ord_table[n] != 0xFF: |
| 233 |
raise ValueError("Repetitive alphabet") |
| 234 |
ord_table[n] = i |
| 235 |
|
| 236 |
# Add alternatives |
| 237 |
_from = [] |
| 238 |
_to = [] |
| 239 |
for e, c in alternatives: |
| 240 |
if c in letters: |
| 241 |
n = ord(e) |
| 242 |
if ord_table[n] == 0xFF: # empty |
| 243 |
ord_table[n] = ord_table[ord(c)] |
| 244 |
_from.append(e) |
| 245 |
_to.append(c) |
| 246 |
self._alternatives = ("".join(_from), "".join(_to)) |
| 247 |
|
| 248 |
assert ord_table[0] == 0xFF |
| 249 |
self._ord_table = ord_table |
| 250 |
|
| 251 |
# The chr_table maps between ordinal position in the alphabet letters |
| 252 |
# and the ordinal position in ascii. This map is not the inverse of |
| 253 |
# ord_table if there are alternatives. |
| 254 |
chr_table = bytearray( |
| 255 |
[ |
| 256 |
0x00, |
| 257 |
] |
| 258 |
* 256 |
| 259 |
) |
| 260 |
for i, a in enumerate(letters): |
| 261 |
chr_table[i] = ord(a) |
| 262 |
self._chr_table = chr_table.decode() |
| 263 |
|
| 264 |
return self |
| 265 |
|
| 266 |
def alphabetic(self, string: str) -> bool: |
| 267 |
"""True if all characters of the string are in this alphabet.""" |
| 268 |
table = self._ord_table |
| 269 |
for s in str(string): |
| 270 |
if table[ord(s)] == 0xFF: |
| 271 |
return False |
| 272 |
return True |
| 273 |
|
| 274 |
def chr(self, n: int) -> str: |
| 275 |
"""The n'th character in the alphabet (zero indexed) or \\0""" |
| 276 |
return self._chr_table[n] |
| 277 |
|
| 278 |
def ord(self, c: str) -> int: |
| 279 |
"""The ordinal position of the character c in this alphabet, |
| 280 |
or 255 if no such character. |
| 281 |
""" |
| 282 |
return self._ord_table[ord(c)] |
| 283 |
|
| 284 |
def chrs(self, sequence_of_ints: Sequence[int]) -> "Seq": |
| 285 |
"""Convert a sequence of ordinals into an alphabetic string.""" |
| 286 |
c = [self.chr(n) for n in sequence_of_ints] |
| 287 |
s = "".join(c) |
| 288 |
return Seq(s, self) |
| 289 |
|
| 290 |
def ords(self, string: Union["Seq", str]) -> array: |
| 291 |
"""Convert an alphabetic string into a byte array of ordinals.""" |
| 292 |
s = str(string) |
| 293 |
s = s.translate(self._ord_table) |
| 294 |
a = array("B", codecs.latin_1_encode(s)[0]) # type: ignore # TESTME FIXME? |
| 295 |
return a |
| 296 |
|
| 297 |
def normalize(self, string: str) -> "Seq": |
| 298 |
"""Normalize an alphabetic string by converting all alternative symbols |
| 299 |
to the canonical equivalent in 'letters'. |
| 300 |
""" |
| 301 |
if not self.alphabetic(string): |
| 302 |
raise ValueError("Not an alphabetic string.") |
| 303 |
return self.chrs(self.ords(string)) |
| 304 |
|
| 305 |
def letters(self) -> str: |
| 306 |
"""Letters of the alphabet as a string.""" |
| 307 |
return str(self) |
| 308 |
|
| 309 |
# def _all_letters(self): |
| 310 |
# """ All allowed letters, including alternatives.""" |
| 311 |
# let = [] |
| 312 |
# let.append(self._letters) |
| 313 |
# for key, value in self._alternatives: |
| 314 |
# let.append(value) |
| 315 |
# return ''.join(let) |
| 316 |
|
| 317 |
def __repr__(self) -> str: |
| 318 |
return ( |
| 319 |
"Alphabet( '" + self._letters + "', zip" + repr(self._alternatives) + " )" |
| 320 |
) |
| 321 |
|
| 322 |
def __str__(self) -> str: |
| 323 |
return str(self._letters) |
| 324 |
|
| 325 |
def __len__(self) -> int: |
| 326 |
return len(self._letters) |
| 327 |
|
| 328 |
def __eq__(self, other: Any) -> bool: |
| 329 |
if not hasattr(other, "_ord_table"): |
| 330 |
return False |
| 331 |
return self._ord_table == other._ord_table |
| 332 |
|
| 333 |
def __ne__(self, other: Any) -> bool: |
| 334 |
return not self.__eq__(other) |
| 335 |
|
| 336 |
def __iter__(self) -> Iterator[str]: |
| 337 |
return iter(self._letters) |
| 338 |
|
| 339 |
# def __getitem__(self, key: Any) -> str: |
| 340 |
# return self._letters[key] |
| 341 |
|
| 342 |
def __hash__(self) -> int: |
| 343 |
return hash(tuple(self._ord_table)) |
| 344 |
|
| 345 |
@staticmethod |
| 346 |
def which( |
| 347 |
seqs: Union["Seq", "SeqList"], alphabets: Optional[List["Alphabet"]] = None |
| 348 |
) -> "Alphabet": |
| 349 |
"""Returns the most appropriate unambiguous protein, RNA or DNA alphabet |
| 350 |
for a Seq or SeqList. If a list of alphabets is supplied, then the best alphabet |
| 351 |
is selected from that list. |
| 352 |
|
| 353 |
The heuristic is to count the occurrences of letters for each alphabet and |
| 354 |
downweight longer alphabets by the log of the alphabet length. Ties |
| 355 |
go to the first alphabet in the list. |
| 356 |
|
| 357 |
""" |
| 358 |
if alphabets is None: |
| 359 |
alphabets = [ |
| 360 |
unambiguous_dna_alphabet, |
| 361 |
unambiguous_rna_alphabet, |
| 362 |
unambiguous_protein_alphabet, |
| 363 |
] |
| 364 |
import math |
| 365 |
|
| 366 |
score = [sum(seqs.tally(a)) / math.log(len(a)) for a in alphabets] |
| 367 |
best = score.index(max(score)) |
| 368 |
a = alphabets[best] |
| 369 |
return a |
| 370 |
|
| 371 |
|
| 372 |
# End class Alphabet |
| 373 |
|
| 374 |
# ------------------- Standard ALPHABETS ------------------- |
| 375 |
# Standard alphabets are defined here, after Alphabet class. |
| 376 |
|
| 377 |
generic_alphabet = Alphabet(None, None) |
| 378 |
|
| 379 |
protein_alphabet = Alphabet( |
| 380 |
"ACDEFGHIKLMNOPQRSTUVWYBJZX*-", |
| 381 |
tuple(zip("acdefghiklmnopqrstuvwybjzx?.~", "ACDEFGHIKLMNOPQRSTUVWYBJZXX--")), |
| 382 |
) |
| 383 |
|
| 384 |
nucleic_alphabet = Alphabet( |
| 385 |
"ACGTURYSWKMBDHVN-", tuple(zip("acgturyswkmbdhvnXx?.~", "ACGTURYSWKMBDHVNNNN--")) |
| 386 |
) |
| 387 |
|
| 388 |
dna_alphabet = Alphabet( |
| 389 |
"ACGTRYSWKMBDHVN-", tuple(zip("acgtryswkmbdhvnXx?.~Uu", "ACGTRYSWKMBDHVNNNN--TT")) |
| 390 |
) |
| 391 |
|
| 392 |
rna_alphabet = Alphabet( |
| 393 |
"ACGURYSWKMBDHVN-", tuple(zip("acguryswkmbdhvnXx?.~Tt", "ACGURYSWKMBDHVNNNN--UU")) |
| 394 |
) |
| 395 |
|
| 396 |
reduced_nucleic_alphabet = Alphabet( |
| 397 |
"ACGTN-", |
| 398 |
tuple(zip("acgtryswkmbdhvnXx?.~TtRYSWKMBDHV", "ACGTNNNNNNNNNNNNNN--TTNNNNNNNNNN")), |
| 399 |
) |
| 400 |
|
| 401 |
reduced_protein_alphabet = Alphabet( |
| 402 |
"ACDEFGHIKLMNPQRSTVWYX*-", |
| 403 |
tuple(zip("acdefghiklmnpqrstvwyx?.~BbZzUu", "ACDEFGHIKLMNPQRSTVWYXX--XXXXCC")), |
| 404 |
) |
| 405 |
|
| 406 |
unambiguous_dna_alphabet = Alphabet("ACGT", tuple(zip("acgt", "ACGT"))) |
| 407 |
|
| 408 |
unambiguous_rna_alphabet = Alphabet("ACGU", tuple(zip("acgu", "ACGU"))) |
| 409 |
|
| 410 |
unambiguous_protein_alphabet = Alphabet( |
| 411 |
"ACDEFGHIKLMNPQRSTVWY", |
| 412 |
tuple(zip("acdefghiklmnopqrstuvwy", "ACDEFGHIKLMNOPQRSTUVWY")), |
| 413 |
) |
| 414 |
|
| 415 |
_complement_table = str.maketrans( |
| 416 |
"ACGTRYSWKMBDHVN-acgtUuryswkmbdhvnXx?.~", "TGCAYRSWMKVHDBN-tgcaAayrswmkvhdbnXx?.~" |
| 417 |
) |
| 418 |
|
| 419 |
|
| 420 |
class Seq(str): |
| 421 |
"""An alphabetic string. A subclass of "str" consisting solely of |
| 422 |
letters from the same alphabet. |
| 423 |
|
| 424 |
Attributes: |
| 425 |
alphabet -- A string or Alphabet of allowed characters. |
| 426 |
name -- A short string used to identify the sequence. |
| 427 |
description -- A string describing the sequence |
| 428 |
|
| 429 |
Authors : |
| 430 |
GEC 2005 |
| 431 |
""" |
| 432 |
|
| 433 |
# TODO: need a method to return a copy of the string with a new alphabet, |
| 434 |
# preserving the sequence, name and alphabet? |
| 435 |
name: str |
| 436 |
description: str |
| 437 |
_alphabet: Alphabet |
| 438 |
|
| 439 |
def __new__( |
| 440 |
cls, |
| 441 |
obj: str, |
| 442 |
alphabet: Optional[Alphabet] = generic_alphabet, |
| 443 |
name: Optional[str] = None, |
| 444 |
description: Optional[str] = None, |
| 445 |
) -> "Seq": |
| 446 |
self = str.__new__(cls, obj) |
| 447 |
if alphabet is None: |
| 448 |
alphabet = generic_alphabet |
| 449 |
if name is None: |
| 450 |
name = "" |
| 451 |
if description is None: |
| 452 |
description = "" |
| 453 |
if not isinstance(alphabet, Alphabet): |
| 454 |
alphabet = Alphabet(alphabet) |
| 455 |
if not alphabet.alphabetic(self): |
| 456 |
raise ValueError("Sequence not alphabetic %s, '%s'" % (alphabet, self)) |
| 457 |
|
| 458 |
self._alphabet = alphabet |
| 459 |
self.name = name |
| 460 |
self.description = description |
| 461 |
|
| 462 |
return self |
| 463 |
|
| 464 |
# BEGIN PROPERTIES |
| 465 |
|
| 466 |
# Make alphabet constant |
| 467 |
@property |
| 468 |
def alphabet(self) -> Alphabet: |
| 469 |
return self._alphabet |
| 470 |
|
| 471 |
# END PROPERTIES |
| 472 |
|
| 473 |
def ords(self) -> array: |
| 474 |
"""Convert sequence to an array of integers |
| 475 |
in the range [0, len(alphabet) ) |
| 476 |
""" |
| 477 |
return self.alphabet.ords(self) |
| 478 |
|
| 479 |
def tally(self, alphabet: Optional[Alphabet] = None) -> List[int]: |
| 480 |
"""Counts the occurrences of alphabetic characters. |
| 481 |
|
| 482 |
Arguments: |
| 483 |
- alphabet -- an optional alternative alphabet |
| 484 |
|
| 485 |
Returns : |
| 486 |
A list of character counts in alphabetic order. |
| 487 |
""" |
| 488 |
# Renamed from count() since this conflicts with str.count(). |
| 489 |
if not alphabet: |
| 490 |
alphabet = self.alphabet |
| 491 |
L = len(alphabet) |
| 492 |
counts = [ |
| 493 |
0, |
| 494 |
] * L |
| 495 |
|
| 496 |
ords = alphabet.ords(self) |
| 497 |
|
| 498 |
for n in ords: |
| 499 |
if n < L: |
| 500 |
counts[n] += 1 |
| 501 |
|
| 502 |
return counts |
| 503 |
|
| 504 |
def __getitem__(self, key: Any) -> "Seq": |
| 505 |
cls = self.__class__ |
| 506 |
return cls(str.__getitem__(self, key), self.alphabet) |
| 507 |
|
| 508 |
def __add__(self, other: Any) -> "Seq": |
| 509 |
# called for "self + other" |
| 510 |
cls = self.__class__ |
| 511 |
return cls(str.__add__(self, other), self.alphabet) |
| 512 |
|
| 513 |
def __radd__(self, other: Any) -> "Seq": |
| 514 |
# Called when "other + self" and other is superclass of self |
| 515 |
cls = self.__class__ |
| 516 |
return cls(str.__add__(self, other), self.alphabet) |
| 517 |
|
| 518 |
def join(self, str_list: List["Seq"]) -> "Seq": # type: ignore # Incorrectly overrides superclass join |
| 519 |
cls = self.__class__ |
| 520 |
return cls(super(Seq, self).join(str_list), self.alphabet) |
| 521 |
|
| 522 |
def __eq__(self, other: Any) -> bool: |
| 523 |
if not hasattr(other, "alphabet"): |
| 524 |
return False |
| 525 |
if self.alphabet != other.alphabet: |
| 526 |
return False |
| 527 |
return str.__eq__(self, other) |
| 528 |
|
| 529 |
def __ne__(self, other: Any) -> bool: |
| 530 |
return not self.__eq__(other) |
| 531 |
|
| 532 |
def tostring(self) -> "str": |
| 533 |
"""Converts Seq to a raw string.""" |
| 534 |
# Compatibility with biopython |
| 535 |
return str(self) |
| 536 |
|
| 537 |
# ---- Transformations of Seq ---- |
| 538 |
def reverse(self) -> "Seq": |
| 539 |
"""Return the reversed sequence. |
| 540 |
|
| 541 |
Note that this method returns a new object, in contrast to |
| 542 |
the in-place reverse() method of list objects. |
| 543 |
""" |
| 544 |
cls = self.__class__ |
| 545 |
return cls(self[::-1], self.alphabet) |
| 546 |
|
| 547 |
def ungap(self) -> "Seq": |
| 548 |
# FIXME: Gap symbols should be specified by the Alphabet? |
| 549 |
return self.remove("-.~") |
| 550 |
|
| 551 |
def remove(self, delchars: str) -> "Seq": |
| 552 |
"""Return a new alphabetic sequence with all characters in 'delchars' |
| 553 |
removed. |
| 554 |
""" |
| 555 |
cls = self.__class__ |
| 556 |
cleanseq = "".join(char for char in str(self) if char not in set(delchars)) |
| 557 |
return cls(cleanseq.translate(str.maketrans("", "")), self.alphabet) |
| 558 |
|
| 559 |
def lower(self) -> "Seq": |
| 560 |
"""Return a lower case copy of the sequence.""" |
| 561 |
cls = self.__class__ |
| 562 |
trans = str.maketrans( |
| 563 |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" |
| 564 |
) |
| 565 |
return cls(str(self).translate(trans), self.alphabet) |
| 566 |
|
| 567 |
def upper(self) -> "Seq": |
| 568 |
"""Return a lower case copy of the sequence.""" |
| 569 |
cls = self.__class__ |
| 570 |
trans = str.maketrans( |
| 571 |
"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 572 |
) |
| 573 |
return cls(str(self).translate(trans), self.alphabet) |
| 574 |
|
| 575 |
def mask( |
| 576 |
self, letters: str = "abcdefghijklmnopqrstuvwxyz", mask: str = "X" |
| 577 |
) -> "Seq": |
| 578 |
"""Replace all occurrences of letters with the mask character. |
| 579 |
The default is to replace all lower case letters with 'X'. |
| 580 |
""" |
| 581 |
LL = len(letters) |
| 582 |
if len(mask) != 1: |
| 583 |
raise ValueError("Mask should be single character") |
| 584 |
to = mask * LL |
| 585 |
trans = str.maketrans(letters, to) |
| 586 |
cls = self.__class__ |
| 587 |
return cls(str(self).translate(trans), self.alphabet) |
| 588 |
|
| 589 |
def translate(self) -> "Seq": # type: ignore # RENAME: Incorrectly overrides superclass translate. |
| 590 |
"""Translate a nucleotide sequence to a polypeptide using full |
| 591 |
IUPAC ambiguities in DNA/RNA and amino acid codes, using the |
| 592 |
standard genetic code. See weblogo.transform.GeneticCode for |
| 593 |
details and more options. |
| 594 |
""" |
| 595 |
# Note: masks str.translate |
| 596 |
from .transform import GeneticCode |
| 597 |
|
| 598 |
return GeneticCode.std().translate(self) |
| 599 |
|
| 600 |
def back_translate(self) -> "Seq": |
| 601 |
"""Translate a protein sequence back into coding DNA, using the |
| 602 |
standard genetic code. See weblogo.transform.GeneticCode for |
| 603 |
details and more options. |
| 604 |
""" |
| 605 |
from .transform import GeneticCode |
| 606 |
|
| 607 |
return GeneticCode.std().back_translate(self) |
| 608 |
|
| 609 |
def reverse_complement(self) -> "Seq": |
| 610 |
"""Returns reversed complementary nucleic acid sequence (i.e. the other |
| 611 |
strand of a DNA sequence.) |
| 612 |
""" |
| 613 |
return self.reverse().complement() |
| 614 |
|
| 615 |
def complement(self) -> "Seq": |
| 616 |
"""Returns complementary nucleic acid sequence.""" |
| 617 |
if not nucleic_alphabet.alphabetic(str(self.alphabet)): |
| 618 |
raise ValueError("Incompatibly alphabets") |
| 619 |
s = str.translate(self, _complement_table) |
| 620 |
cls = self.__class__ |
| 621 |
return cls(s, self.alphabet, self.name, self.description) |
| 622 |
|
| 623 |
def words( |
| 624 |
self, k: int, alphabet: Optional[Alphabet] = None |
| 625 |
) -> Generator[str, None, None]: |
| 626 |
"""Return an iteration over all subwords of length k in the sequence. If an optional |
| 627 |
alphabet is provided, only words from that alphabet are returned. |
| 628 |
|
| 629 |
>>> list(Seq("abcabc").words(3)) |
| 630 |
['abc', 'bca', 'cab', 'abc'] |
| 631 |
""" |
| 632 |
|
| 633 |
if len(self) < k: |
| 634 |
return |
| 635 |
|
| 636 |
# An optimization. Chopping up strings is faster. |
| 637 |
seq = self.alphabet.normalize(self).tostring() |
| 638 |
# seq = self.tostring() |
| 639 |
|
| 640 |
for i in range(0, len(seq) - k + 1): |
| 641 |
word = seq[i : i + k] |
| 642 |
if alphabet is None or alphabet.alphabetic(word): |
| 643 |
yield word |
| 644 |
|
| 645 |
def word_count(self, k: int, alphabet: Optional[Alphabet] = None) -> List: |
| 646 |
"""Return a count of all subwords in the sequence. |
| 647 |
|
| 648 |
>>> from weblogo.seq import * |
| 649 |
>>> Seq("abcabc").word_count(3) |
| 650 |
[('abc', 2), ('bca', 1), ('cab', 1)] |
| 651 |
""" |
| 652 |
from .utils import group_count |
| 653 |
|
| 654 |
words = sorted(self.words(k, alphabet)) |
| 655 |
return group_count(words) |
| 656 |
|
| 657 |
|
| 658 |
# end class Seq |
| 659 |
|
| 660 |
|
| 661 |
class SeqList(list): |
| 662 |
"""A list of sequences.""" |
| 663 |
|
| 664 |
__slots__ = ["alphabet", "name", "description"] |
| 665 |
|
| 666 |
def __init__( |
| 667 |
self, |
| 668 |
alist: List[Seq] = [], |
| 669 |
alphabet: Optional[Alphabet] = None, |
| 670 |
name: Optional[str] = None, |
| 671 |
description: Optional[str] = None, |
| 672 |
): |
| 673 |
list.__init__(self, alist) |
| 674 |
self.alphabet = alphabet |
| 675 |
self.name = name |
| 676 |
self.description = description |
| 677 |
|
| 678 |
# TOOWTDI. Replicates seq_io.read() |
| 679 |
# @classmethod |
| 680 |
# def read(cls, afile, alphabet = None): |
| 681 |
# return weblogo.seq_io.read(afile, alphabet) |
| 682 |
|
| 683 |
def isaligned(self) -> bool: |
| 684 |
"""Are all sequences of the same length and alphabet?""" |
| 685 |
if len(self) == 0: |
| 686 |
return True |
| 687 |
A = self.alphabet |
| 688 |
if A is None: |
| 689 |
A = self[0].alphabet |
| 690 |
L = len(self[0]) |
| 691 |
|
| 692 |
for s in self: |
| 693 |
if len(s) != L: |
| 694 |
return False |
| 695 |
if s.alphabet != A: |
| 696 |
return False |
| 697 |
return True |
| 698 |
|
| 699 |
def ords(self, alphabet: Optional[Alphabet] = None) -> List[array]: |
| 700 |
"""Convert sequence list into a 2D array of ordinals.""" |
| 701 |
if not alphabet: |
| 702 |
alphabet = self.alphabet |
| 703 |
if not alphabet: |
| 704 |
raise ValueError("No alphabet") |
| 705 |
k = [] |
| 706 |
for s in self: |
| 707 |
k.append(alphabet.ords(s)) |
| 708 |
return k |
| 709 |
|
| 710 |
def tally(self, alphabet: Optional[Alphabet] = None) -> List[int]: |
| 711 |
"""Counts the occurrences of alphabetic characters. |
| 712 |
|
| 713 |
Arguments: |
| 714 |
- alphabet -- an optional alternative alphabet |
| 715 |
|
| 716 |
Returns : |
| 717 |
A list of character counts in alphabetic order. |
| 718 |
""" |
| 719 |
if not alphabet: |
| 720 |
alphabet = self.alphabet |
| 721 |
if not alphabet: |
| 722 |
raise ValueError("No alphabet") |
| 723 |
|
| 724 |
counts = [sum(c) for c in zip(*[s.tally(alphabet) for s in self])] |
| 725 |
return counts |
| 726 |
|
| 727 |
def profile(self, alphabet: Optional[Alphabet] = None): # type: ignore # Nasty circular import |
| 728 |
"""Counts the occurrences of characters in each column. |
| 729 |
|
| 730 |
Returns: Motif(counts, alphabet) |
| 731 |
""" |
| 732 |
if not alphabet: |
| 733 |
alphabet = self.alphabet |
| 734 |
if not alphabet: |
| 735 |
raise ValueError("No alphabet") |
| 736 |
|
| 737 |
N = len(alphabet) |
| 738 |
ords = self.ords(alphabet) |
| 739 |
L = len(ords[0]) |
| 740 |
counts = [ |
| 741 |
[ |
| 742 |
0, |
| 743 |
] |
| 744 |
* N |
| 745 |
for x in range(0, L) |
| 746 |
] |
| 747 |
|
| 748 |
for o in ords: |
| 749 |
if len(o) != L: |
| 750 |
raise ValueError( |
| 751 |
"Sequences are of incommensurate lengths. Cannot tally." |
| 752 |
) |
| 753 |
for j, n in enumerate(o): |
| 754 |
if n < N: |
| 755 |
counts[j][n] += 1 |
| 756 |
|
| 757 |
from .matrix import Motif |
| 758 |
|
| 759 |
return Motif(alphabet, counts) |
| 760 |
|
| 761 |
|
| 762 |
# end class SeqList |
| 763 |
|
| 764 |
|
| 765 |
def dna(string: str) -> Seq: |
| 766 |
"""Create an alphabetic sequence representing a stretch of DNA.""" |
| 767 |
return Seq(string, alphabet=dna_alphabet) |
| 768 |
|
| 769 |
|
| 770 |
def rna(string: str) -> Seq: |
| 771 |
"""Create an alphabetic sequence representing a stretch of RNA.""" |
| 772 |
return Seq(string, alphabet=rna_alphabet) |
| 773 |
|
| 774 |
|
| 775 |
def protein(string: str) -> Seq: |
| 776 |
"""Create an alphabetic sequence representing a stretch of polypeptide.""" |
| 777 |
return Seq(string, alphabet=protein_alphabet) |