forked from biopython/biopython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSeq.py
3029 lines (2550 loc) · 111 KB
/
Seq.py
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2000 Andrew Dalke.
# Copyright 2000-2002 Brad Chapman.
# Copyright 2004-2005, 2010 by M de Hoon.
# Copyright 2007-2020 by Peter Cock.
# All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Provide objects to represent biological sequences with alphabets.
See also the Seq_ wiki and the chapter in our tutorial:
- `HTML Tutorial`_
- `PDF Tutorial`_
.. _Seq: http://biopython.org/wiki/Seq
.. _`HTML Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.html
.. _`PDF Tutorial`: http://biopython.org/DIST/docs/tutorial/Tutorial.pdf
"""
import array
import sys
import warnings
import collections
from collections.abc import Iterable as _Iterable
from Bio import BiopythonWarning
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Data.IUPACData import ambiguous_dna_complement, ambiguous_rna_complement
from Bio.Data.IUPACData import ambiguous_dna_letters as _ambiguous_dna_letters
from Bio.Data.IUPACData import ambiguous_rna_letters as _ambiguous_rna_letters
from Bio.Data import CodonTable
def _maketrans(complement_mapping):
"""Make a python string translation table (PRIVATE).
Arguments:
- complement_mapping - a dictionary such as ambiguous_dna_complement
and ambiguous_rna_complement from Data.IUPACData.
Returns a translation table (a string of length 256) for use with the
python string's translate method to use in a (reverse) complement.
Compatible with lower case and upper case sequences.
For internal use only.
"""
before = "".join(complement_mapping.keys())
after = "".join(complement_mapping.values())
before += before.lower()
after += after.lower()
return str.maketrans(before, after)
_dna_complement_table = _maketrans(ambiguous_dna_complement)
_rna_complement_table = _maketrans(ambiguous_rna_complement)
class Seq:
"""Read-only sequence object (essentially a string with an alphabet).
Like normal python strings, our basic sequence object is immutable.
This prevents you from doing my_seq[5] = "A" for example, but does allow
Seq objects to be used as dictionary keys.
The Seq object provides a number of string like methods (such as count,
find, split and strip), which are alphabet aware where appropriate.
In addition to the string like sequence, the Seq object has an alphabet
property. This is an instance of an Alphabet class from Bio.Alphabet,
for example generic DNA, or IUPAC DNA. This describes the type of molecule
(e.g. RNA, DNA, protein) and may also indicate the expected symbols
(letters).
The Seq object also provides some biological methods, such as complement,
reverse_complement, transcribe, back_transcribe and translate (which are
not applicable to sequences with a protein alphabet).
"""
def __init__(self, data, alphabet=Alphabet.generic_alphabet):
"""Create a Seq object.
Arguments:
- seq - Sequence, required (string)
- alphabet - Optional argument, an Alphabet object from
Bio.Alphabet
You will typically use Bio.SeqIO to read in sequences from files as
SeqRecord objects, whose sequence will be exposed as a Seq object via
the seq property.
However, will often want to create your own Seq objects directly:
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF",
... IUPAC.protein)
>>> my_seq
Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF', IUPACProtein())
>>> print(my_seq)
MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
>>> my_seq.alphabet
IUPACProtein()
"""
# Enforce string storage
if not isinstance(data, str):
raise TypeError(
"The sequence data given to a Seq object should "
"be a string (not another Seq object etc)"
)
self._data = data
self.alphabet = alphabet # Seq API requirement
def __repr__(self):
"""Return (truncated) representation of the sequence for debugging."""
if self.alphabet is Alphabet.generic_alphabet:
# Default used, we can omit it and simplify the representation
a = ""
else:
a = ", %r" % self.alphabet
if len(self) > 60:
# Shows the last three letters as it is often useful to see if
# there is a stop codon at the end of a sequence.
# Note total length is 54+3+3=60
return "{0}('{1}...{2}'{3!s})".format(
self.__class__.__name__, str(self)[:54], str(self)[-3:], a
)
else:
return "{0}({1!r}{2!s})".format(self.__class__.__name__, self._data, a)
def __str__(self):
"""Return the full sequence as a python string, use str(my_seq).
Note that Biopython 1.44 and earlier would give a truncated
version of repr(my_seq) for str(my_seq). If you are writing code
which need to be backwards compatible with really old Biopython,
you should continue to use my_seq.tostring() as follows::
try:
# The old way, removed in Biopython 1.73
as_string = seq_obj.tostring()
except AttributeError:
# The new way, needs Biopython 1.45 or later.
# Don't use this on Biopython 1.44 or older as truncates
as_string = str(seq_obj)
"""
return self._data
def __hash__(self):
"""Hash for comparison.
See Seq object comparison documentation - this has changed
from past versions of Biopython!
"""
# TODO - remove this warning in a future release
warnings.warn(
"Biopython Seq objects now use string comparison. "
"Older versions of Biopython used object comparison. "
"During this transition, please use hash(id(my_seq)) "
"or my_dict[id(my_seq)] if you want the old behaviour, "
"or use hash(str(my_seq)) or my_dict[str(my_seq)] for "
"the new string hashing behaviour.",
BiopythonWarning,
)
return hash(str(self))
def __eq__(self, other):
"""Compare the sequence to another sequence or a string (README).
Historically comparing Seq objects has done Python object comparison.
After considerable discussion (keeping in mind constraints of the
Python language, hashes and dictionary support), Biopython now uses
simple string comparison (with a warning about the change).
Note that incompatible alphabets (e.g. DNA to RNA) will trigger a
warning.
During this transition period, please just do explicit comparisons:
>>> from Bio.Seq import Seq
>>> seq1 = Seq("ACGT")
>>> seq2 = Seq("ACGT")
>>> id(seq1) == id(seq2)
False
>>> str(seq1) == str(seq2)
True
The new behaviour is to use string-like equality:
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> seq1 == seq2
True
>>> seq1 == "ACGT"
True
>>> seq1 == Seq("ACGT", generic_dna)
True
"""
if hasattr(other, "alphabet"):
# other could be a Seq or a MutableSeq
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
warnings.warn(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
),
BiopythonWarning,
)
return str(self) == str(other)
def __lt__(self, other):
"""Implement the less-than operand."""
if hasattr(other, "alphabet"):
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
warnings.warn(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
),
BiopythonWarning,
)
if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
return str(self) < str(other)
raise TypeError(
"'<' not supported between instances of '{}' and '{}'".format(
type(self).__name__, type(other).__name__
)
)
def __le__(self, other):
"""Implement the less-than or equal operand."""
if hasattr(other, "alphabet"):
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
warnings.warn(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
),
BiopythonWarning,
)
if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
return str(self) <= str(other)
raise TypeError(
"'<=' not supported between instances of '{}' and '{}'".format(
type(self).__name__, type(other).__name__
)
)
def __gt__(self, other):
"""Implement the greater-than operand."""
if hasattr(other, "alphabet"):
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
warnings.warn(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
),
BiopythonWarning,
)
if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
return str(self) > str(other)
raise TypeError(
"'>' not supported between instances of '{}' and '{}'".format(
type(self).__name__, type(other).__name__
)
)
def __ge__(self, other):
"""Implement the greater-than or equal operand."""
if hasattr(other, "alphabet"):
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
warnings.warn(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
),
BiopythonWarning,
)
if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)):
return str(self) >= str(other)
raise TypeError(
"'>=' not supported between instances of '{}' and '{}'".format(
type(self).__name__, type(other).__name__
)
)
def __len__(self):
"""Return the length of the sequence, use len(my_seq)."""
return len(self._data) # Seq API requirement
def __getitem__(self, index): # Seq API requirement
"""Return a subsequence of single letter, use my_seq[index].
>>> my_seq = Seq('ACTCGACGTCG')
>>> my_seq[5]
'A'
"""
if isinstance(index, int):
# Return a single letter as a string
return self._data[index]
else:
# Return the (sub)sequence as another Seq object
return Seq(self._data[index], self.alphabet)
def __add__(self, other):
"""Add another sequence or string to this sequence.
If adding a string to a Seq, the alphabet is preserved:
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_protein
>>> Seq("MELKI", generic_protein) + "LV"
Seq('MELKILV', ProteinAlphabet())
When adding two Seq (like) objects, the alphabets are important.
Consider this example:
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet.IUPAC import unambiguous_dna, ambiguous_dna
>>> unamb_dna_seq = Seq("ACGT", unambiguous_dna)
>>> ambig_dna_seq = Seq("ACRGT", ambiguous_dna)
>>> unamb_dna_seq
Seq('ACGT', IUPACUnambiguousDNA())
>>> ambig_dna_seq
Seq('ACRGT', IUPACAmbiguousDNA())
If we add the ambiguous and unambiguous IUPAC DNA alphabets, we get
the more general ambiguous IUPAC DNA alphabet:
>>> unamb_dna_seq + ambig_dna_seq
Seq('ACGTACRGT', IUPACAmbiguousDNA())
However, if the default generic alphabet is included, the result is
a generic alphabet:
>>> Seq("") + ambig_dna_seq
Seq('ACRGT')
You can't add RNA and DNA sequences:
>>> from Bio.Alphabet import generic_dna, generic_rna
>>> Seq("ACGT", generic_dna) + Seq("ACGU", generic_rna)
Traceback (most recent call last):
...
TypeError: Incompatible alphabets DNAAlphabet() and RNAAlphabet()
You can't add nucleotide and protein sequences:
>>> from Bio.Alphabet import generic_dna, generic_protein
>>> Seq("ACGT", generic_dna) + Seq("MELKI", generic_protein)
Traceback (most recent call last):
...
TypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet()
"""
if hasattr(other, "alphabet"):
# other should be a Seq or a MutableSeq
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
raise TypeError(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
)
)
# They should be the same sequence type (or one of them is generic)
a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
return self.__class__(str(self) + str(other), a)
elif isinstance(other, str):
# other is a plain string - use the current alphabet
return self.__class__(str(self) + other, self.alphabet)
from Bio.SeqRecord import SeqRecord # Lazy to avoid circular imports
if isinstance(other, SeqRecord):
# Get the SeqRecord's __radd__ to handle this
return NotImplemented
else:
raise TypeError
def __radd__(self, other):
"""Add a sequence on the left.
If adding a string to a Seq, the alphabet is preserved:
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_protein
>>> "LV" + Seq("MELKI", generic_protein)
Seq('LVMELKI', ProteinAlphabet())
Adding two Seq (like) objects is handled via the __add__ method.
"""
if hasattr(other, "alphabet"):
# other should be a Seq or a MutableSeq
if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]):
raise TypeError(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other.alphabet
)
)
# They should be the same sequence type (or one of them is generic)
a = Alphabet._consensus_alphabet([self.alphabet, other.alphabet])
return self.__class__(str(other) + str(self), a)
elif isinstance(other, str):
# other is a plain string - use the current alphabet
return self.__class__(other + str(self), self.alphabet)
else:
raise TypeError
def __mul__(self, other):
"""Multiply Seq by integer.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> Seq('ATG') * 2
Seq('ATGATG')
>>> Seq('ATG', generic_dna) * 2
Seq('ATGATG', DNAAlphabet())
"""
if not isinstance(other, int):
raise TypeError(
"can't multiply {} by non-int type".format(self.__class__.__name__)
)
return self.__class__(str(self) * other, self.alphabet)
def __rmul__(self, other):
"""Multiply integer by Seq.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> 2 * Seq('ATG')
Seq('ATGATG')
>>> 2 * Seq('ATG', generic_dna)
Seq('ATGATG', DNAAlphabet())
"""
if not isinstance(other, int):
raise TypeError(
"can't multiply {} by non-int type".format(self.__class__.__name__)
)
return self.__class__(str(self) * other, self.alphabet)
def __imul__(self, other):
"""Multiply Seq in-place.
Note although Seq is immutable, the in-place method is
included to match the behaviour for regular Python strings.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> seq = Seq('ATG', generic_dna)
>>> seq *= 2
>>> seq
Seq('ATGATG', DNAAlphabet())
"""
if not isinstance(other, int):
raise TypeError(
"can't multiply {} by non-int type".format(self.__class__.__name__)
)
return self.__class__(str(self) * other, self.alphabet)
def tomutable(self): # Needed? Or use a function?
"""Return the full sequence as a MutableSeq object.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_seq = Seq("MKQHKAMIVALIVICITAVVAAL",
... IUPAC.protein)
>>> my_seq
Seq('MKQHKAMIVALIVICITAVVAAL', IUPACProtein())
>>> my_seq.tomutable()
MutableSeq('MKQHKAMIVALIVICITAVVAAL', IUPACProtein())
Note that the alphabet is preserved.
"""
return MutableSeq(str(self), self.alphabet)
def _get_seq_str_and_check_alphabet(self, other_sequence):
"""Convert string/Seq/MutableSeq to string, checking alphabet (PRIVATE).
For a string argument, returns the string.
For a Seq or MutableSeq, it checks the alphabet is compatible
(raising an exception if it isn't), and then returns a string.
"""
try:
other_alpha = other_sequence.alphabet
except AttributeError:
# Assume other_sequence is a string
return other_sequence
# Other should be a Seq or a MutableSeq
if not Alphabet._check_type_compatible([self.alphabet, other_alpha]):
raise TypeError(
"Incompatible alphabets {0!r} and {1!r}".format(
self.alphabet, other_alpha
)
)
# Return as a string
return str(other_sequence)
def count(self, sub, start=0, end=sys.maxsize):
"""Return a non-overlapping count, like that of a python string.
This behaves like the python string method of the same name,
which does a non-overlapping count!
For an overlapping search use the newer count_overlap() method.
Returns an integer, the number of occurrences of substring
argument sub in the (sub)sequence given by [start:end].
Optional arguments start and end are interpreted as in slice
notation.
Arguments:
- sub - a string or another Seq object to look for
- start - optional integer, slice start
- end - optional integer, slice end
e.g.
>>> from Bio.Seq import Seq
>>> my_seq = Seq("AAAATGA")
>>> print(my_seq.count("A"))
5
>>> print(my_seq.count("ATG"))
1
>>> print(my_seq.count(Seq("AT")))
1
>>> print(my_seq.count("AT", 2, -1))
1
HOWEVER, please note because python strings and Seq objects (and
MutableSeq objects) do a non-overlapping search, this may not give
the answer you expect:
>>> "AAAA".count("AA")
2
>>> print(Seq("AAAA").count("AA"))
2
An overlapping search, as implemented in .count_overlap(),
would give the answer as three!
"""
# If it has one, check the alphabet:
sub_str = self._get_seq_str_and_check_alphabet(sub)
return str(self).count(sub_str, start, end)
def count_overlap(self, sub, start=0, end=sys.maxsize):
"""Return an overlapping count.
For a non-overlapping search use the count() method.
Returns an integer, the number of occurrences of substring
argument sub in the (sub)sequence given by [start:end].
Optional arguments start and end are interpreted as in slice
notation.
Arguments:
- sub - a string or another Seq object to look for
- start - optional integer, slice start
- end - optional integer, slice end
e.g.
>>> from Bio.Seq import Seq
>>> print(Seq("AAAA").count_overlap("AA"))
3
>>> print(Seq("ATATATATA").count_overlap("ATA"))
4
>>> print(Seq("ATATATATA").count_overlap("ATA", 3, -1))
1
Where substrings do not overlap, should behave the same as
the count() method:
>>> from Bio.Seq import Seq
>>> my_seq = Seq("AAAATGA")
>>> print(my_seq.count_overlap("A"))
5
>>> my_seq.count_overlap("A") == my_seq.count("A")
True
>>> print(my_seq.count_overlap("ATG"))
1
>>> my_seq.count_overlap("ATG") == my_seq.count("ATG")
True
>>> print(my_seq.count_overlap(Seq("AT")))
1
>>> my_seq.count_overlap(Seq("AT")) == my_seq.count(Seq("AT"))
True
>>> print(my_seq.count_overlap("AT", 2, -1))
1
>>> my_seq.count_overlap("AT", 2, -1) == my_seq.count("AT", 2, -1)
True
HOWEVER, do not use this method for such cases because the
count() method is much for efficient.
"""
sub_str = self._get_seq_str_and_check_alphabet(sub)
self_str = str(self)
overlap_count = 0
while True:
start = self_str.find(sub_str, start, end) + 1
if start != 0:
overlap_count += 1
else:
return overlap_count
def __contains__(self, char):
"""Implement the 'in' keyword, like a python string.
e.g.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna, generic_rna, generic_protein
>>> my_dna = Seq("ATATGAAATTTGAAAA", generic_dna)
>>> "AAA" in my_dna
True
>>> Seq("AAA") in my_dna
True
>>> Seq("AAA", generic_dna) in my_dna
True
Like other Seq methods, this will raise a type error if another Seq
(or Seq like) object with an incompatible alphabet is used:
>>> Seq("AAA", generic_rna) in my_dna
Traceback (most recent call last):
...
TypeError: Incompatible alphabets DNAAlphabet() and RNAAlphabet()
>>> Seq("AAA", generic_protein) in my_dna
Traceback (most recent call last):
...
TypeError: Incompatible alphabets DNAAlphabet() and ProteinAlphabet()
"""
# If it has one, check the alphabet:
sub_str = self._get_seq_str_and_check_alphabet(char)
return sub_str in str(self)
def find(self, sub, start=0, end=sys.maxsize):
"""Find method, like that of a python string.
This behaves like the python string method of the same name.
Returns an integer, the index of the first occurrence of substring
argument sub in the (sub)sequence given by [start:end].
Arguments:
- sub - a string or another Seq object to look for
- start - optional integer, slice start
- end - optional integer, slice end
Returns -1 if the subsequence is NOT found.
e.g. Locating the first typical start codon, AUG, in an RNA sequence:
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.find("AUG")
3
"""
# If it has one, check the alphabet:
sub_str = self._get_seq_str_and_check_alphabet(sub)
return str(self).find(sub_str, start, end)
def rfind(self, sub, start=0, end=sys.maxsize):
"""Find from right method, like that of a python string.
This behaves like the python string method of the same name.
Returns an integer, the index of the last (right most) occurrence of
substring argument sub in the (sub)sequence given by [start:end].
Arguments:
- sub - a string or another Seq object to look for
- start - optional integer, slice start
- end - optional integer, slice end
Returns -1 if the subsequence is NOT found.
e.g. Locating the last typical start codon, AUG, in an RNA sequence:
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.rfind("AUG")
15
"""
# If it has one, check the alphabet:
sub_str = self._get_seq_str_and_check_alphabet(sub)
return str(self).rfind(sub_str, start, end)
def index(self, sub, start=0, end=sys.maxsize):
"""Like find() but raise ValueError when the substring is not found.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.find("T")
-1
>>> my_rna.index("T")
Traceback (most recent call last):
...
ValueError: substring not found...
"""
# If it has one, check the alphabet:
sub_str = self._get_seq_str_and_check_alphabet(sub)
return str(self).index(sub_str, start, end)
def rindex(self, sub, start=0, end=sys.maxsize):
"""Like rfind() but raise ValueError when the substring is not found."""
# If it has one, check the alphabet:
sub_str = self._get_seq_str_and_check_alphabet(sub)
return str(self).rindex(sub_str, start, end)
def startswith(self, prefix, start=0, end=sys.maxsize):
"""Return True if the Seq starts with the given prefix, False otherwise.
This behaves like the python string method of the same name.
Return True if the sequence starts with the specified prefix
(a string or another Seq object), False otherwise.
With optional start, test sequence beginning at that position.
With optional end, stop comparing sequence at that position.
prefix can also be a tuple of strings to try. e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.startswith("GUC")
True
>>> my_rna.startswith("AUG")
False
>>> my_rna.startswith("AUG", 3)
True
>>> my_rna.startswith(("UCC", "UCA", "UCG"), 1)
True
"""
# If it has one, check the alphabet:
if isinstance(prefix, tuple):
prefix_strs = tuple(self._get_seq_str_and_check_alphabet(p) for p in prefix)
return str(self).startswith(prefix_strs, start, end)
else:
prefix_str = self._get_seq_str_and_check_alphabet(prefix)
return str(self).startswith(prefix_str, start, end)
def endswith(self, suffix, start=0, end=sys.maxsize):
"""Return True if the Seq ends with the given suffix, False otherwise.
This behaves like the python string method of the same name.
Return True if the sequence ends with the specified suffix
(a string or another Seq object), False otherwise.
With optional start, test sequence beginning at that position.
With optional end, stop comparing sequence at that position.
suffix can also be a tuple of strings to try. e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_rna.endswith("UUG")
True
>>> my_rna.endswith("AUG")
False
>>> my_rna.endswith("AUG", 0, 18)
True
>>> my_rna.endswith(("UCC", "UCA", "UUG"))
True
"""
# If it has one, check the alphabet:
if isinstance(suffix, tuple):
suffix_strs = tuple(self._get_seq_str_and_check_alphabet(p) for p in suffix)
return str(self).endswith(suffix_strs, start, end)
else:
suffix_str = self._get_seq_str_and_check_alphabet(suffix)
return str(self).endswith(suffix_str, start, end)
def split(self, sep=None, maxsplit=-1):
"""Split method, like that of a python string.
This behaves like the python string method of the same name.
Return a list of the 'words' in the string (as Seq objects),
using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done. If maxsplit is omitted, all
splits are made.
Following the python string method, sep will by default be any
white space (tabs, spaces, newlines) but this is unlikely to
apply to biological sequences.
e.g.
>>> from Bio.Seq import Seq
>>> my_rna = Seq("GUCAUGGCCAUUGUAAUGGGCCGCUGAAAGGGUGCCCGAUAGUUG")
>>> my_aa = my_rna.translate()
>>> my_aa
Seq('VMAIVMGR*KGAR*L', HasStopCodon(ExtendedIUPACProtein(), '*'))
>>> for pep in my_aa.split("*"):
... pep
Seq('VMAIVMGR', HasStopCodon(ExtendedIUPACProtein(), '*'))
Seq('KGAR', HasStopCodon(ExtendedIUPACProtein(), '*'))
Seq('L', HasStopCodon(ExtendedIUPACProtein(), '*'))
>>> for pep in my_aa.split("*", 1):
... pep
Seq('VMAIVMGR', HasStopCodon(ExtendedIUPACProtein(), '*'))
Seq('KGAR*L', HasStopCodon(ExtendedIUPACProtein(), '*'))
See also the rsplit method:
>>> for pep in my_aa.rsplit("*", 1):
... pep
Seq('VMAIVMGR*KGAR', HasStopCodon(ExtendedIUPACProtein(), '*'))
Seq('L', HasStopCodon(ExtendedIUPACProtein(), '*'))
"""
# If it has one, check the alphabet:
sep_str = self._get_seq_str_and_check_alphabet(sep)
# TODO - If the sep is the defined stop symbol, or gap char,
# should we adjust the alphabet?
return [Seq(part, self.alphabet) for part in str(self).split(sep_str, maxsplit)]
def rsplit(self, sep=None, maxsplit=-1):
"""Do a right split method, like that of a python string.
This behaves like the python string method of the same name.
Return a list of the 'words' in the string (as Seq objects),
using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done COUNTING FROM THE RIGHT.
If maxsplit is omitted, all splits are made.
Following the python string method, sep will by default be any
white space (tabs, spaces, newlines) but this is unlikely to
apply to biological sequences.
e.g. print(my_seq.rsplit("*",1))
See also the split method.
"""
# If it has one, check the alphabet:
sep_str = self._get_seq_str_and_check_alphabet(sep)
return [
Seq(part, self.alphabet) for part in str(self).rsplit(sep_str, maxsplit)
]
def strip(self, chars=None):
"""Return a new Seq object with leading and trailing ends stripped.
This behaves like the python string method of the same name.
Optional argument chars defines which characters to remove. If
omitted or None (default) then as for the python string method,
this defaults to removing any white space.
e.g. print(my_seq.strip("-"))
See also the lstrip and rstrip methods.
"""
# If it has one, check the alphabet:
strip_str = self._get_seq_str_and_check_alphabet(chars)
return Seq(str(self).strip(strip_str), self.alphabet)
def lstrip(self, chars=None):
"""Return a new Seq object with leading (left) end stripped.
This behaves like the python string method of the same name.
Optional argument chars defines which characters to remove. If
omitted or None (default) then as for the python string method,
this defaults to removing any white space.
e.g. print(my_seq.lstrip("-"))
See also the strip and rstrip methods.
"""
# If it has one, check the alphabet:
strip_str = self._get_seq_str_and_check_alphabet(chars)
return Seq(str(self).lstrip(strip_str), self.alphabet)
def rstrip(self, chars=None):
"""Return a new Seq object with trailing (right) end stripped.
This behaves like the python string method of the same name.
Optional argument chars defines which characters to remove. If
omitted or None (default) then as for the python string method,
this defaults to removing any white space.
e.g. Removing a nucleotide sequence's polyadenylation (poly-A tail):
>>> from Bio.Alphabet import IUPAC
>>> from Bio.Seq import Seq
>>> my_seq = Seq("CGGTACGCTTATGTCACGTAGAAAAAA", IUPAC.unambiguous_dna)
>>> my_seq
Seq('CGGTACGCTTATGTCACGTAGAAAAAA', IUPACUnambiguousDNA())
>>> my_seq.rstrip("A")
Seq('CGGTACGCTTATGTCACGTAG', IUPACUnambiguousDNA())
See also the strip and lstrip methods.
"""
# If it has one, check the alphabet:
strip_str = self._get_seq_str_and_check_alphabet(chars)
return Seq(str(self).rstrip(strip_str), self.alphabet)
def upper(self):
"""Return an upper case copy of the sequence.
>>> from Bio.Alphabet import HasStopCodon, generic_protein
>>> from Bio.Seq import Seq
>>> my_seq = Seq("VHLTPeeK*", HasStopCodon(generic_protein))
>>> my_seq
Seq('VHLTPeeK*', HasStopCodon(ProteinAlphabet(), '*'))
>>> my_seq.lower()
Seq('vhltpeek*', HasStopCodon(ProteinAlphabet(), '*'))
>>> my_seq.upper()
Seq('VHLTPEEK*', HasStopCodon(ProteinAlphabet(), '*'))
This will adjust the alphabet if required. See also the lower method.
"""
return Seq(str(self).upper(), self.alphabet._upper())
def lower(self):
"""Return a lower case copy of the sequence.
This will adjust the alphabet if required. Note that the IUPAC
alphabets are upper case only, and thus a generic alphabet must be
substituted.
>>> from Bio.Alphabet import Gapped, generic_dna
>>> from Bio.Alphabet import IUPAC
>>> from Bio.Seq import Seq
>>> my_seq = Seq("CGGTACGCTTATGTCACGTAG*AAAAAA",
... Gapped(IUPAC.unambiguous_dna, "*"))
>>> my_seq
Seq('CGGTACGCTTATGTCACGTAG*AAAAAA', Gapped(IUPACUnambiguousDNA(), '*'))
>>> my_seq.lower()
Seq('cggtacgcttatgtcacgtag*aaaaaa', Gapped(DNAAlphabet(), '*'))
See also the upper method.
"""
return Seq(str(self).lower(), self.alphabet._lower())
def encode(self, encoding="utf-8", errors="strict"):
"""Return an encoded version of the sequence as a bytes object.
The Seq object aims to match the interfact of a Python string.
(This means on Python 3 it acts like a unicode string.)
This is essentially to save you doing str(my_seq).encode() when
you need a bytes string, for example for computing a hash:
>>> from Bio.Seq import Seq
>>> Seq("ACGT").encode("ascii")
b'ACGT'
"""
return str(self).encode(encoding, errors)
def complement(self):
"""Return the complement sequence by creating a new Seq object.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import IUPAC
>>> my_dna = Seq("CCCCCGATAG", IUPAC.unambiguous_dna)
>>> my_dna
Seq('CCCCCGATAG', IUPACUnambiguousDNA())
>>> my_dna.complement()
Seq('GGGGGCTATC', IUPACUnambiguousDNA())
You can of course used mixed case sequences,
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> my_dna = Seq("CCCCCgatA-GD", generic_dna)
>>> my_dna
Seq('CCCCCgatA-GD', DNAAlphabet())
>>> my_dna.complement()
Seq('GGGGGctaT-CH', DNAAlphabet())
Note in the above example, ambiguous character D denotes
G, A or T so its complement is H (for C, T or A).
Trying to complement a protein sequence raises an exception.
>>> my_protein = Seq("MAIVMGR", IUPAC.protein)
>>> my_protein.complement()
Traceback (most recent call last):
...
ValueError: Proteins do not have complements!
"""
base = Alphabet._get_base_alphabet(self.alphabet)
if isinstance(base, Alphabet.ProteinAlphabet):
raise ValueError("Proteins do not have complements!")
if isinstance(base, Alphabet.DNAAlphabet):
ttable = _dna_complement_table
elif isinstance(base, Alphabet.RNAAlphabet):
ttable = _rna_complement_table
elif ("U" in self._data or "u" in self._data) and (
"T" in self._data or "t" in self._data
):
# TODO - Handle this cleanly?
raise ValueError("Mixed RNA/DNA found")
elif "U" in self._data or "u" in self._data:
ttable = _rna_complement_table
else:
ttable = _dna_complement_table
# Much faster on really long sequences than the previous loop based
# one. Thanks to Michael Palmer, University of Waterloo.
return Seq(str(self).translate(ttable), self.alphabet)