-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathtreemodel.py
More file actions
6747 lines (5998 loc) · 274 KB
/
Copy pathtreemodel.py
File metadata and controls
6747 lines (5998 loc) · 274 KB
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion thereof in published work,
## please cite it as:
##
## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library
## for phylogenetic computing. Bioinformatics 26: 1569-1571.
##
##############################################################################
"""
This module handles the core definition of tree data structure class,
as well as all the structural classes that make up a tree.
"""
import collections
import math
from dendropy.utility.textprocessing import StringIO
import copy
import sys
from dendropy.utility import GLOBAL_RNG
from dendropy.utility import container
from dendropy.utility import terminal
from dendropy.utility import error
from dendropy.utility import bitprocessing
from dendropy.utility import deprecate
from dendropy.utility import constants
from dendropy.utility import textprocessing
from dendropy.datamodel import basemodel
from dendropy.datamodel import taxonmodel
from dendropy import dataio
##############################################################################
### Bipartition
class Bipartition(object):
"""
A bipartition on a tree.
A bipartition of a tree is a division or sorting of the leaves/tips of a
tree into two mutually-exclusive and collectively-comprehensive subsets,
obtained by bisecting the tree at a particular edge. There is thus a
one-to-one correspondence with an edge of a tree and a bipartition. The
term "split" is often also used to refer to the same concept, though this
is typically applied to unrooted trees.
A bipartition is modeled using a bitmask. This is a a bit array
representing the membership of taxa, with the least-significant bit
corresponding to the first taxon, the next least-signficant bit
corresponding to the second taxon, and so on, till the last taxon
corresponding to the most-significant bit. Taxon membership in one of two
arbitrary groups, '0' or '1', is indicated by its corresponding bit being
unset or set, respectively.
To allow comparisons and correct identification of the same bipartition
across different rotational and orientiational representations of unrooted
trees, we *normalize* the bipartition such that the first taxon is always
assigned to group '0' for bipartition representations of unrooted trees.
The normalization of the bitmask loses information about the actual
descendents of a particular edge. Thus in addition to the
:attr:`Bipartition.bitmask` attribute, each |Bipartition| object
also maintains a :attr:`Bipartition.leafset_bitmask` attribute which is
*unnormalized*. This is a bit array representing the presence or absence of
taxa in the subtree descending from the child node of the edge of which
this bipartition is associated. The least-significant bit corresponds to
the first taxon, the next least-signficant bit corresponds to the second
taxon, and so on, with the last taxon corresponding to the most-significant
bit. For rooted trees, the value of :attr:`Bipartition.bitmask` and
:attr:`Bipartition.leafset_bitmask` are identical. For unrooted trees, they
may or may not be equal.
In general, we use :attr:`Bipartition.bitmask` data to establish the *identity*
of a split or bipartition across *different* trees: for example, when
computing the Robinson-Foulds distances between trees, or in assessing the
support for different bipartitions given an MCMC or bootstrap sample of trees.
Here the normalization of the bitmask in unrooted trees allows for the
(arbitrarily-labeled) group '0' to be consistent across different
representations, rotations, and orientations of trees.
On the other hand, we use :attr:`Bipartition.leafset_bitmask` data to work
with various ancestor-descendent relationships *within* the *same* tree:
for example, to quickly assess if a taxon descends from a particular
node in a given tree, or if a particular node is a common ancestor of
two taxa in a given tree.
The |Bipartition| object might be used in keys in dictionaries and
look-up tables implemented as sets to allow for, e.g., calculation of
support in terms of the number times a particular bipartition is observed.
The :attr:`Bipartition.bitmask` is used as hash value for this purpose. As
such, it is crucial that this value does not change once a particular
|Bipartition| object is stored in a dictionary or set. To this end,
we impose the constraint that |Bipartition| objects are immutable
unless the ``is_mutable`` attribute is explicitly set to |True| as a sort
of waiver signed by the client code. Client code does this at its risk,
with the warning that anything up to and including the implosion of the
universe may occur if the |Bipartition| object is a member of an set
of dictionary at the time (or, at the very least, the modified
|Bipartition| object may not be accessible from dictionaries
and sets in which it is stored, or may occlude other
|Bipartition| objects in the container).
Note
----
There are two possible ways of mapping taxa to bits in a bitarray or bitstring.
In the "Least-Signficiant-Bit" (LSB) scheme, the first taxon corresponds to the
least-significant, or left-most bit. So, given four taxa, indexed from 1 to 4,
taxon 1 would map to 0b0001, taxon 2 would map to 0b0010, taxon 3 would map
to 0b0100, and taxon 4 would map to 0b1000.
In the "Most-Significant-Bit" (MSB) scheme, on the other hand, the first taxon
corresponds to the most-significant, or right-most bit. So, given four
taxa, indexed from 1 to 4, taxon 1 would map to 0b1000, taxon 2 would map
to 0b0100, taxon 3 would map to 0b0010, and taxon 4 would map to 0b0001.
We selected the Least Significant Bit (LSB) approach because the MSB scheme
requires the size of the taxon namespace to fixed before the index can be
assigned to any taxa. For example, under the MSB scheme, if there are 4
taxa, the bitmask for taxon 1 is 0b1000 == 8, but if another taxon is
added, then the bitmask for taxon 1 will become 0b10000 == 16. On the other
hand, under the LSB scheme, the bitmask for taxon 1 will be 0b0001 == 1 if
there are 4 taxa, and 0b00001 == 1 if there 5 taxa, and so on. This
stability of taxon indexes even as the taxon namespace grows is a strongly
desirable property, and this the adoption of the LSB scheme.
Constraining the first taxon to be in group 0 (LSB-0) rather than group 1
(LSB-1) is motivated by the fact that, in the former, we can would combine
the bitmasks of child nodes using OR (logical addition) operations when
calculating the bitmask for a parent node, whereas, with the latter, we
would need to use AND operations. The former strikes us as more intuitive.
"""
def normalize_bitmask(bitmask, fill_bitmask, lowest_relevant_bit=1):
if bitmask & lowest_relevant_bit:
return (~bitmask) & fill_bitmask # force least-significant bit to 0
else:
return bitmask & fill_bitmask # keep least-significant bit as 0
normalize_bitmask = staticmethod(normalize_bitmask)
def is_trivial_bitmask(bitmask, fill_bitmask):
"""
Returns True if the bitmask occurs in any tree of the taxa ``mask`` -- if
there is only fewer than two 1's or fewer than two 0's in ``bitmask`` (among
all of the that are 1 in mask).
"""
masked_split = bitmask & fill_bitmask
if bitmask == 0 or bitmask == fill_bitmask:
return True
if ((masked_split - 1) & masked_split) == 0:
return True
cm = (~bitmask) & fill_bitmask
if ((cm - 1) & cm) == 0:
return True
return False
is_trivial_bitmask = staticmethod(is_trivial_bitmask)
def is_trivial_leafset(leafset_bitmask):
return bitprocessing.num_set_bits(leafset_bitmask) == 1
is_trivial_leafset = staticmethod(is_trivial_leafset)
def is_compatible_bitmasks(m1, m2, fill_bitmask):
"""
Returns |True| if ``m1`` is compatible with ``m2``
Parameters
----------
m1 : int
A bitmask representing a split.
m2 : int
A bitmask representing a split.
Returns
-------
bool
|True| if ``m1`` is compatible with ``m2``. |False| otherwise.
"""
if fill_bitmask != 0:
m1 = fill_bitmask & m1
m2 = fill_bitmask & m2
if 0 == (m1 & m2):
return True
c2 = m1 ^ m2
if 0 == (m1 & c2):
return True
c1 = fill_bitmask ^ m1
if 0 == (c1 & m2):
return True
if 0 == (c1 & c2):
return True
return False
is_compatible_bitmasks = staticmethod(is_compatible_bitmasks)
##############################################################################
## Life-cycle
def __init__(self, **kwargs):
"""
Keyword Arguments
-----------------
bitmask : integer
A bit array representing the membership of taxa, with the
least-significant bit corresponding to the first taxon, the next
least-signficant bit correspodning to the second taxon, and so on,
till the last taxon corresponding to the most-significant bit.
Taxon membership in one of two arbitrary groups, '0' or '1', is
indicated by its correspondign bit being unset or set,
respectively.
leafset_bitmask : integer
A bit array representing the presence or absence of taxa in the
subtree descending from the child node of the edge of which this
bipartition is associated. The least-significant bit corresponds to
the first taxon, the next least-signficant bit corresponds to the
second taxon, and so on, with the last taxon corresponding to the
most-significant bit.
tree_leafset_bitmask : integer
The ``leafset_bitmask`` of the root edge of the tree with which this
bipartition is associated. In, general, this will be $0b1111...n$,
where $n$ is the number of taxa, *except* in cases of trees with
incomplete leaf-sets, where the positions corresponding to the
missing taxa will have the bits unset.
is_rooted : bool
Specifies whether or not the tree with which this bipartition is
associated is rooted.
"""
self._split_bitmask = kwargs.get("bitmask", 0)
self._leafset_bitmask = kwargs.get("leafset_bitmask", self._split_bitmask)
self._tree_leafset_bitmask = kwargs.get("tree_leafset_bitmask", None)
self._lowest_relevant_bit = None
self._is_rooted = kwargs.get("is_rooted", None)
# self.edge = kwargs.get("edge", None)
is_mutable = kwargs.get("is_mutable", None)
if kwargs.get("compile_bipartition", True):
self.is_mutable = True
self.compile_split_bitmask(
leafset_bitmask=self._leafset_bitmask,
tree_leafset_bitmask=self._tree_leafset_bitmask)
if is_mutable is None:
self.is_mutable = True
else:
self.is_mutable = is_mutable
elif is_mutable is not None:
self.is_mutable = is_mutable
##############################################################################
## Identity
def __hash__(self):
assert not self.is_mutable, "Bipartition is mutable: hash is unstable"
return self._split_bitmask or 0
def __eq__(self, other):
# return self._split_bitmask == other._split_bitmask
return (self._split_bitmask is not None and self._split_bitmask == other._split_bitmask) or (self._split_bitmask is other._split_bitmask)
##############################################################################
## All properties are publically read-only if not mutable
def _get_split_bitmask(self):
return self._split_bitmask
def _set_split_bitmask(self, value):
assert self.is_mutable, "Bipartition instance is not mutable"
self._split_bitmask = value
split_bitmask = property(_get_split_bitmask, _set_split_bitmask)
def _get_leafset_bitmask(self):
return self._leafset_bitmask
def _set_leafset_bitmask(self, value):
assert self.is_mutable, "Bipartition instance is not mutable"
self._leafset_bitmask = value
leafset_bitmask = property(_get_leafset_bitmask, _set_leafset_bitmask)
def _get_tree_leafset_bitmask(self):
return self._tree_leafset_bitmask
def _set_tree_leafset_bitmask(self, value):
assert self.is_mutable, "Bipartition instance is not mutable"
self.compile_tree_leafset_bitmask(value)
tree_leafset_bitmask = property(_get_tree_leafset_bitmask, _set_tree_leafset_bitmask)
def _get_is_rooted(self):
return self._is_rooted
def _set_is_rooted(self, value):
assert self.is_mutable, "Bipartition instance is not mutable"
self._is_rooted = value
is_rooted = property(_get_is_rooted, _set_is_rooted)
##############################################################################
## Representation
def __str__(self):
return bin(self._split_bitmask)[2:].rjust(bitprocessing.bit_length(self._tree_leafset_bitmask), '0')
def __int__(self):
return self._split_bitmask
def split_as_int(self):
return self._split_bitmask
def leafset_as_int(self):
return self._leafset_bitmask
def split_as_bitstring(self, symbol0="0", symbol1="1", reverse=False):
"""
Composes and returns and representation of the bipartition as a
bitstring.
Parameters
----------
symbol1 : str
The symbol to represent group '0' in the bitmask.
symbol1 : str
The symbol to represent group '1' in the bitmask.
reverse : bool
If |True|, then the first taxon will correspond to the
most-significant bit, instead of the least-significant bit, as is
the default.
Returns
-------
str
The bitstring representing the bipartition.
Example
-------
To represent a bipartition in the same scheme used by, e.g. PAUP* or
Mr. Bayes::
print(bipartition.split_as_bitstring('.', '*', reverse=True))
"""
return self.bitmask_as_bitstring(
mask=self._split_bitmask,
symbol0=symbol0,
symbol1=symbol1,
reverse=reverse)
def leafset_as_bitstring(self, symbol0="0", symbol1="1", reverse=False):
"""
Composes and returns and representation of the bipartition leafset as a
bitstring.
Parameters
----------
symbol1 : str
The symbol to represent group '0' in the bitmask.
symbol1 : str
The symbol to represent group '1' in the bitmask.
reverse : bool
If |True|, then the first taxon will correspond to the
most-significant bit, instead of the least-significant bit, as is
the default.
Returns
-------
str
The bitstring representing the bipartition.
Example
-------
To represent a bipartition in the same scheme used by, e.g. PAUP* or
Mr. Bayes::
print(bipartition.leafset_as_bitstring('.', '*', reverse=True))
"""
return self.bitmask_as_bitstring(
mask=self._leafset_bitmask,
symbol0=symbol0,
symbol1=symbol1,
reverse=reverse)
def bitmask_as_bitstring(self, mask, symbol0=None, symbol1=None, reverse=False):
return bitprocessing.int_as_bitstring(mask,
length=bitprocessing.bit_length(self._tree_leafset_bitmask),
symbol0=symbol0,
symbol1=symbol1,
reverse=reverse)
##############################################################################
## Calculation
def compile_tree_leafset_bitmask(self,
tree_leafset_bitmask,
lowest_relevant_bit=None):
"""
Avoids recalculation of ``lowest_relevant_bit`` if specified.
"""
assert self.is_mutable, "Bipartition instance is not mutable"
self._tree_leafset_bitmask = tree_leafset_bitmask
if lowest_relevant_bit is not None:
self._lowest_relevant_bit = lowest_relevant_bit
elif self._tree_leafset_bitmask:
self._lowest_relevant_bit = bitprocessing.least_significant_set_bit(self._tree_leafset_bitmask)
else:
self._lowest_relevant_bit = None
return self._tree_leafset_bitmask
def compile_leafset_bitmask(self,
leafset_bitmask=None,
tree_leafset_bitmask=None):
assert self.is_mutable, "Bipartition instance is not mutable"
if tree_leafset_bitmask is not None:
self.compile_tree_leafset_bitmask(tree_leafset_bitmask)
if leafset_bitmask is None:
leafset_bitmask = self._leafset_bitmask
if self._tree_leafset_bitmask:
self._leafset_bitmask = leafset_bitmask & self._tree_leafset_bitmask
else:
self._leafset_bitmask = leafset_bitmask
return self._leafset_bitmask
def compile_split_bitmask(self,
leafset_bitmask=None,
tree_leafset_bitmask=None,
is_rooted=None,
is_mutable=True):
"""
Updates the values of the various masks specified and calculates the
normalized bipartition bitmask.
If a rooted bipartition, then this is set to the value of the leafset
bitmask.
If an unrooted bipartition, then the leafset bitmask is normalized such that
the lowest-significant bit (i.e., the group to which the first taxon
belongs) is set to '0'.
Also makes this bipartition immutable (unless ``is_mutable`` is |False|),
which facilitates it being used in dictionaries and sets.
Parameters
----------
leafset_bitmask : integer
A bit array representing the presence or absence of taxa in the
subtree descending from the child node of the edge of which this
bipartition is associated. The least-significant bit corresponds to
the first taxon, the next least-signficant bit corresponds to the
second taxon, and so on, with the last taxon corresponding to the
most-significant bit. If not specified or |None|, the current value
of ``self.leafset_bitmask`` is used.
tree_leafset_bitmask : integer
The ``leafset_bitmask`` of the root edge of the tree with which this
bipartition is associated. In, general, this will be $0b1111...n$,
where $n$ is the number of taxa, *except* in cases of trees with
incomplete leaf-sets, where the positions corresponding to the
missing taxa will have the bits unset. If not specified or |None|,
the current value of ``self.tree_leafset_bitmask`` is used.
is_rooted : bool
Specifies whether or not the tree with which this bipartition is
associated is rooted. If not specified or |None|, the current value
of ``self.is_rooted`` is used.
Returns
-------
integer
The bipartition bitmask.
"""
assert self.is_mutable, "Bipartition instance is not mutable"
if is_rooted is not None:
self._is_rooted = is_rooted
if tree_leafset_bitmask:
self.compile_tree_leafset_bitmask(tree_leafset_bitmask=tree_leafset_bitmask)
if leafset_bitmask:
self.compile_leafset_bitmask(leafset_bitmask=leafset_bitmask)
if self._leafset_bitmask is None:
return
if self._tree_leafset_bitmask is None:
return
if self._is_rooted:
self._split_bitmask = self._leafset_bitmask
else:
self._split_bitmask = Bipartition.normalize_bitmask(
bitmask=self._leafset_bitmask,
fill_bitmask=self._tree_leafset_bitmask,
lowest_relevant_bit=self._lowest_relevant_bit)
if is_mutable is not None:
self.is_mutable = is_mutable
return self._split_bitmask
def compile_bipartition(self, is_mutable=None):
"""
Updates the values of the various masks specified and calculates the
normalized bipartition bitmask.
If a rooted bipartition, then this is set to the value of the leafset
bitmask.
If an unrooted bipartition, then the leafset bitmask is normalized such that
the lowest-significant bit (i.e., the group to which the first taxon
belongs) is set to '0'.
Also makes this bipartition immutable (unless ``is_mutable`` is |False|),
which facilitates it being used in dictionaries and sets.
Note that this requires full population of the following fields:
- self._leafset_bitmask
- self._tree_leafset_bitmask
"""
self.compile_split_bitmask(self,
leafset_bitmask=self._leafset_bitmask,
tree_leafset_bitmask=self._tree_leafset_bitmask,
is_rooted=self._is_rooted,
is_mutable=is_mutable)
##############################################################################
## Operations
def normalize(self, bitmask, convention="lsb0"):
"""
Return ``bitmask`` ensuring that the bit corresponding to the first
taxon is 1.
"""
if convention == "lsb0":
if self._lowest_relevant_bit & bitmask:
return (~bitmask) & self._tree_leafset_bitmask
else:
return bitmask & self._tree_leafset_bitmask
elif convention == "lsb1":
if self._lowest_relevant_bit & bitmask:
return bitmask & self._tree_leafset_bitmask
else:
return (~bitmask) & self._tree_leafset_bitmask
else:
raise ValueError("Unrecognized convention: {}".format(convention))
def is_compatible_with(self, other):
"""
Returns |True| if ``other`` is compatible with self.
Parameters
----------
other : |Bipartition|
The bipartition to check for compatibility.
Returns
-------
bool
|True| if ``other`` is compatible with ``self``; |False| otherwise.
"""
m1 = self._split_bitmask
if isinstance(other, int):
m2 = other
else:
m2 = other._split_bitmask
return Bipartition.is_compatible_bitmasks(m1, m2, self._tree_leafset_bitmask)
def is_incompatible_with(self, other):
"""
Returns |True| if ``other`` conflicts with self.
Parameters
----------
other : |Bipartition|
The bipartition to check for conflicts.
Returns
-------
bool
|True| if ``other`` conflicts with ``self``; |False| otherwise.
"""
return not self.is_compatible_with(other)
def is_nested_within(self, other, is_other_masked_for_tree_leafset=False):
"""
Returns |True| if the current bipartition is contained
within other.
Parameters
----------
other : |Bipartition|
The bipartition to check.
Returns
-------
bool
|True| if the the bipartition is "contained" within ``other``
"""
if self._is_rooted:
m1 = self._leafset_bitmask
m2 = other._leafset_bitmask
else:
m1 = self._split_bitmask
m2 = other._split_bitmask
if not is_other_masked_for_tree_leafset:
m2 = self._tree_leafset_bitmask & m2
return ( (m1 & m2) == m1 )
def is_leafset_nested_within(self, other):
"""
Returns |True| if the leafset of ``self`` is a subset of the leafset of
``other``.
Parameters
----------
other : |Bipartition|
The bipartition to check for compatibility.
Returns
-------
bool
|True| if the leafset of ``self`` is contained in ``other``.
"""
if isinstance(other, int):
m2 = other
else:
m2 = other._leafset_bitmask
m2 = self._tree_leafset_bitmask & m2
return ( (m2 & self._leafset_bitmask) == self._leafset_bitmask )
def is_trivial(self):
"""
Returns
-------
bool
|True| if this bipartition divides a leaf and the rest of the
tree.
"""
return Bipartition.is_trivial_bitmask(self._split_bitmask,
self._tree_leafset_bitmask)
def split_as_newick_string(self,
taxon_namespace,
preserve_spaces=False,
quote_underscores=True):
"""
Represents this bipartition split as a newick string.
Parameters
----------
taxon_namespace : |TaxonNamespace| instance
The operational taxonomic unit concept namespace to reference.
preserve_spaces : boolean, optional
If |False| (default), then spaces in taxon labels will be replaced
by underscores. If |True|, then taxon labels with spaces will be
wrapped in quotes.
quote_underscores : boolean, optional
If |True| (default), then taxon labels with underscores will be
wrapped in quotes. If |False|, then the labels will not be wrapped
in quotes.
Returns
-------
string
NEWICK representation of split specified by ``bitmask``.
"""
return taxon_namespace.bitmask_as_newick_string(
bitmask=self._split_bitmask,
preserve_spaces=preserve_spaces,
quote_underscores=quote_underscores)
def leafset_as_newick_string(self,
taxon_namespace,
preserve_spaces=False,
quote_underscores=True):
"""
Represents this bipartition leafset as a newick string.
Parameters
----------
taxon_namespace : |TaxonNamespace| instance
The operational taxonomic unit concept namespace to reference.
preserve_spaces : boolean, optional
If |False| (default), then spaces in taxon labels will be replaced
by underscores. If |True|, then taxon labels with spaces will be
wrapped in quotes.
quote_underscores : boolean, optional
If |True| (default), then taxon labels with underscores will be
wrapped in quotes. If |False|, then the labels will not be wrapped
in quotes.
Returns
-------
string
NEWICK representation of split specified by ``bitmask``.
"""
return taxon_namespace.bitmask_as_newick_string(
bitmask=self._leafset_bitmask,
preserve_spaces=preserve_spaces,
quote_underscores=quote_underscores)
def leafset_taxa(self, taxon_namespace, index=0):
"""
Returns list of |Taxon| objects in the leafset of this
bipartition.
Parameters
----------
taxon_namespace : |TaxonNamespace| instance
The operational taxonomic unit concept namespace to reference.
index : integer, optional
Start from this |Taxon| object instead of the first
|Taxon| object in the collection.
Returns
-------
:py:class:`list` [|Taxon|]
List of |Taxon| objects specified or spanned by
``bitmask``.
"""
return taxon_namespace.bitmask_taxa_list(
bitmask=self._leafset_bitmask,
index=index)
# def as_newick_string
# def is_trivial
# def is_non_singleton
# def leafset_hash
# def leafset_as_bitstring
# def is_compatible
##############################################################################
### Edge
class Edge(
basemodel.DataObject,
basemodel.Annotable):
"""
An :term:``edge`` on a :term:``tree``.
"""
###########################################################################
### Life-cycle and Identity
def __init__(self, **kwargs):
"""
Keyword Arguments
-----------------
head_node : |Node|, optional
Node from to which this edge links, i.e., the child node of this
node ``tail_node``.
length : numerical, optional
A value representing the weight of the edge.
rootedge : boolean, optional
Is the child node of this edge the root or seed node of the tree?
label : string, optional
Label for this edge.
"""
basemodel.DataObject.__init__(self, label=kwargs.pop("label", None))
self._head_node = kwargs.pop("head_node", None)
if "tail_node" in kwargs:
raise TypeError("Setting the tail node directly is no longer supported: instead, set the parent node of the head node")
self.rootedge = kwargs.pop("rootedge", None)
self.length = kwargs.pop("length", None)
if kwargs:
raise TypeError("Unsupported keyword arguments: {}".format(kwargs))
self._bipartition = None
self.comments = []
def __copy__(self, memo=None):
raise TypeError("Cannot directly copy Edge")
def taxon_namespace_scoped_copy(self, memo=None):
raise TypeError("Cannot directly copy Edge")
def __deepcopy__(self, memo=None):
# call Annotable.__deepcopy__()
return basemodel.Annotable.__deepcopy__(self, memo=memo)
# return super(Edge, self).__deepcopy__(memo=memo)
def __hash__(self):
return id(self)
def __eq__(self, other):
return self is other
def __lt__(self, other):
return id(self) < id(other)
###########################################################################
### Basic Structure
def _get_tail_node(self):
if self._head_node is None:
return None
return self._head_node._parent_node
def _set_tail_node(self, node):
if self._head_node is None:
raise ValueError("'_head_node' is 'None': cannot assign 'tail_node'")
# Go through managed property instead of
# setting attribute to ensure book-keeping
self._head_node.parent_node = node
tail_node = property(_get_tail_node, _set_tail_node)
def _get_head_node(self):
return self._head_node
def _set_head_node(self, node):
# Go through managed property instead of setting attribute to ensure
# book-keeping; following should also set ``_head_node`` of ``self``
node.edge = self
head_node = property(_get_head_node, _set_head_node)
def is_leaf(self):
"Returns True if the head node has no children"
return self.head_node and self.head_node.is_leaf()
def is_terminal(self):
return self.is_leaf()
def is_internal(self):
"Returns True if the head node has children"
return self.head_node and not self.head_node.is_leaf()
def get_adjacent_edges(self):
"""
Returns a list of all edges that "share" a node with ``self``.
"""
he = [i for i in self.head_node.incident_edges() if i is not self]
te = [i for i in self.tail_node.incident_edges() if i is not self]
he.extend(te)
return he
adjacent_edges = property(get_adjacent_edges)
###########################################################################
### Structural Manipulation
def collapse(self, adjust_collapsed_head_children_edge_lengths=False):
"""
Inserts all children of the head_node of self as children of the
tail_node of self in the same place in the child_node list that
head_node had occupied. The edge length and head_node will no longer be
part of the tree unless ``adjust_collapsed_head_children_edge_lengths``.
is True.
"""
to_del = self.head_node
parent = self.tail_node
if not parent:
return
children = to_del.child_nodes()
if not children:
raise ValueError('collapse_self called with a terminal.')
pos = parent.child_nodes().index(to_del)
parent.remove_child(to_del)
for child in children:
parent.insert_child(pos, child)
pos += 1
if adjust_collapsed_head_children_edge_lengths and self.length is not None:
# print id(child), child.edge.length, self.length
if child.edge.length is None:
child.edge.length = self.length
else:
child.edge.length += self.length
def invert(self, update_bipartitions=False):
"""
Changes polarity of edge.
"""
# self.head_node, self.tail_node = self.tail_node, self.head_node
if not self.head_node:
raise ValueError("Cannot invert edge with 'None' for head node")
if not self.tail_node:
raise ValueError("Cannot invert edge with 'None' for tail node")
old_head_node = self.head_node
new_tail_node = old_head_node
old_tail_node = self.tail_node
new_head_node = old_tail_node
grandparent = old_tail_node._parent_node
if grandparent is not None:
for idx, ch in enumerate(grandparent._child_nodes):
if ch is old_tail_node:
grandparent._child_nodes[idx] = old_head_node
break
else:
# we did not break loop: force insertion of old_head_node if
# not already there
if old_head_node not in grandparent._child_nodes:
grandparent._child_nodes.append(old_head_node)
assert old_head_node in old_tail_node._child_nodes
old_tail_node.remove_child(old_head_node)
assert old_head_node not in old_tail_node._child_nodes
old_head_node.add_child(old_tail_node)
old_tail_node.edge.length, old_head_node.edge.length = old_head_node.edge.length, old_tail_node.edge_length
###########################################################################
### Bipartition Management
def _get_bipartition(self):
if self._bipartition is None:
self._bipartition = Bipartition(
edge=self,
is_mutable=True,
)
return self._bipartition
def _set_bipartition(self, v=None):
self._bipartition = v
bipartition = property(_get_bipartition, _set_bipartition)
def _get_split_bitmask(self):
return self.bipartition._split_bitmask
def _set_split_bitmask(self, h):
self.bipartition._split_bitmask = h
split_bitmask = property(_get_split_bitmask, _set_split_bitmask)
def _get_leafset_bitmask(self):
return self.bipartition._leafset_bitmask
def _set_leafset_bitmask(self, h):
self.bipartition._leafset_bitmask = h
leafset_bitmask = property(_get_leafset_bitmask, _set_leafset_bitmask)
def _get_tree_leafset_bitmask(self):
return self.bipartition._tree_leafset_bitmask
def _set_tree_leafset_bitmask(self, h):
self.bipartition._tree_leafset_bitmask = h
tree_leafset_bitmask = property(_get_tree_leafset_bitmask, _set_tree_leafset_bitmask)
def split_as_bitstring(self):
return self.bipartition.split_as_bitstring()
def leafset_as_bitstring(self):
return self.bipartition.leafset_as_bitstring()
###########################################################################
### Representation
def description(self,
depth=1,
indent=0,
itemize="",
output=None,
taxon_namespace=None):
"""
Returns description of object, up to level ``depth``.
"""
if depth is None or depth < 0:
return
output_strio = StringIO()
if self.label is None:
label = " (%s, Length=%s)" % (id(self), str(self.length))
else:
label = " (%s: '%s', Length=%s)" % (id(self), self.label, str(self.length))
output_strio.write('%s%sEdge object at %s%s'
% (indent*' ',
itemize,
hex(id(self)),
label))
if depth >= 1:
leader1 = ' ' * (indent + 4)
leader2 = ' ' * (indent + 8)
output_strio.write('\n%s[Length]' % leader1)
if self.length is not None:
length = self.length
else:
length = "None"
output_strio.write('\n%s%s' % (leader2, length))
output_strio.write('\n%s[Tail Node]' % leader1)
if self.tail_node is not None:
tn = self.tail_node.description(0)
else:
tn = "None"
output_strio.write('\n%s%s' % (leader2, tn))
output_strio.write('\n%s[Head Node]' % leader1)
if self.head_node is not None:
hn = self.head_node.description(0)
else:
hn = "None"
output_strio.write('\n%s%s' % (leader2, hn))
s = output_strio.getvalue()
if output is not None:
output.write(s)
return s
##############################################################################
### Node
class Node(
basemodel.DataObject,
basemodel.Annotable):
"""
A :term:|Node| on a :term:|Tree|.
"""
def edge_factory(cls, **kwargs):
"""
Creates and returns a |Edge| object.
Derived classes can override this method to provide support for
specialized or different types of edges on the tree.
Parameters
----------
\*\*kwargs : keyword arguments
Passed directly to constructor of |Edge|.
Returns
-------
|Edge|
A new |Edge| object.