/
_tabular_msa.py
2506 lines (2097 loc) · 79.5 KB
/
_tabular_msa.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 (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# ----------------------------------------------------------------------------
import collections
import copy
import numpy as np
import pandas as pd
import scipy.stats
from skbio._base import SkbioObject
from skbio.metadata._mixin import MetadataMixin, PositionalMetadataMixin
from skbio.sequence import Sequence
from skbio.sequence._grammared_sequence import GrammaredSequence
from skbio.util._decorator import experimental, classonlymethod, overrides
from skbio.util._misc import resolve_key
from skbio.alignment._indexing import TabularMSAILoc, TabularMSALoc
from skbio.alignment._repr import _TabularMSAReprBuilder
_Shape = collections.namedtuple("Shape", ["sequence", "position"])
class TabularMSA(MetadataMixin, PositionalMetadataMixin, SkbioObject):
"""Store a multiple sequence alignment in tabular (row/column) form.
Parameters
----------
sequences : iterable of GrammaredSequence, TabularMSA
Aligned sequences in the MSA. Sequences must all be the same type and
length. For example, `sequences` could be an iterable of ``DNA``,
``RNA``, or ``Protein`` sequences. If `sequences` is a ``TabularMSA``,
its `metadata`, `positional_metadata`, and `index` will be used unless
overridden by parameters `metadata`, `positional_metadata`, and
`minter`/`index`, respectively.
metadata : dict, optional
Arbitrary metadata which applies to the entire MSA. A shallow copy of
the ``dict`` will be made.
positional_metadata : pd.DataFrame consumable, optional
Arbitrary metadata which applies to each position in the MSA. Must be
able to be passed directly to ``pd.DataFrame`` constructor. Each column
of metadata must be the same length as the number of positions in the
MSA. A shallow copy of the positional metadata will be made.
minter : callable or metadata key, optional
If provided, defines an index label for each sequence in `sequences`.
Can either be a callable accepting a single argument (each sequence) or
a key into each sequence's ``metadata`` attribute. Note that `minter`
cannot be combined with `index`.
index : pd.Index consumable, optional
Index containing labels for `sequences`. Must be the same length as
`sequences`. Must be able to be passed directly to ``pd.Index``
constructor. Note that `index` cannot be combined with `minter` and the
contents of `index` must be hashable.
Raises
------
ValueError
If `minter` and `index` are both provided.
ValueError
If `index` is not the same length as `sequences`.
TypeError
If `sequences` contains an object that isn't a ``GrammaredSequence``.
TypeError
If `sequences` does not contain exactly the same type of
``GrammaredSequence`` objects.
ValueError
If `sequences` does not contain ``GrammaredSequence`` objects of the
same length.
See Also
--------
skbio.sequence.DNA
skbio.sequence.RNA
skbio.sequence.Protein
pandas.DataFrame
pandas.Index
reassign_index
Notes
-----
If neither `minter` nor `index` are provided, default index labels will be
used: ``pd.RangeIndex(start=0, stop=len(sequences), step=1)``.
Examples
--------
Create a ``TabularMSA`` object with three DNA sequences and four positions:
>>> from skbio import DNA, TabularMSA
>>> seqs = [
... DNA('ACGT'),
... DNA('AG-T'),
... DNA('-C-T')
... ]
>>> msa = TabularMSA(seqs)
>>> msa
TabularMSA[DNA]
---------------------
Stats:
sequence count: 3
position count: 4
---------------------
ACGT
AG-T
-C-T
Since `minter` or `index` wasn't provided, the MSA has default index
labels:
>>> msa.index
RangeIndex(start=0, stop=3, step=1)
Create an MSA with metadata, positional metadata, and non-default index
labels:
>>> msa = TabularMSA(seqs, index=['seq1', 'seq2', 'seq3'],
... metadata={'id': 'msa-id'},
... positional_metadata={'prob': [3, 4, 2, 2]})
>>> msa
TabularMSA[DNA]
--------------------------
Metadata:
'id': 'msa-id'
Positional metadata:
'prob': <dtype: int64>
Stats:
sequence count: 3
position count: 4
--------------------------
ACGT
AG-T
-C-T
>>> msa.index
Index(['seq1', 'seq2', 'seq3'], dtype='object')
"""
default_write_format = "fasta"
__hash__ = None
@property
@experimental(as_of="0.4.1")
def dtype(self):
"""Data type of the stored sequences.
Notes
-----
This property is not writeable.
Examples
--------
>>> from skbio import DNA, TabularMSA
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')])
>>> msa.dtype
<class 'skbio.sequence._dna.DNA'>
>>> msa.dtype is DNA
True
"""
return type(self._get_sequence_iloc_(0)) if len(self) > 0 else None
@property
@experimental(as_of="0.4.1")
def shape(self):
"""Number of sequences (rows) and positions (columns).
Notes
-----
This property is not writeable.
Examples
--------
>>> from skbio import DNA, TabularMSA
Create a ``TabularMSA`` object with 2 sequences and 3 positions:
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')])
>>> msa.shape
Shape(sequence=2, position=3)
>>> msa.shape == (2, 3)
True
Dimensions can be accessed by index or by name:
>>> msa.shape[0]
2
>>> msa.shape.sequence
2
>>> msa.shape[1]
3
>>> msa.shape.position
3
"""
sequence_count = len(self)
if sequence_count > 0:
position_count = len(self._get_sequence_iloc_(0))
else:
position_count = 0
return _Shape(sequence=sequence_count, position=position_count)
@property
@experimental(as_of="0.4.1")
def index(self):
"""Index containing labels along the sequence axis.
Returns
-------
pd.Index
Index containing sequence labels.
See Also
--------
reassign_index
Notes
-----
This property can be set and deleted. Deleting the index will reset the
index to the ``TabularMSA`` constructor's default.
Examples
--------
Create a ``TabularMSA`` object with sequences labeled by sequence
identifier:
>>> from skbio import DNA, TabularMSA
>>> seqs = [DNA('ACG', metadata={'id': 'a'}),
... DNA('AC-', metadata={'id': 'b'}),
... DNA('AC-', metadata={'id': 'c'})]
>>> msa = TabularMSA(seqs, minter='id')
Retrieve index:
>>> msa.index
Index(['a', 'b', 'c'], dtype='object')
Set index:
>>> msa.index = ['seq1', 'seq2', 'seq3']
>>> msa.index
Index(['seq1', 'seq2', 'seq3'], dtype='object')
Deleting the index resets it to the ``TabularMSA`` constructor's
default:
>>> del msa.index
>>> msa.index
RangeIndex(start=0, stop=3, step=1)
"""
return self._seqs.index
@index.setter
def index(self, index):
# Cast to Index to identify tuples as a MultiIndex to match
# pandas constructor. Just setting would make an index of tuples.
if not isinstance(index, pd.Index):
index = pd.Index(index)
self._seqs.index = index
@index.deleter
def index(self):
# Create a memory-efficient integer index as the default MSA index.
self._seqs.index = pd.RangeIndex(start=0, stop=len(self), step=1)
@property
@experimental(as_of="0.4.1")
def loc(self):
"""Slice the MSA on first axis by index label, second axis by position.
This will return an object with the following interface:
.. code-block:: python
msa.loc[seq_idx]
msa.loc[seq_idx, pos_idx]
msa.loc(axis='sequence')[seq_idx]
msa.loc(axis='position')[pos_idx]
Parameters
----------
seq_idx : label, slice, 1D array_like (bool or label)
Slice the first axis of the MSA. When this value is a scalar, a
sequence of ``msa.dtype`` will be returned. This may be further
sliced by `pos_idx`.
pos_idx : (same as seq_idx), optional
Slice the second axis of the MSA. When this value is a scalar, a
sequence of type :class:`skbio.sequence.Sequence` will be returned.
This represents a column of the MSA and may have been additionally
sliced by `seq_idx`.
axis : {'sequence', 'position', 0, 1, None}, optional
Limit the axis to slice on. When set, a tuple as the argument will
no longer be split into `seq_idx` and `pos_idx`.
Returns
-------
TabularMSA, GrammaredSequence, Sequence
A ``TabularMSA`` is returned when `seq_idx` and `pos_idx` are
non-scalars. A ``GrammaredSequence`` of type ``msa.dtype`` is
returned when `seq_idx` is a scalar (this object will match the
dtype of the MSA). A ``Sequence`` is returned when `seq_idx` is
non-scalar and `pos_idx` is scalar.
See Also
--------
iloc
__getitem__
Notes
-----
If the slice operation results in a ``TabularMSA`` without any
sequences, the MSA's ``positional_metadata`` will be unset.
When the MSA's index is a ``pd.MultiIndex`` a tuple may be given to
`seq_idx` to indicate the slicing operations to perform on each
component index.
Examples
--------
First we need to set up an MSA to slice:
>>> from skbio import TabularMSA, DNA
>>> msa = TabularMSA([DNA("ACGT"), DNA("A-GT"), DNA("AC-T"),
... DNA("ACGA")], index=['a', 'b', 'c', 'd'])
>>> msa
TabularMSA[DNA]
---------------------
Stats:
sequence count: 4
position count: 4
---------------------
ACGT
A-GT
AC-T
ACGA
>>> msa.index
Index(['a', 'b', 'c', 'd'], dtype='object')
When we slice by a scalar we get the original sequence back out of the
MSA:
>>> msa.loc['b']
DNA
--------------------------
Stats:
length: 4
has gaps: True
has degenerates: False
has definites: True
GC-content: 33.33%
--------------------------
0 A-GT
Similarly when we slice the second axis by a scalar we get a column of
the MSA:
>>> msa.loc[..., 1]
Sequence
-------------
Stats:
length: 4
-------------
0 C-CC
Note: we return an ``skbio.Sequence`` object because the column of an
alignment has no biological meaning and many operations defined for the
MSA's sequence `dtype` would be meaningless.
When we slice both axes by a scalar, operations are applied left to
right:
>>> msa.loc['a', 0]
DNA
--------------------------
Stats:
length: 1
has gaps: False
has degenerates: False
has definites: True
GC-content: 0.00%
--------------------------
0 A
In other words, it exactly matches slicing the resulting sequence
object directly:
>>> msa.loc['a'][0]
DNA
--------------------------
Stats:
length: 1
has gaps: False
has degenerates: False
has definites: True
GC-content: 0.00%
--------------------------
0 A
When our slice is non-scalar we get back an MSA of the same `dtype`:
>>> msa.loc[['a', 'c']]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 4
---------------------
ACGT
AC-T
We can similarly slice out a column of that:
>>> msa.loc[['a', 'c'], 2]
Sequence
-------------
Stats:
length: 2
-------------
0 G-
Slice syntax works as well:
>>> msa.loc[:'c']
TabularMSA[DNA]
---------------------
Stats:
sequence count: 3
position count: 4
---------------------
ACGT
A-GT
AC-T
Notice how the end label is included in the results. This is different
from how positional slices behave:
>>> msa.loc[[True, False, False, True], 2:3]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 1
---------------------
G
G
Here we sliced the first axis by a boolean vector, but then restricted
the columns to a single column. Because the second axis was given a
nonscalar we still recieve an MSA even though only one column is
present.
Duplicate labels can be an unfortunate reality in the real world,
however `loc` is capable of handling this:
>>> msa.index = ['a', 'a', 'b', 'c']
Notice how the label 'a' happens twice. If we were to access 'a' we get
back an MSA with both sequences:
>>> msa.loc['a']
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 4
---------------------
ACGT
A-GT
Remember that `iloc` can always be used to differentiate sequences with
duplicate labels.
More advanced slicing patterns are possible with different index types.
Let's use a `pd.MultiIndex`:
>>> msa.index = [('a', 0), ('a', 1), ('b', 0), ('b', 1)]
Here we will explicitly set the axis that we are slicing by to make
things easier to read:
>>> msa.loc(axis='sequence')['a', 0]
DNA
--------------------------
Stats:
length: 4
has gaps: False
has degenerates: False
has definites: True
GC-content: 50.00%
--------------------------
0 ACGT
This selected the first sequence because the complete label was
provided. In other words `('a', 0)` was treated as a scalar for this
index.
We can also slice along the component indices of the multi-index:
>>> msa.loc(axis='sequence')[:, 1]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 4
---------------------
A-GT
ACGA
If we were to do that again without the `axis` argument, it would look
like this:
>>> msa.loc[(slice(None), 1), ...]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 4
---------------------
A-GT
ACGA
Notice how we needed to specify the second axis. If we had left that
out we would have simply gotten the 2nd column back instead. We also
lost the syntactic sugar for slice objects. These are a few of the
reasons specifying the `axis` preemptively can be useful.
"""
return self._loc
@property
@experimental(as_of="0.4.1")
def iloc(self):
"""Slice the MSA on either axis by index position.
This will return an object with the following interface:
.. code-block:: python
msa.iloc[seq_idx]
msa.iloc[seq_idx, pos_idx]
msa.iloc(axis='sequence')[seq_idx]
msa.iloc(axis='position')[pos_idx]
Parameters
----------
seq_idx : int, slice, iterable (int and slice), 1D array_like (bool)
Slice the first axis of the MSA. When this value is a scalar, a
sequence of ``msa.dtype`` will be returned. This may be further
sliced by `pos_idx`.
pos_idx : (same as seq_idx), optional
Slice the second axis of the MSA. When this value is a scalar, a
sequence of type :class:`skbio.sequence.Sequence` will be returned.
This represents a column of the MSA and may have been additionally
sliced by `seq_idx`.
axis : {'sequence', 'position', 0, 1, None}, optional
Limit the axis to slice on. When set, a tuple as the argument will
no longer be split into `seq_idx` and `pos_idx`.
Returns
-------
TabularMSA, GrammaredSequence, Sequence
A ``TabularMSA`` is returned when `seq_idx` and `pos_idx` are
non-scalars. A ``GrammaredSequence`` of type ``msa.dtype`` is
returned when `seq_idx` is a scalar (this object will match the
dtype of the MSA). A ``Sequence`` is returned when `seq_idx` is
non-scalar and `pos_idx` is scalar.
See Also
--------
__getitem__
loc
Notes
-----
If the slice operation results in a ``TabularMSA`` without any
sequences, the MSA's ``positional_metadata`` will be unset.
Examples
--------
First we need to set up an MSA to slice:
>>> from skbio import TabularMSA, DNA
>>> msa = TabularMSA([DNA("ACGT"), DNA("A-GT"), DNA("AC-T"),
... DNA("ACGA")])
>>> msa
TabularMSA[DNA]
---------------------
Stats:
sequence count: 4
position count: 4
---------------------
ACGT
A-GT
AC-T
ACGA
When we slice by a scalar we get the original sequence back out of the
MSA:
>>> msa.iloc[1]
DNA
--------------------------
Stats:
length: 4
has gaps: True
has degenerates: False
has definites: True
GC-content: 33.33%
--------------------------
0 A-GT
Similarly when we slice the second axis by a scalar we get a column of
the MSA:
>>> msa.iloc[..., 1]
Sequence
-------------
Stats:
length: 4
-------------
0 C-CC
Note: we return an ``skbio.Sequence`` object because the column of an
alignment has no biological meaning and many operations defined for the
MSA's sequence `dtype` would be meaningless.
When we slice both axes by a scalar, operations are applied left to
right:
>>> msa.iloc[0, 0]
DNA
--------------------------
Stats:
length: 1
has gaps: False
has degenerates: False
has definites: True
GC-content: 0.00%
--------------------------
0 A
In other words, it exactly matches slicing the resulting sequence
object directly:
>>> msa.iloc[0][0]
DNA
--------------------------
Stats:
length: 1
has gaps: False
has degenerates: False
has definites: True
GC-content: 0.00%
--------------------------
0 A
When our slice is non-scalar we get back an MSA of the same `dtype`:
>>> msa.iloc[[0, 2]]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 4
---------------------
ACGT
AC-T
We can similarly slice out a column of that:
>>> msa.iloc[[0, 2], 2]
Sequence
-------------
Stats:
length: 2
-------------
0 G-
Slice syntax works as well:
>>> msa.iloc[:3]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 3
position count: 4
---------------------
ACGT
A-GT
AC-T
We can also use boolean vectors:
>>> msa.iloc[[True, False, False, True], 2:3]
TabularMSA[DNA]
---------------------
Stats:
sequence count: 2
position count: 1
---------------------
G
G
Here we sliced the first axis by a boolean vector, but then restricted
the columns to a single column. Because the second axis was given a
nonscalar we still recieve an MSA even though only one column is
present.
"""
return self._iloc
@classonlymethod
@experimental(as_of="0.4.1")
def from_dict(cls, dictionary):
"""Create a ``TabularMSA`` from a ``dict``.
Parameters
----------
dictionary : dict
Dictionary mapping keys to ``GrammaredSequence`` sequence objects.
The ``TabularMSA`` object will have its index labels set
to the keys in the dictionary.
Returns
-------
TabularMSA
``TabularMSA`` object constructed from the keys and sequences in
`dictionary`.
See Also
--------
to_dict
sort
Notes
-----
The order of sequences and index labels in the resulting ``TabularMSA``
object is arbitrary. Use ``TabularMSA.sort`` to set a different order.
Examples
--------
>>> from skbio import DNA, TabularMSA
>>> seqs = {'a': DNA('ACGT'), 'b': DNA('A--T')}
>>> msa = TabularMSA.from_dict(seqs)
>>> msa.shape
Shape(sequence=2, position=4)
>>> 'a' in msa
True
>>> 'b' in msa
True
"""
# Python 3 guarantees same order of iteration as long as no
# modifications are made to the dictionary between calls:
# https://docs.python.org/3/library/stdtypes.html#
# dictionary-view-objects
return cls(dictionary.values(), index=dictionary.keys())
@experimental(as_of="0.4.1")
def __init__(
self,
sequences,
metadata=None,
positional_metadata=None,
minter=None,
index=None,
):
if isinstance(sequences, TabularMSA):
if metadata is None and sequences.has_metadata():
metadata = sequences.metadata
if positional_metadata is None and sequences.has_positional_metadata():
positional_metadata = sequences.positional_metadata
if minter is None and index is None:
index = sequences.index
# Give a better error message than the one raised by `extend` (it
# references `reset_index`, which isn't a constructor parameter).
if minter is not None and index is not None:
raise ValueError("Cannot use both `minter` and `index` at the same time.")
self._seqs = pd.Series([], dtype=object)
self.extend(
sequences,
minter=minter,
index=index,
reset_index=minter is None and index is None,
)
MetadataMixin._init_(self, metadata=metadata)
PositionalMetadataMixin._init_(self, positional_metadata=positional_metadata)
# Set up our indexers
self._loc = TabularMSALoc(self)
self._iloc = TabularMSAILoc(self)
def _constructor_(
self,
sequences=NotImplemented,
metadata=NotImplemented,
positional_metadata=NotImplemented,
index=NotImplemented,
):
"""Return new copy of the MSA with overridden properties.
NotImplemented is used as a sentinel so that None may be used to
override values.
"""
if metadata is NotImplemented:
if self.has_metadata():
metadata = self.metadata
else:
metadata = None
if positional_metadata is NotImplemented:
if self.has_positional_metadata():
positional_metadata = self.positional_metadata
else:
positional_metadata = None
if index is NotImplemented:
if isinstance(sequences, pd.Series):
index = sequences.index
else:
index = self.index
if sequences is NotImplemented:
sequences = self._seqs
sequences = [copy.copy(s) for s in sequences]
return self.__class__(
sequences,
metadata=metadata,
positional_metadata=positional_metadata,
index=index,
)
@experimental(as_of="0.4.1")
def __repr__(self):
"""Return string summary of this MSA."""
pep8_line_length_limit = 79
length_taken_by_docstring_indent = 8
width = pep8_line_length_limit - length_taken_by_docstring_indent
return _TabularMSAReprBuilder(msa=self, width=width, indent=4).build()
def _repr_stats(self):
return [
("sequence count", str(self.shape.sequence)),
("position count", str(self.shape.position)),
]
@experimental(as_of="0.4.1")
def __bool__(self):
"""Boolean indicating whether the MSA is empty or not.
Returns
-------
bool
``False`` if there are no sequences, OR if there are no positions
(i.e., all sequences are empty). ``True`` otherwise.
Examples
--------
>>> from skbio import DNA, TabularMSA
MSA with sequences and positions:
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')])
>>> bool(msa)
True
No sequences:
>>> msa = TabularMSA([])
>>> bool(msa)
False
No positions:
>>> msa = TabularMSA([DNA(''), DNA('')])
>>> bool(msa)
False
"""
# It is impossible to have 0 sequences and >0 positions.
# TODO: change for #1198
return self.shape.position > 0
@experimental(as_of="0.4.1")
def __contains__(self, label):
"""Determine if an index label is in this MSA.
Parameters
----------
label : hashable
Label to search for in this MSA.
Returns
-------
bool
Indicates whether `label` is in this MSA.
Examples
--------
>>> from skbio import DNA, TabularMSA
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')], index=['l1', 'l2'])
>>> 'l1' in msa
True
>>> 'l2' in msa
True
>>> 'l3' in msa
False
"""
return label in self.index
@experimental(as_of="0.4.1")
def __len__(self):
"""Return number of sequences in the MSA.
Returns
-------
int
Number of sequences in the MSA (i.e., size of the 1st dimension).
Notes
-----
This is equivalent to ``msa.shape[0]``.
Examples
--------
>>> from skbio import DNA, TabularMSA
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')])
>>> len(msa)
2
>>> msa = TabularMSA([])
>>> len(msa)
0
"""
return len(self._seqs)
@experimental(as_of="0.4.1")
def __iter__(self):
"""Iterate over sequences in the MSA.
Yields
------
GrammaredSequence
Each sequence in the order they are stored in the MSA.
Examples
--------
>>> from skbio import DNA, TabularMSA
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')])
>>> for seq in msa:
... str(seq)
'ACG'
'AC-'
"""
return iter(self._seqs)
@experimental(as_of="0.4.1")
def __reversed__(self):
"""Iterate in reverse order over sequences in the MSA.
Yields
------
GrammaredSequence
Each sequence in reverse order from how they are stored in the MSA.
Examples
--------
>>> from skbio import DNA, TabularMSA
>>> msa = TabularMSA([DNA('ACG'), DNA('AC-')])
>>> for seq in reversed(msa):
... str(seq)
'AC-'
'ACG'
"""
return reversed(self._seqs)
@experimental(as_of="0.4.1")
def __str__(self):
"""Return string summary of this MSA."""
return self.__repr__()
@experimental(as_of="0.4.1")
def __eq__(self, other):
"""Determine if this MSA is equal to another.