forked from biopython/biopython
/
SeqFeature.py
2204 lines (1813 loc) · 73.9 KB
/
SeqFeature.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-2003 Jeff Chang.
# Copyright 2001-2008 Brad Chapman.
# Copyright 2005-2016 by Peter Cock.
# Copyright 2006-2009 Michiel de Hoon.
# 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.
"""Represent a Sequence Feature holding info about a part of a sequence.
This is heavily modeled after the Biocorba SeqFeature objects, and
may be pretty biased towards GenBank stuff since I'm writing it
for the GenBank parser output...
What's here:
Base class to hold a Feature
----------------------------
Classes:
- SeqFeature
Hold information about a Reference
----------------------------------
This is an attempt to create a General class to hold Reference type
information.
Classes:
- Reference
Specify locations of a feature on a Sequence
--------------------------------------------
This aims to handle, in Ewan Birney's words, 'the dreaded fuzziness issue'.
This has the advantages of allowing us to handle fuzzy stuff in case anyone
needs it, and also be compatible with BioPerl etc and BioSQL.
Classes:
- FeatureLocation - Specify the start and end location of a feature.
- CompoundLocation - Collection of FeatureLocation objects (for joins etc).
- ExactPosition - Specify the position as being exact.
- WithinPosition - Specify a position occurring within some range.
- BetweenPosition - Specify a position occurring between a range (OBSOLETE?).
- BeforePosition - Specify the position as being found before some base.
- AfterPosition - Specify the position as being found after some base.
- OneOfPosition - Specify a position where the location can be multiple positions.
- UncertainPosition - Specify a specific position which is uncertain.
- UnknownPosition - Represents missing information like '?' in UniProt.
"""
from collections import OrderedDict
from Bio.Seq import MutableSeq, reverse_complement
class SeqFeature:
"""Represent a Sequence Feature on an object.
Attributes:
- location - the location of the feature on the sequence (FeatureLocation)
- type - the specified type of the feature (ie. CDS, exon, repeat...)
- location_operator - a string specifying how this SeqFeature may
be related to others. For example, in the example GenBank feature
shown below, the location_operator would be "join". This is a proxy
for feature.location.operator and only applies to compound locations.
- strand - A value specifying on which strand (of a DNA sequence, for
instance) the feature deals with. 1 indicates the plus strand, -1
indicates the minus strand, 0 indicates stranded but unknown (? in GFF3),
while the default of None indicates that strand doesn't apply (dot in GFF3,
e.g. features on proteins). Note this is a shortcut for accessing the
strand property of the feature's location.
- id - A string identifier for the feature.
- ref - A reference to another sequence. This could be an accession
number for some different sequence. Note this is a shortcut for the
reference property of the feature's location.
- ref_db - A different database for the reference accession number.
Note this is a shortcut for the reference property of the location
- qualifiers - A dictionary of qualifiers on the feature. These are
analogous to the qualifiers from a GenBank feature table. The keys of
the dictionary are qualifier names, the values are the qualifier
values. As of Biopython 1.69 this is an ordered dictionary.
"""
def __init__(
self,
location=None,
type="",
location_operator="",
strand=None,
id="<unknown id>",
qualifiers=None,
sub_features=None,
ref=None,
ref_db=None,
):
"""Initialize a SeqFeature on a Sequence.
location can either be a FeatureLocation (with strand argument also
given if required), or None.
e.g. With no strand, on the forward strand, and on the reverse strand:
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> f1 = SeqFeature(FeatureLocation(5, 10), type="domain")
>>> f1.strand == f1.location.strand == None
True
>>> f2 = SeqFeature(FeatureLocation(7, 110, strand=1), type="CDS")
>>> f2.strand == f2.location.strand == +1
True
>>> f3 = SeqFeature(FeatureLocation(9, 108, strand=-1), type="CDS")
>>> f3.strand == f3.location.strand == -1
True
An invalid strand will trigger an exception:
>>> f4 = SeqFeature(FeatureLocation(50, 60), strand=2)
Traceback (most recent call last):
...
ValueError: Strand should be +1, -1, 0 or None, not 2
Similarly if set via the FeatureLocation directly:
>>> loc4 = FeatureLocation(50, 60, strand=2)
Traceback (most recent call last):
...
ValueError: Strand should be +1, -1, 0 or None, not 2
For exact start/end positions, an integer can be used (as shown above)
as shorthand for the ExactPosition object. For non-exact locations, the
FeatureLocation must be specified via the appropriate position objects.
Note that the strand, ref and ref_db arguments to the SeqFeature are
now obsolete and will be deprecated in a future release (which will
give warning messages) and later removed. Set them via the location
object instead.
Note that location_operator and sub_features arguments can no longer
be used, instead do this via the CompoundLocation object.
"""
if (
location is not None
and not isinstance(location, FeatureLocation)
and not isinstance(location, CompoundLocation)
):
raise TypeError(
"FeatureLocation, CompoundLocation (or None) required for the location"
)
self.location = location
self.type = type
if location_operator:
# TODO - Deprecation warning
self.location_operator = location_operator
if strand is not None:
# TODO - Deprecation warning
self.strand = strand
self.id = id
if qualifiers is None:
qualifiers = OrderedDict()
self.qualifiers = qualifiers
if sub_features is not None:
raise TypeError("Rather than sub_features, use a CompoundFeatureLocation")
if ref is not None:
# TODO - Deprecation warning
self.ref = ref
if ref_db is not None:
# TODO - Deprecation warning
self.ref_db = ref_db
def _get_strand(self):
"""Get function for the strand property (PRIVATE)."""
return self.location.strand
def _set_strand(self, value):
"""Set function for the strand property (PRIVATE)."""
try:
self.location.strand = value
except AttributeError:
if self.location is None:
if value is not None:
raise ValueError("Can't set strand without a location.") from None
else:
raise
strand = property(
fget=_get_strand,
fset=_set_strand,
doc="""Feature's strand
This is a shortcut for feature.location.strand
""",
)
def _get_ref(self):
"""Get function for the reference property (PRIVATE)."""
try:
return self.location.ref
except AttributeError:
return None
def _set_ref(self, value):
"""Set function for the reference property (PRIVATE)."""
try:
self.location.ref = value
except AttributeError:
if self.location is None:
if value is not None:
raise ValueError("Can't set ref without a location.") from None
else:
raise
ref = property(
fget=_get_ref,
fset=_set_ref,
doc="""Feature location reference (e.g. accession).
This is a shortcut for feature.location.ref
""",
)
def _get_ref_db(self):
"""Get function for the database reference property (PRIVATE)."""
try:
return self.location.ref_db
except AttributeError:
return None
def _set_ref_db(self, value):
"""Set function for the database reference property (PRIVATE)."""
self.location.ref_db = value
ref_db = property(
fget=_get_ref_db,
fset=_set_ref_db,
doc="""Feature location reference's database.
This is a shortcut for feature.location.ref_db
""",
)
def _get_location_operator(self):
"""Get function for the location operator property (PRIVATE)."""
try:
return self.location.operator
except AttributeError:
return None
def _set_location_operator(self, value):
"""Set function for the location operator property (PRIVATE)."""
if value:
if isinstance(self.location, CompoundLocation):
self.location.operator = value
elif self.location is None:
raise ValueError(
"Location is None so can't set its operator (to %r)" % value
)
else:
raise ValueError("Only CompoundLocation gets an operator (%r)" % value)
location_operator = property(
fget=_get_location_operator,
fset=_set_location_operator,
doc="Location operator for compound locations (e.g. join).",
)
def __repr__(self):
"""Represent the feature as a string for debugging."""
answer = "%s(%s" % (self.__class__.__name__, repr(self.location))
if self.type:
answer += ", type=%s" % repr(self.type)
if self.location_operator:
answer += ", location_operator=%s" % repr(self.location_operator)
if self.id and self.id != "<unknown id>":
answer += ", id=%s" % repr(self.id)
if self.ref:
answer += ", ref=%s" % repr(self.ref)
if self.ref_db:
answer += ", ref_db=%s" % repr(self.ref_db)
answer += ")"
return answer
def __str__(self):
"""Return the full feature as a python string."""
out = "type: %s\n" % self.type
out += "location: %s\n" % self.location
if self.id and self.id != "<unknown id>":
out += "id: %s\n" % self.id
out += "qualifiers:\n"
for qual_key in sorted(self.qualifiers):
out += " Key: %s, Value: %s\n" % (qual_key, self.qualifiers[qual_key])
return out
def _shift(self, offset):
"""Return a copy of the feature with its location shifted (PRIVATE).
The annotation qaulifiers are copied.
"""
return SeqFeature(
location=self.location._shift(offset),
type=self.type,
location_operator=self.location_operator,
id=self.id,
qualifiers=OrderedDict(self.qualifiers.items()),
)
def _flip(self, length):
"""Return a copy of the feature with its location flipped (PRIVATE).
The argument length gives the length of the parent sequence. For
example a location 0..20 (+1 strand) with parent length 30 becomes
after flipping 10..30 (-1 strand). Strandless (None) or unknown
strand (0) remain like that - just their end points are changed.
The annotation qaulifiers are copied.
"""
return SeqFeature(
location=self.location._flip(length),
type=self.type,
location_operator=self.location_operator,
id=self.id,
qualifiers=OrderedDict(self.qualifiers.items()),
)
def extract(self, parent_sequence):
"""Extract the feature's sequence from supplied parent sequence.
The parent_sequence can be a Seq like object or a string, and will
generally return an object of the same type. The exception to this is
a MutableSeq as the parent sequence will return a Seq object.
This should cope with complex locations including complements, joins
and fuzzy positions. Even mixed strand features should work! This
also covers features on protein sequences (e.g. domains), although
here reverse strand features are not permitted.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_protein
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein)
>>> f = SeqFeature(FeatureLocation(8, 15), type="domain")
>>> f.extract(seq)
Seq('VALIVIC', ProteinAlphabet())
If the FeatureLocation is None, e.g. when parsing invalid locus
locations in the GenBank parser, extract() will raise a ValueError.
>>> from Bio.Seq import Seq
>>> from Bio.SeqFeature import SeqFeature
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein)
>>> f = SeqFeature(None, type="domain")
>>> f.extract(seq)
Traceback (most recent call last):
...
ValueError: The feature's .location is None. Check the sequence file for a valid location.
Note - currently only compound features of type "join" are supported.
"""
if self.location is None:
raise ValueError(
"The feature's .location is None. Check the "
"sequence file for a valid location."
)
return self.location.extract(parent_sequence)
def translate(
self,
parent_sequence,
table="Standard",
start_offset=None,
stop_symbol="*",
to_stop=False,
cds=None,
gap=None,
):
"""Get a translation of the feature's sequence.
This method is intended for CDS or other features that code proteins
and is a shortcut that will both extract the feature and
translate it, taking into account the codon_start and transl_table
qualifiers, if they are present. If they are not present the
value of the arguments "table" and "start_offset" are used.
The "cds" parameter is set to "True" if the feature is of type
"CDS" but can be overridden by giving an explicit argument.
The arguments stop_symbol, to_stop and gap have the same meaning
as Seq.translate, refer to that documentation for further information.
Arguments:
- parent_sequence - This method will translate DNA or RNA sequences,
and those with a nucleotide or generic alphabet. Trying to
translate a protein sequence raises an exception.
- table - Which codon table to use if there is no transl_table
qualifier for this feature. This can be either a name
(string), an NCBI identifier (integer), or a CodonTable
object (useful for non-standard genetic codes). This
defaults to the "Standard" table.
- start_offset - offset at which the first complete codon of a
coding feature can be found, relative to the first base of
that feature. Has a valid value of 0, 1 or 2. NOTE: this
uses python's 0-based numbering whereas the codon_start
qualifier in files from NCBI use 1-based numbering.
Will override a codon_start qualifier
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_dna
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> seq = Seq("GGTTACACTTACCGATAATGTCTCTGATGA", generic_dna)
>>> f = SeqFeature(FeatureLocation(0, 30), type="CDS")
>>> f.qualifiers['transl_table'] = [11]
Note that features of type CDS are subject to the usual
checks at translation. But you can override this behaviour
by giving explicit arguments:
>>> f.translate(seq, cds=False)
Seq('GYTYR*CL**', HasStopCodon(ExtendedIUPACProtein(), '*'))
Now use the start_offset argument to change the frame. Note
this uses python 0-based numbering.
>>> f.translate(seq, start_offset=1, cds=False)
Seq('VTLTDNVSD', ExtendedIUPACProtein())
Alternatively use the codon_start qualifier to do the same
thing. Note: this uses 1-based numbering, which is found
in files from NCBI.
>>> f.qualifiers['codon_start'] = [2]
>>> f.translate(seq, cds=False)
Seq('VTLTDNVSD', ExtendedIUPACProtein())
"""
# see if this feature should be translated in a different
# frame using the "codon_start" qualifier
if start_offset is None:
try:
start_offset = int(self.qualifiers["codon_start"][0]) - 1
except KeyError:
start_offset = 0
if start_offset not in [0, 1, 2]:
raise ValueError(
"The start_offset must be 0, 1, or 2. "
f"The supplied value is {start_offset}. "
"Check the value of either the codon_start qualifier "
"or the start_offset argument"
)
feat_seq = self.extract(parent_sequence)[start_offset:]
codon_table = self.qualifiers.get("transl_table", [table])[0]
if cds is None:
cds = self.type == "CDS"
return feat_seq.translate(
table=codon_table,
stop_symbol=stop_symbol,
to_stop=to_stop,
cds=cds,
gap=gap,
)
def __bool__(self):
"""Boolean value of an instance of this class (True).
This behaviour is for backwards compatibility, since until the
__len__ method was added, a SeqFeature always evaluated as True.
Note that in comparison, Seq objects, strings, lists, etc, will all
evaluate to False if they have length zero.
WARNING: The SeqFeature may in future evaluate to False when its
length is zero (in order to better match normal python behaviour)!
"""
return True
def __len__(self):
"""Return the length of the region where the feature is located.
>>> from Bio.Seq import Seq
>>> from Bio.Alphabet import generic_protein
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> seq = Seq("MKQHKAMIVALIVICITAVVAAL", generic_protein)
>>> f = SeqFeature(FeatureLocation(8, 15), type="domain")
>>> len(f)
7
>>> f.extract(seq)
Seq('VALIVIC', ProteinAlphabet())
>>> len(f.extract(seq))
7
This is a proxy for taking the length of the feature's location:
>>> len(f.location)
7
For simple features this is the same as the region spanned (end
position minus start position using Pythonic counting). However, for
a compound location (e.g. a CDS as the join of several exons) the
gaps are not counted (e.g. introns). This ensures that len(f) matches
len(f.extract(parent_seq)), and also makes sure things work properly
with features wrapping the origin etc.
"""
return len(self.location)
def __iter__(self):
"""Iterate over the parent positions within the feature.
The iteration order is strand aware, and can be thought of as moving
along the feature using the parent sequence coordinates:
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> f = SeqFeature(FeatureLocation(5, 10), type="domain", strand=-1)
>>> len(f)
5
>>> for i in f: print(i)
9
8
7
6
5
>>> list(f)
[9, 8, 7, 6, 5]
This is a proxy for iterating over the location,
>>> list(f.location)
[9, 8, 7, 6, 5]
"""
return iter(self.location)
def __contains__(self, value):
"""Check if an integer position is within the feature.
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> f = SeqFeature(FeatureLocation(5, 10), type="domain", strand=-1)
>>> len(f)
5
>>> [i for i in range(15) if i in f]
[5, 6, 7, 8, 9]
For example, to see which features include a SNP position, you could
use this:
>>> from Bio import SeqIO
>>> record = SeqIO.read("GenBank/NC_000932.gb", "gb")
>>> for f in record.features:
... if 1750 in f:
... print("%s %s" % (f.type, f.location))
source [0:154478](+)
gene [1716:4347](-)
tRNA join{[4310:4347](-), [1716:1751](-)}
Note that for a feature defined as a join of several subfeatures (e.g.
the union of several exons) the gaps are not checked (e.g. introns).
In this example, the tRNA location is defined in the GenBank file as
complement(join(1717..1751,4311..4347)), so that position 1760 falls
in the gap:
>>> for f in record.features:
... if 1760 in f:
... print("%s %s" % (f.type, f.location))
source [0:154478](+)
gene [1716:4347](-)
Note that additional care may be required with fuzzy locations, for
example just before a BeforePosition:
>>> from Bio.SeqFeature import SeqFeature, FeatureLocation
>>> from Bio.SeqFeature import BeforePosition
>>> f = SeqFeature(FeatureLocation(BeforePosition(3), 8), type="domain")
>>> len(f)
5
>>> [i for i in range(10) if i in f]
[3, 4, 5, 6, 7]
Note that is is a proxy for testing membership on the location.
>>> [i for i in range(10) if i in f.location]
[3, 4, 5, 6, 7]
"""
return value in self.location
# --- References
# TODO -- Will this hold PubMed and Medline information decently?
class Reference:
"""Represent a Generic Reference object.
Attributes:
- location - A list of Location objects specifying regions of
the sequence that the references correspond to. If no locations are
specified, the entire sequence is assumed.
- authors - A big old string, or a list split by author, of authors
for the reference.
- title - The title of the reference.
- journal - Journal the reference was published in.
- medline_id - A medline reference for the article.
- pubmed_id - A pubmed reference for the article.
- comment - A place to stick any comments about the reference.
"""
def __init__(self):
"""Initialize the class."""
self.location = []
self.authors = ""
self.consrtm = ""
self.title = ""
self.journal = ""
self.medline_id = ""
self.pubmed_id = ""
self.comment = ""
def __str__(self):
"""Return the full Reference object as a python string."""
out = ""
for single_location in self.location:
out += "location: %s\n" % single_location
out += "authors: %s\n" % self.authors
if self.consrtm:
out += "consrtm: %s\n" % self.consrtm
out += "title: %s\n" % self.title
out += "journal: %s\n" % self.journal
out += "medline id: %s\n" % self.medline_id
out += "pubmed id: %s\n" % self.pubmed_id
out += "comment: %s\n" % self.comment
return out
def __repr__(self):
"""Represent the Reference object as a string for debugging."""
# TODO - Update this is __init__ later accpets values
return "%s(title=%s, ...)" % (self.__class__.__name__, repr(self.title))
def __eq__(self, other):
"""Check if two Reference objects should be considered equal.
Note prior to Biopython 1.70 the location was not compared, as
until then __eq__ for the FeatureLocation class was not defined.
"""
return (
self.authors == other.authors
and self.consrtm == other.consrtm
and self.title == other.title
and self.journal == other.journal
and self.medline_id == other.medline_id
and self.pubmed_id == other.pubmed_id
and self.comment == other.comment
and self.location == other.location
)
# --- Handling feature locations
class FeatureLocation:
"""Specify the location of a feature along a sequence.
The FeatureLocation is used for simple continuous features, which can
be described as running from a start position to and end position
(optionally with a strand and reference information). More complex
locations made up from several non-continuous parts (e.g. a coding
sequence made up of several exons) are described using a SeqFeature
with a CompoundLocation.
Note that the start and end location numbering follow Python's scheme,
thus a GenBank entry of 123..150 (one based counting) becomes a location
of [122:150] (zero based counting).
>>> from Bio.SeqFeature import FeatureLocation
>>> f = FeatureLocation(122, 150)
>>> print(f)
[122:150]
>>> print(f.start)
122
>>> print(f.end)
150
>>> print(f.strand)
None
Note the strand defaults to None. If you are working with nucleotide
sequences you'd want to be explicit if it is the forward strand:
>>> from Bio.SeqFeature import FeatureLocation
>>> f = FeatureLocation(122, 150, strand=+1)
>>> print(f)
[122:150](+)
>>> print(f.strand)
1
Note that for a parent sequence of length n, the FeatureLocation
start and end must satisfy the inequality 0 <= start <= end <= n.
This means even for features on the reverse strand of a nucleotide
sequence, we expect the 'start' coordinate to be less than the
'end'.
>>> from Bio.SeqFeature import FeatureLocation
>>> r = FeatureLocation(122, 150, strand=-1)
>>> print(r)
[122:150](-)
>>> print(r.start)
122
>>> print(r.end)
150
>>> print(r.strand)
-1
i.e. Rather than thinking of the 'start' and 'end' biologically in a
strand aware manner, think of them as the 'left most' or 'minimum'
boundary, and the 'right most' or 'maximum' boundary of the region
being described. This is particularly important with compound
locations describing non-continuous regions.
In the example above we have used standard exact positions, but there
are also specialised position objects used to represent fuzzy positions
as well, for example a GenBank location like complement(<123..150)
would use a BeforePosition object for the start.
"""
def __init__(self, start, end, strand=None, ref=None, ref_db=None):
"""Initialize the class.
start and end arguments specify the values where the feature begins
and ends. These can either by any of the ``*Position`` objects that
inherit from AbstractPosition, or can just be integers specifying the
position. In the case of integers, the values are assumed to be
exact and are converted in ExactPosition arguments. This is meant
to make it easy to deal with non-fuzzy ends.
i.e. Short form:
>>> from Bio.SeqFeature import FeatureLocation
>>> loc = FeatureLocation(5, 10, strand=-1)
>>> print(loc)
[5:10](-)
Explicit form:
>>> from Bio.SeqFeature import FeatureLocation, ExactPosition
>>> loc = FeatureLocation(ExactPosition(5), ExactPosition(10), strand=-1)
>>> print(loc)
[5:10](-)
Other fuzzy positions are used similarly,
>>> from Bio.SeqFeature import FeatureLocation
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
>>> loc2 = FeatureLocation(BeforePosition(5), AfterPosition(10), strand=-1)
>>> print(loc2)
[<5:>10](-)
For nucleotide features you will also want to specify the strand,
use 1 for the forward (plus) strand, -1 for the reverse (negative)
strand, 0 for stranded but strand unknown (? in GFF3), or None for
when the strand does not apply (dot in GFF3), e.g. features on
proteins.
>>> loc = FeatureLocation(5, 10, strand=+1)
>>> print(loc)
[5:10](+)
>>> print(loc.strand)
1
Normally feature locations are given relative to the parent
sequence you are working with, but an explicit accession can
be given with the optional ref and db_ref strings:
>>> loc = FeatureLocation(105172, 108462, ref="AL391218.9", strand=1)
>>> print(loc)
AL391218.9[105172:108462](+)
>>> print(loc.ref)
AL391218.9
"""
# TODO - Check 0 <= start <= end (<= length of reference)
if isinstance(start, AbstractPosition):
self._start = start
elif isinstance(start, int):
self._start = ExactPosition(start)
else:
raise TypeError("start=%r %s" % (start, type(start)))
if isinstance(end, AbstractPosition):
self._end = end
elif isinstance(end, int):
self._end = ExactPosition(end)
else:
raise TypeError("end=%r %s" % (end, type(end)))
if (
isinstance(self.start.position, int)
and isinstance(self.end.position, int)
and self.start > self.end
):
raise ValueError(
f"End location ({self.end}) must be greater than "
f"or equal to start location ({self.start})"
)
self.strand = strand
self.ref = ref
self.ref_db = ref_db
def _get_strand(self):
"""Get function for the strand property (PRIVATE)."""
return self._strand
def _set_strand(self, value):
"""Set function for the strand property (PRIVATE)."""
if value not in [+1, -1, 0, None]:
raise ValueError("Strand should be +1, -1, 0 or None, not %r" % value)
self._strand = value
strand = property(
fget=_get_strand,
fset=_set_strand,
doc="Strand of the location (+1, -1, 0 or None).",
)
def __str__(self):
"""Return a representation of the FeatureLocation object (with python counting).
For the simple case this uses the python splicing syntax, [122:150]
(zero based counting) which GenBank would call 123..150 (one based
counting).
"""
answer = "[%s:%s]" % (self._start, self._end)
if self.ref and self.ref_db:
answer = "%s:%s%s" % (self.ref_db, self.ref, answer)
elif self.ref:
answer = self.ref + answer
# Is ref_db without ref meaningful?
if self.strand is None:
return answer
elif self.strand == +1:
return answer + "(+)"
elif self.strand == -1:
return answer + "(-)"
else:
# strand = 0, stranded but strand unknown, ? in GFF3
return answer + "(?)"
def __repr__(self):
"""Represent the FeatureLocation object as a string for debugging."""
optional = ""
if self.strand is not None:
optional += ", strand=%r" % self.strand
if self.ref is not None:
optional += ", ref=%r" % self.ref
if self.ref_db is not None:
optional += ", ref_db=%r" % self.ref_db
return "%s(%r, %r%s)" % (
self.__class__.__name__,
self.start,
self.end,
optional,
)
def __add__(self, other):
"""Combine location with another FeatureLocation object, or shift it.
You can add two feature locations to make a join CompoundLocation:
>>> from Bio.SeqFeature import FeatureLocation
>>> f1 = FeatureLocation(5, 10)
>>> f2 = FeatureLocation(20, 30)
>>> combined = f1 + f2
>>> print(combined)
join{[5:10], [20:30]}
This is thus equivalent to:
>>> from Bio.SeqFeature import CompoundLocation
>>> join = CompoundLocation([f1, f2])
>>> print(join)
join{[5:10], [20:30]}
You can also use sum(...) in this way:
>>> join = sum([f1, f2])
>>> print(join)
join{[5:10], [20:30]}
Furthermore, you can combine a FeatureLocation with a CompoundLocation
in this way.
Separately, adding an integer will give a new FeatureLocation with
its start and end offset by that amount. For example:
>>> print(f1)
[5:10]
>>> print(f1 + 100)
[105:110]
>>> print(200 + f1)
[205:210]
This can be useful when editing annotation.
"""
if isinstance(other, FeatureLocation):
return CompoundLocation([self, other])
elif isinstance(other, int):
return self._shift(other)
else:
# This will allow CompoundLocation's __radd__ to be called:
return NotImplemented
def __radd__(self, other):
"""Add a feature locationanother FeatureLocation object to the left."""
if isinstance(other, int):
return self._shift(other)
else:
return NotImplemented
def __nonzero__(self):
"""Return True regardless of the length of the feature.
This behaviour is for backwards compatibility, since until the
__len__ method was added, a FeatureLocation always evaluated as True.
Note that in comparison, Seq objects, strings, lists, etc, will all
evaluate to False if they have length zero.
WARNING: The FeatureLocation may in future evaluate to False when its
length is zero (in order to better match normal python behaviour)!
"""
return True
def __len__(self):
"""Return the length of the region described by the FeatureLocation object.
Note that extra care may be needed for fuzzy locations, e.g.
>>> from Bio.SeqFeature import FeatureLocation
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
>>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10))
>>> len(loc)
5
"""
return int(self._end) - int(self._start)
def __contains__(self, value):
"""Check if an integer position is within the FeatureLocation object.
Note that extra care may be needed for fuzzy locations, e.g.
>>> from Bio.SeqFeature import FeatureLocation
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
>>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10))
>>> len(loc)
5
>>> [i for i in range(15) if i in loc]
[5, 6, 7, 8, 9]
"""
if not isinstance(value, int):
raise ValueError(
"Currently we only support checking for integer "
"positions being within a FeatureLocation."
)
if value < self._start or value >= self._end:
return False
else:
return True
def __iter__(self):
"""Iterate over the parent positions within the FeatureLocation object.
>>> from Bio.SeqFeature import FeatureLocation
>>> from Bio.SeqFeature import BeforePosition, AfterPosition
>>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10))
>>> len(loc)
5
>>> for i in loc: print(i)
5
6
7
8
9
>>> list(loc)
[5, 6, 7, 8, 9]
>>> [i for i in range(15) if i in loc]
[5, 6, 7, 8, 9]
Note this is strand aware:
>>> loc = FeatureLocation(BeforePosition(5), AfterPosition(10), strand = -1)
>>> list(loc)
[9, 8, 7, 6, 5]
"""
if self.strand == -1:
yield from range(self._end - 1, self._start - 1, -1)
else:
yield from range(self._start, self._end)
def __eq__(self, other):
"""Implement equality by comparing all the location attributes."""
if not isinstance(other, FeatureLocation):