forked from biopython/biopython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSeq.py
3504 lines (2937 loc) · 123 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-2023 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.
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 collections
import numbers
import warnings
from abc import ABC
from abc import abstractmethod
from typing import overload, Optional, Union, Dict
from Bio import BiopythonDeprecationWarning
from Bio import BiopythonWarning
from Bio.Data import CodonTable
from Bio.Data import IUPACData
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 bytes object 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.
"""
keys = "".join(complement_mapping.keys()).encode("ASCII")
values = "".join(complement_mapping.values()).encode("ASCII")
return bytes.maketrans(keys + keys.lower(), values + values.lower())
ambiguous_dna_complement = dict(IUPACData.ambiguous_dna_complement)
ambiguous_dna_complement["U"] = ambiguous_dna_complement["T"]
_dna_complement_table = _maketrans(ambiguous_dna_complement)
del ambiguous_dna_complement
ambiguous_rna_complement = dict(IUPACData.ambiguous_rna_complement)
ambiguous_rna_complement["T"] = ambiguous_rna_complement["U"]
_rna_complement_table = _maketrans(ambiguous_rna_complement)
del ambiguous_rna_complement
class SequenceDataAbstractBaseClass(ABC):
"""Abstract base class for sequence content providers.
Most users will not need to use this class. It is used internally as a base
class for sequence content provider classes such as _UndefinedSequenceData
defined in this module, and _TwoBitSequenceData in Bio.SeqIO.TwoBitIO.
Instances of these classes can be used instead of a ``bytes`` object as the
data argument when creating a Seq object, and provide the sequence content
only when requested via ``__getitem__``. This allows lazy parsers to load
and parse sequence data from a file only for the requested sequence regions,
and _UndefinedSequenceData instances to raise an exception when undefined
sequence data are requested.
Future implementations of lazy parsers that similarly provide on-demand
parsing of sequence data should use a subclass of this abstract class and
implement the abstract methods ``__len__`` and ``__getitem__``:
* ``__len__`` must return the sequence length;
* ``__getitem__`` must return
* a ``bytes`` object for the requested region; or
* a new instance of the subclass for the requested region; or
* raise an ``UndefinedSequenceError``.
Calling ``__getitem__`` for a sequence region of size zero should always
return an empty ``bytes`` object.
Calling ``__getitem__`` for the full sequence (as in data[:]) should
either return a ``bytes`` object with the full sequence, or raise an
``UndefinedSequenceError``.
Subclasses of SequenceDataAbstractBaseClass must call ``super().__init__()``
as part of their ``__init__`` method.
"""
__slots__ = ()
def __init__(self):
"""Check if ``__getitem__`` returns a bytes-like object."""
assert self[:0] == b""
@abstractmethod
def __len__(self):
pass
@abstractmethod
def __getitem__(self, key):
pass
def __bytes__(self):
return self[:]
def __hash__(self):
return hash(bytes(self))
def __eq__(self, other):
return bytes(self) == other
def __lt__(self, other):
return bytes(self) < other
def __le__(self, other):
return bytes(self) <= other
def __gt__(self, other):
return bytes(self) > other
def __ge__(self, other):
return bytes(self) >= other
def __add__(self, other):
try:
return bytes(self) + bytes(other)
except UndefinedSequenceError:
return NotImplemented
# will be handled by _UndefinedSequenceData.__radd__ or
# by _PartiallyDefinedSequenceData.__radd__
def __radd__(self, other):
return other + bytes(self)
def __mul__(self, other):
return other * bytes(self)
def __contains__(self, item):
return bytes(self).__contains__(item)
def decode(self, encoding="utf-8"):
"""Decode the data as bytes using the codec registered for encoding.
encoding
The encoding with which to decode the bytes.
"""
return bytes(self).decode(encoding)
def count(self, sub, start=None, end=None):
"""Return the number of non-overlapping occurrences of sub in data[start:end].
Optional arguments start and end are interpreted as in slice notation.
This method behaves as the count method of Python strings.
"""
return bytes(self).count(sub, start, end)
def find(self, sub, start=None, end=None):
"""Return the lowest index in data where subsection sub is found.
Return the lowest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return bytes(self).find(sub, start, end)
def rfind(self, sub, start=None, end=None):
"""Return the highest index in data where subsection sub is found.
Return the highest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return bytes(self).rfind(sub, start, end)
def index(self, sub, start=None, end=None):
"""Return the lowest index in data where subsection sub is found.
Return the lowest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Raises ValueError when the subsection is not found.
"""
return bytes(self).index(sub, start, end)
def rindex(self, sub, start=None, end=None):
"""Return the highest index in data where subsection sub is found.
Return the highest index in data where subsection sub is found,
such that sub is contained within data[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Raise ValueError when the subsection is not found.
"""
return bytes(self).rindex(sub, start, end)
def startswith(self, prefix, start=None, end=None):
"""Return True if data starts with the specified prefix, False otherwise.
With optional start, test data beginning at that position.
With optional end, stop comparing data at that position.
prefix can also be a tuple of bytes to try.
"""
return bytes(self).startswith(prefix, start, end)
def endswith(self, suffix, start=None, end=None):
"""Return True if data ends with the specified suffix, False otherwise.
With optional start, test data beginning at that position.
With optional end, stop comparing data at that position.
suffix can also be a tuple of bytes to try.
"""
return bytes(self).endswith(suffix, start, end)
def split(self, sep=None, maxsplit=-1):
"""Return a list of the sections in the data, using sep as the delimiter.
sep
The delimiter according which to split the data.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
"""
return bytes(self).split(sep, maxsplit)
def rsplit(self, sep=None, maxsplit=-1):
"""Return a list of the sections in the data, using sep as the delimiter.
sep
The delimiter according which to split the data.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Splitting is done starting at the end of the data and working to the front.
"""
return bytes(self).rsplit(sep, maxsplit)
def strip(self, chars=None):
"""Strip leading and trailing characters contained in the argument.
If the argument is omitted or None, strip leading and trailing ASCII whitespace.
"""
return bytes(self).strip(chars)
def lstrip(self, chars=None):
"""Strip leading characters contained in the argument.
If the argument is omitted or None, strip leading ASCII whitespace.
"""
return bytes(self).lstrip(chars)
def rstrip(self, chars=None):
"""Strip trailing characters contained in the argument.
If the argument is omitted or None, strip trailing ASCII whitespace.
"""
return bytes(self).rstrip(chars)
def removeprefix(self, prefix):
"""Remove the prefix if present."""
# Want to do just this, but need Python 3.9+
# return bytes(self).removeprefix(prefix)
data = bytes(self)
try:
return data.removeprefix(prefix)
except AttributeError:
if data.startswith(prefix):
return data[len(prefix) :]
else:
return data
def removesuffix(self, suffix):
"""Remove the suffix if present."""
# Want to do just this, but need Python 3.9+
# return bytes(self).removesuffix(suffix)
data = bytes(self)
try:
return data.removesuffix(suffix)
except AttributeError:
if data.startswith(suffix):
return data[: -len(suffix)]
else:
return data
def upper(self):
"""Return a copy of data with all ASCII characters converted to uppercase."""
return bytes(self).upper()
def lower(self):
"""Return a copy of data with all ASCII characters converted to lowercase."""
return bytes(self).lower()
def isupper(self):
"""Return True if all ASCII characters in data are uppercase.
If there are no cased characters, the method returns False.
"""
return bytes(self).isupper()
def islower(self):
"""Return True if all ASCII characters in data are lowercase.
If there are no cased characters, the method returns False.
"""
return bytes(self).islower()
def replace(self, old, new):
"""Return a copy with all occurrences of substring old replaced by new."""
return bytes(self).replace(old, new)
def translate(self, table, delete=b""):
"""Return a copy with each character mapped by the given translation table.
table
Translation table, which must be a bytes object of length 256.
All characters occurring in the optional argument delete are removed.
The remaining characters are mapped through the given translation table.
"""
return bytes(self).translate(table, delete)
@property
def defined(self):
"""Return True if the sequence is defined, False if undefined or partially defined.
Zero-length sequences are always considered to be defined.
"""
return True
@property
def defined_ranges(self):
"""Return a tuple of the ranges where the sequence contents is defined.
The return value has the format ((start1, end1), (start2, end2), ...).
"""
length = len(self)
if length > 0:
return ((0, length),)
else:
return ()
class _SeqAbstractBaseClass(ABC):
"""Abstract base class for the Seq and MutableSeq classes (PRIVATE).
Most users will not need to use this class. It is used internally as an
abstract base class for Seq and MutableSeq, as most of their methods are
identical.
"""
__slots__ = ("_data",)
__array_ufunc__ = None # turn off numpy Ufuncs
@abstractmethod
def __init__(self):
pass
def __bytes__(self):
return bytes(self._data)
def __repr__(self):
"""Return (truncated) representation of the sequence."""
data = self._data
if isinstance(data, _UndefinedSequenceData):
return f"Seq(None, length={len(self)})"
if isinstance(data, _PartiallyDefinedSequenceData):
d = {}
for position, seq in data._data.items():
if len(seq) > 60:
start = seq[:54].decode("ASCII")
end = seq[-3:].decode("ASCII")
seq = f"{start}...{end}"
else:
seq = seq.decode("ASCII")
d[position] = seq
return "Seq(%r, length=%d)" % (d, len(self))
if len(data) > 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
start = data[:54].decode("ASCII")
end = data[-3:].decode("ASCII")
return f"{self.__class__.__name__}('{start}...{end}')"
else:
data = data.decode("ASCII")
return f"{self.__class__.__name__}('{data}')"
def __str__(self):
"""Return the full sequence as a python string."""
return self._data.decode("ASCII")
def __eq__(self, other):
"""Compare the sequence to another sequence or a string.
Sequences are equal to each other if their sequence contents is
identical:
>>> from Bio.Seq import Seq, MutableSeq
>>> seq1 = Seq("ACGT")
>>> seq2 = Seq("ACGT")
>>> mutable_seq = MutableSeq("ACGT")
>>> seq1 == seq2
True
>>> seq1 == mutable_seq
True
>>> seq1 == "ACGT"
True
Note that the sequence objects themselves are not identical to each
other:
>>> id(seq1) == id(seq2)
False
>>> seq1 is seq2
False
Sequences can also be compared to strings, ``bytes``, and ``bytearray``
objects:
>>> seq1 == "ACGT"
True
>>> seq1 == b"ACGT"
True
>>> seq1 == bytearray(b"ACGT")
True
"""
if isinstance(other, _SeqAbstractBaseClass):
return self._data == other._data
elif isinstance(other, str):
return self._data == other.encode("ASCII")
else:
return self._data == other
def __lt__(self, other):
"""Implement the less-than operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data < other._data
elif isinstance(other, str):
return self._data < other.encode("ASCII")
else:
return self._data < other
def __le__(self, other):
"""Implement the less-than or equal operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data <= other._data
elif isinstance(other, str):
return self._data <= other.encode("ASCII")
else:
return self._data <= other
def __gt__(self, other):
"""Implement the greater-than operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data > other._data
elif isinstance(other, str):
return self._data > other.encode("ASCII")
else:
return self._data > other
def __ge__(self, other):
"""Implement the greater-than or equal operand."""
if isinstance(other, _SeqAbstractBaseClass):
return self._data >= other._data
elif isinstance(other, str):
return self._data >= other.encode("ASCII")
else:
return self._data >= other
def __len__(self):
"""Return the length of the sequence."""
return len(self._data)
def __iter__(self):
"""Return an iterable of the sequence."""
return self._data.decode("ASCII").__iter__()
@overload
def __getitem__(self, index: int) -> str:
...
@overload
def __getitem__(self, index: slice) -> "Seq":
...
def __getitem__(self, index):
"""Return a subsequence as a single letter or as a sequence object.
If the index is an integer, a single letter is returned as a Python
string:
>>> seq = Seq('ACTCGACGTCG')
>>> seq[5]
'A'
Otherwise, a new sequence object of the same class is returned:
>>> seq[5:8]
Seq('ACG')
>>> mutable_seq = MutableSeq('ACTCGACGTCG')
>>> mutable_seq[5:8]
MutableSeq('ACG')
"""
if isinstance(index, numbers.Integral):
# Return a single letter as a string
return chr(self._data[index])
else:
# Return the (sub)sequence as another Seq/MutableSeq object
return self.__class__(self._data[index])
def __add__(self, other):
"""Add a sequence or string to this sequence.
>>> from Bio.Seq import Seq, MutableSeq
>>> Seq("MELKI") + "LV"
Seq('MELKILV')
>>> MutableSeq("MELKI") + "LV"
MutableSeq('MELKILV')
"""
if isinstance(other, _SeqAbstractBaseClass):
return self.__class__(self._data + other._data)
elif isinstance(other, str):
return self.__class__(self._data + other.encode("ASCII"))
else:
# If other is a SeqRecord, then SeqRecord's __radd__ will handle
# this. If not, returning NotImplemented will trigger a TypeError.
return NotImplemented
def __radd__(self, other):
"""Add a sequence string on the left.
>>> from Bio.Seq import Seq, MutableSeq
>>> "LV" + Seq("MELKI")
Seq('LVMELKI')
>>> "LV" + MutableSeq("MELKI")
MutableSeq('LVMELKI')
Adding two sequence objects is handled via the __add__ method.
"""
if isinstance(other, str):
return self.__class__(other.encode("ASCII") + self._data)
else:
return NotImplemented
def __mul__(self, other):
"""Multiply sequence by integer.
>>> from Bio.Seq import Seq, MutableSeq
>>> Seq('ATG') * 2
Seq('ATGATG')
>>> MutableSeq('ATG') * 2
MutableSeq('ATGATG')
"""
if not isinstance(other, numbers.Integral):
raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type")
# we would like to simply write
# data = self._data * other
# here, but currently that causes a bug on PyPy if self._data is a
# bytearray and other is a numpy integer. Using this workaround:
data = self._data.__mul__(other)
return self.__class__(data)
def __rmul__(self, other):
"""Multiply integer by sequence.
>>> from Bio.Seq import Seq
>>> 2 * Seq('ATG')
Seq('ATGATG')
"""
if not isinstance(other, numbers.Integral):
raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type")
# we would like to simply write
# data = self._data * other
# here, but currently that causes a bug on PyPy if self._data is a
# bytearray and other is a numpy integer. Using this workaround:
data = self._data.__mul__(other)
return self.__class__(data)
def __imul__(self, other):
"""Multiply the sequence object by other and assign.
>>> from Bio.Seq import Seq
>>> seq = Seq('ATG')
>>> seq *= 2
>>> seq
Seq('ATGATG')
Note that this is different from in-place multiplication. The ``seq``
variable is reassigned to the multiplication result, but any variable
pointing to ``seq`` will remain unchanged:
>>> seq = Seq('ATG')
>>> seq2 = seq
>>> id(seq) == id(seq2)
True
>>> seq *= 2
>>> seq
Seq('ATGATG')
>>> seq2
Seq('ATG')
>>> id(seq) == id(seq2)
False
"""
if not isinstance(other, numbers.Integral):
raise TypeError(f"can't multiply {self.__class__.__name__} by non-int type")
# we would like to simply write
# data = self._data * other
# here, but currently that causes a bug on PyPy if self._data is a
# bytearray and other is a numpy integer. Using this workaround:
data = self._data.__mul__(other)
return self.__class__(data)
def count(self, sub, start=None, end=None):
"""Return a non-overlapping count, like that of a python string.
The number of occurrences of substring argument sub in the
(sub)sequence given by [start:end] is returned as an integer.
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 the ``count`` method of Seq and MutableSeq
objects, like that of Python strings, do a non-overlapping search, this
may not give the answer you expect:
>>> "AAAA".count("AA")
2
>>> print(Seq("AAAA").count("AA"))
2
For an overlapping search, use the ``count_overlap`` method:
>>> print(Seq("AAAA").count_overlap("AA"))
3
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.count(sub, start, end)
def count_overlap(self, sub, start=None, end=None):
"""Return an overlapping count.
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
For a non-overlapping search, use the ``count`` method:
>>> print(Seq("AAAA").count("AA"))
2
Where substrings do not overlap, ``count_overlap`` behaves 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.
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
data = self._data
overlap_count = 0
while True:
start = data.find(sub, start, end) + 1
if start != 0:
overlap_count += 1
else:
return overlap_count
def __contains__(self, item):
"""Return True if item is a subsequence of the sequence, and False otherwise.
e.g.
>>> from Bio.Seq import Seq, MutableSeq
>>> my_dna = Seq("ATATGAAATTTGAAAA")
>>> "AAA" in my_dna
True
>>> Seq("AAA") in my_dna
True
>>> MutableSeq("AAA") in my_dna
True
"""
if isinstance(item, _SeqAbstractBaseClass):
item = bytes(item)
elif isinstance(item, str):
item = item.encode("ASCII")
return item in self._data
def find(self, sub, start=None, end=None):
"""Return the lowest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the lowest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search 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
The next typical start codon can then be found by starting the search
at position 4:
>>> my_rna.find("AUG", 4)
15
See the ``search`` method to find the locations of multiple subsequences
at the same time.
"""
if isinstance(sub, _SeqAbstractBaseClass):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.find(sub, start, end)
def rfind(self, sub, start=None, end=None):
"""Return the highest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the highest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search 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
The location of the typical start codon before that can be found by
ending the search at position 15:
>>> my_rna.rfind("AUG", end=15)
3
See the ``search`` method to find the locations of multiple subsequences
at the same time.
"""
if isinstance(sub, _SeqAbstractBaseClass):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.rfind(sub, start, end)
def index(self, sub, start=None, end=None):
"""Return the lowest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the lowest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search for
- start - optional integer, slice start
- end - optional integer, slice end
Raises a ValueError 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.index("AUG")
3
The next typical start codon can then be found by starting the search
at position 4:
>>> my_rna.index("AUG", 4)
15
This method performs the same search as the ``find`` method. However,
if the subsequence is not found, ``find`` returns -1 while ``index``
raises a ValueError:
>>> my_rna.index("T")
Traceback (most recent call last):
...
ValueError: ...
>>> my_rna.find("T")
-1
See the ``search`` method to find the locations of multiple subsequences
at the same time.
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.index(sub, start, end)
def rindex(self, sub, start=None, end=None):
"""Return the highest index in the sequence where subsequence sub is found.
With optional arguments start and end, return the highest index in the
sequence such that the subsequence sub is contained within the sequence
region [start:end].
Arguments:
- sub - a string or another Seq or MutableSeq object to search 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.rindex("AUG")
15
The location of the typical start codon before that can be found by
ending the search at position 15:
>>> my_rna.rindex("AUG", end=15)
3
This method performs the same search as the ``rfind`` method. However,
if the subsequence is not found, ``rfind`` returns -1 which ``rindex``
raises a ValueError:
>>> my_rna.rindex("T")
Traceback (most recent call last):
...
ValueError: ...
>>> my_rna.rfind("T")
-1
See the ``search`` method to find the locations of multiple subsequences
at the same time.
"""
if isinstance(sub, MutableSeq):
sub = sub._data
elif isinstance(sub, Seq):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, (bytes, bytearray)):
raise TypeError(
"a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% type(sub)
)
return self._data.rindex(sub, start, end)
def search(self, subs):
"""Search the substrings subs in self and yield the index and substring found.
Arguments:
- subs - a list of strings, Seq, MutableSeq, bytes, or bytearray
objects containing the substrings to search for.
>>> from Bio.Seq import Seq
>>> dna = Seq("GTCATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAGTTG")
>>> matches = dna.search(["CC", Seq("ATTG"), "ATTG", Seq("CCC")])
>>> for index, substring in matches:
... print(index, substring)
...
7 CC
9 ATTG
20 CC
34 CC
34 CCC
35 CC
"""
subdict = collections.defaultdict(set)
for index, sub in enumerate(subs):
if isinstance(sub, (_SeqAbstractBaseClass, bytearray)):
sub = bytes(sub)
elif isinstance(sub, str):
sub = sub.encode("ASCII")
elif not isinstance(sub, bytes):
raise TypeError(
"subs[%d]: a Seq, MutableSeq, str, bytes, or bytearray object is required, not '%s'"
% (index, type(sub))
)
length = len(sub)