-
Notifications
You must be signed in to change notification settings - Fork 2
/
phylotreelib.py
4509 lines (3613 loc) · 194 KB
/
phylotreelib.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
"""Classes and methods for analyzing, manipulating, and building phylogenetic trees"""
# Anders Gorm Pedersen
# Section for Bioinformatics, DTU Health Technology, Technical University of Denmark
import copy
import functools
import itertools
import math
import random
import re
import statistics
import sys
from io import StringIO
from operator import itemgetter
import numpy as np
###################################################################################################
###################################################################################################
##
## Implementation notes:
## (1) In principle all leafnames are duplicated many times (once per bipartition in
## bipartsummary and toposummary). However, python appears to automagically
## map all identical unbroken strings (=no whitespace) to the same id:
##
## >>> a='tetM_X90939_Streptococcus_pneu'
## >>> b='tetM_X90939_Streptococcus_pneu'
## >>> a is b
## True
##
## >>> a='does not work if string contains blanks'
## >>> b='does not work if string contains blanks'
## >>> a is b
## False
##
## However, since this is dependent on implementation of python, I should probably
## code around it explicitly
##
## NOTE: I have now added explicit sys.intern() for all leafnames.
## check that this behaves as expected wrt performance (and remove Globals perhaps)
##
## (2) Although there is some extra overhead in using classes to emulate structs,
## using dicts instead does not make a big difference performancewise (I tried).
##
## (3) Treestrings could be parsed recursively in fewer lines, but this works a lot
## less efficiently than the iterated version currently in Tree.from_string()
## (I tested it).
##
###################################################################################################
###################################################################################################
###################################################################################################
###################################################################################################
#
# Various functions used by methods, that do not fit neatly in any class
###################################################################################################
def remove_comments(text):
"""Takes input string and strips away commented text, delimited by '[' and ']'.
Also deals with nested comments."""
# Python note: could be simplified
# Before spending any time:
# bail if there are no comment delimiters in string
# raise exception if comment delimiters not balanced
if "[" not in text:
return text
elif text.count("[") != text.count("]"):
raise TreeError("String contains different number of left and right comment delimiters")
# Preprocess delims for use in re etc
leftdelim = re.escape("[")
rightdelim = re.escape("]")
# Construct sorted list of tuples of the form [(0, 'start'), (5, 'stop'), (7, 'start'), ...]
delimlist = [(match.start(), match.end(), "start") for match in re.finditer(leftdelim, text)]
delimlist.extend([(match.start(), match.end(), "stop") for match in re.finditer(rightdelim, text)])
delimlist.sort()
# Traverse text; along the way copy text not inside comment-delimiter pairs.
# Use stack ("unmatched_starts") to keep track of nesting
unmatched_starts = 0
prevpos = 0
processed_text = []
for (match_start, match_end, match_type) in delimlist:
if match_type == "start":
unmatched_starts += 1
if unmatched_starts == 1: # Beginning of new comment region
processed_text.append(text[prevpos:match_start])
elif match_type == "stop":
unmatched_starts -= 1
if unmatched_starts == 0: # End of comment region
prevpos = match_end
elif unmatched_starts == -1: # Error: more right delims than left delims
raise TreeError("Unmatched end-comment delimiter. Context: '{}'".format(text[prevpos-10:prevpos+10]))
# Add final block of text if relevant (i.e., if text does not stop with rightdelim), return processed text
if prevpos < len(text):
processed_text.append(text[prevpos:])
return "".join(processed_text)
###################################################################################################
###################################################################################################
class Globals():
"""Class containing globally used functions and labels."""
# I'm not convinced this is the way to go. Module instead?"""
# Global repository for bipartitions, to avoid redundant saving in topologies etc.
biparts = {}
###################################################################################################
###################################################################################################
class Interner():
"""Class used for interning various objects."""
# Stores dictionaries of leafset, bipartitions, and topologies
# Interner methods returns *pointer* to leafset or bipartition
# Could perhaps just use one dict for interning *anything*, but worry about hash collisions?
def __init__(self):
self.leafsets = {}
self.biparts = {}
self.topo = {}
def intern_leafset(self, leafset):
if leafset not in self.leafsets:
self.leafsets[leafset]=leafset
return self.leafsets[leafset]
def intern_bipart(self, bipart):
if bipart not in self.biparts:
self.biparts[bipart]=bipart
return self.biparts[bipart]
def intern_topology(self, topology):
if topology not in self.topo:
self.topo[topology]=topology
return self.topo[topology]
###################################################################################################
###################################################################################################
class Branchstruct:
"""Class that emulates a struct. Keeps branch-related info"""
def __init__(self, length=0.0, label=""):
self.length = length
self.label = label
###############################################################################################
def copy(self):
"""Returns copy of Branchstruct object, with all attributes included"""
# Python note: deepcopy may be overkill and possibly costly.
# Maybe only copy blen and lab?
obj = Branchstruct()
for attrname, value in vars(self).items():
setattr(obj, attrname, copy.deepcopy(value))
return obj
###################################################################################################
###################################################################################################
class Topostruct:
"""Class that emulates a struct. Keeps topology-related info"""
__slots__ = ["weight", "tree", "freq"]
# Python note: perhaps replace with dataclass, available since python 3.7
pass
###################################################################################################
###################################################################################################
class TreeError(Exception):
pass
###################################################################################################
###################################################################################################
class Tree():
"""Class representing basic phylogenetic tree object."""
# Implementation note: Tree objects can be constructed from several different kinds of things:
# including Newick tree strings, Bipartition lists, and a list of leaves.
# The Tree class therefore has several alternate constructors implemented as classmethods
# The main constructor "__init__" is therefore mostly empty
def __init__(self):
self._parent_dict = None # Dict node:parent relationships (only built if required)
self.dist_dict = None
self.path_dict = None
###############################################################################################
@property
def parent_dict(self):
"""Lazy evaluation of _parent_dict when needed"""
if self._parent_dict == None:
self.build_parent_dict()
return self._parent_dict
###############################################################################################
def build_parent_dict(self):
"""Constructs _parent_dict enabling faster lookups, when needed"""
self._parent_dict = {}
for parent in self.intnodes:
for child in self.tree[parent]:
self._parent_dict[child] = parent
self._parent_dict[self.root] = None # Add special value "None" as parent of root
###############################################################################################
@classmethod
def from_string(cls, orig_treestring, transdict=None):
"""Constructor: Tree object from tree-string in Newick format"""
obj = cls()
# NOTE: interprets non-leaf labels as belonging to an internal branch (not to
# an internal node). The label is attached to the same branch as the branch length
# Remove whitespace (string methods are much faster than regexp.sub)
treestring = orig_treestring.replace(" ", "")
treestring = treestring.replace("\t", "")
treestring = treestring.replace("\n", "")
treestring = treestring.replace("\r", "")
treestring = treestring.replace("\f", "")
# Sanity check: number of left- and right-parentheses should match
if treestring.count("(") != treestring.count(")"):
msg = "Imbalance in tree-string: different number of left- and right-parentheses\n"
msg += "Left: ({0} Right: {1})".format(treestring.count("("), treestring.count(")"))
raise TreeError(msg)
# Break treestring up into a list of parentheses, commas, names, and branch lengths
# ("tokenize")
# Python note: characters that are not one of the below, will be quietly discarded
# this includes things such as quotes, ampersands, dollarsigns etc.
# possibly this is a good idea, but may cause trouble (figtree format for instance)
tree_parts = re.compile(r""" # Save the following sub-patterns:
\( | # (1) a left parenthesis
\) | # (2) a right parenthesis
, | # (3) a comma
; | # (4) a semicolon
:[+-]?\d*\.?\d+(?:[eE][-+]?\d+)? | # (5) a colon followed by a branch length
# possibly negative,
# possibly using exponential notation
[\w\-\/\.\*\|]+ | # (6) a name/label (one or more alphanumeric)
\[.*?\] # (7) a bracketted comment
# typically from FigTree
# placed as branch label
""", re.VERBOSE)
tree_parts_list = tree_parts.findall(treestring)
# Tree is represented as a dictionary of dictionaries. The keys in the top dictionary
# are the internal nodes which are numbered consecutively. Each key has an
# associated value that is itself a dictionary listing the children: keys are
# child nodes, values are Branchstructs containing "length" and "label" fields.
# Leafs are identified by a string instead of a number
# NOTE: self.tree should ONLY be used by this object. Make pseudo-private?
obj.tree = {} # Essentially a "child-list"
obj.leaves = set() # Set of leaf names. For speedy lookups
obj.intnodes = set() # Set of internal node IDs. For speedy lookups
obj.root = 0 # Root is node zero at start. (May change)
obj.belowroot = None
# Preprocess parts list to remove and store any labels or lengths below root node
# Any text here (between the semicolon and the last right parenthesis)
# will be stores as _one_ string in "self.belowroot"
i = -2
extraparts = []
while tree_parts_list[i] != ")":
extraparts.append(tree_parts_list[i])
i -= 1
if extraparts:
extraparts.reverse()
obj.belowroot = "".join(extraparts)
del tree_parts_list[(i+1):-1]
# Parse tree_parts_list left to right. Use a stack to keep track of current node
nodeno = -1
node_stack = []
for part in tree_parts_list:
# A left parenthesis indicates that we are about to examine a new internal node.
if part == "(" :
nodeno += 1
obj.tree[nodeno] = {} # Create child-list for new node
if nodeno != 0: # If we are not at the root then add new node
parent = node_stack[-1] # to previous node's list of children
obj.tree[parent][nodeno] = Branchstruct()
node_stack.append(nodeno) # Push new node onto stack
obj.intnodes.add(nodeno) # Add node to list of internal nodes
# A right parenthesis indicates that we have finished examining a node
# I should maybe catch the "IndexError: pop from empty list" somewhere
elif part == ")":
del node_stack[-1] # Remove last examined node from stack
# A colon indicates this is a distance
elif part[0] == ":":
dist = float(part[1:]) # Remove colon and convert to float
child = node_stack[-1]
parent = node_stack[-2]
obj.tree[parent][child].length = dist # Add dist to relevant child-list
# A comma indicates that we have finished examining a node
elif part == ",":
del node_stack[-1] # Remove last examined node from stack
# A semicolon indicates the end of the treestring has been reached
elif part == ";":
del node_stack[-1] # Clean up stack
# If nothing else matched then this must be a name or label
# If previous part was simultaneously a right parenthesis or a leaf name,
# then the token must be a branch label
elif prevpart in [")", "leafname"]:
child = node_stack[-1]
parent = node_stack[-2]
obj.tree[parent][child].label = part
# Last possibility (I hope): the name is a leafname
else:
# If translation dictionary was supplied: change name accordingly
if transdict:
child = sys.intern(transdict[part]) # Already interned. Not sure this is needed...
else:
child = sys.intern(part) # "Intern" strings so only one copy in memory
# (may happen automatically anyway?...)
# Check for duplicated leaf names
if child in obj.leaves:
msg = "Leaf name present more than once: {}".format(child)
raise TreeError(msg)
parent=node_stack[-1] # Add new leaf node to previous node's
obj.tree[parent][child] = Branchstruct() # list of children
node_stack.append(child) # Push new leaf node onto stack
obj.leaves.add(child) # Also update list of leaves
part = "leafname"
prevpart = part
# If nodes remain on stack after parsing, then something was wrong with tree-string
if node_stack:
msg = "Imbalance in tree-string: '%s'" % orig_treestring
raise TreeError(msg)
obj.nodes = obj.leaves | obj.intnodes
return obj
###############################################################################################
@classmethod
def from_biplist(cls, biplist):
"""Constructor: Tree object from bipartition list"""
# Input is a bipartitionlist (actually a dictionary of bipartition:Branchstruct pairs):
# Names of leaves on one side of a branch are represented as an immutable set of leaves
# A bipartition is represented as an immutable set of two such (complementary) sets
# The entire tree is represented as a dictionary of bipartition:Branchstruct pairs
obj = cls()
# Extract set of leaves
part1, part2 = next(iter(biplist)) # First key=set of two leaf name sets
obj.leaves = part1 | part2 # Concatenate them to get all leafnames
obj.intnodes = {0} # Will be built as we go along
obj.root = 0 # Root is node zero at start
# This may change after re-rooting etc
# Tree is represented as a dictionary of dictionaries. The keys in the top dictionary
# are the internal nodes, which are numbered consecutively. Each key has an associated
# value that is itself a dictionary listing the children: keys are child nodes, values are
# Branchstructs containing "length" (float) and "label" (str) fields.
# Leafs are identified by a string instead of a number
# Construct tree dictionary (main data structure, essentially a child list)
obj.tree = {}
obj.tree[0]={}
maxnode = 0
# Start by building star-tree, this is resolved branch-by-branch later on
# Python note: use startree constructor?
for leaf in obj.leaves:
obj.tree[0][leaf]= None
# Iterate over all bipartitions, for each: add extra branch and/or update Branchstruct
for (bip1, bip2), branchstruct in biplist.items():
# If bipartition represents external branch: update relevant Branchstruct
if len(bip1) == 1 or len(bip2) == 1:
if len(bip1) == 1:
(leaf, ) = bip1 # A one-member tuple used for value unpacking (pop)
else:
(leaf, ) = bip2
# Find childdict containing leaf, and update branchstruct
for childdict in obj.tree.values():
if leaf in childdict:
childdict[leaf] = branchstruct
break
# If bipartition represents internal branch: add branch to tree, transfer Branchstruct
else:
mrca1 = obj.find_mrca(bip1)
mrca2 = obj.find_mrca(bip2)
# Determine which group of leaves to move
# Note: one part of bipartition will necessarily have root as its MRCA
# since the members are present on both sides of root. It is the other part of
# the bipartition (where all members are on same side of root) that should be moved
# For a star-tree the resolution will be random (both have root as their MRCA)
if mrca1 == 0: # If mrca is root, move other group
insertpoint = mrca2
active_bip = bip2
else:
insertpoint = mrca1
active_bip = bip1
# Determine which of insertpoints children to move, namely all children
# that are either in the active bipartition OR children whose descendants are
moveset = []
for child in obj.children(insertpoint):
if child in active_bip:
moveset.append(child)
elif (child not in obj.leaves) and (obj.remote_children(child) <= active_bip):
moveset.append(child)
# Construct new internal node (and therefore branch), transfer Branchstruct
maxnode += 1
obj.tree[maxnode] = {}
obj.tree[insertpoint][maxnode] = branchstruct
obj.intnodes.add(maxnode) # Add new node to list of internal nodes
# Move relevant children to new node, transfer Branchstructs
for child in moveset:
obj.tree[maxnode][child] = obj.tree[insertpoint][child]
del obj.tree[insertpoint][child]
obj.nodes = set(obj.leaves | obj.intnodes)
return obj
###############################################################################################
@classmethod
def from_topology(cls, topology):
"""Constructor: Tree object from topology"""
# Input is a topology, i.e., a set of bipartitions
# Names of leaves on one side of a branch are represented as an immutable set of leaves
# A bipartition is represented as an immutable set of two such (complementary) sets
# Huge overlap with from_biplist: difference is this doesnt have Branchstructs to begin with
# Think about mergin code, with flag for branchstruct presence
obj = cls()
# Extract set of leaves
part1, part2 = next(iter(topology)) # First item=set of two leaf name sets
obj.leaves = part1 | part2 # Concatenate them to get all leafnames
obj.intnodes = {0} # Will be built as we go along
obj.root = 0 # Root is node zero at start
# This may change after re-rooting etc
# Tree is represented as a dictionary of dictionaries. The keys in the top dictionary
# are the internal nodes, which are numbered consecutively. Each key has an associated
# value that is itself a dictionary listing the children: keys are child nodes, values are
# Branchstructs containing "length" (float) and "label" (str) fields.
# Leafs are identified by a string instead of a number
# Construct tree dictionary (main data structure, essentially a child list)
obj.tree = {}
obj.tree[0]={}
maxnode = 0
# Start by building star-tree, this is resolved branch-by-branch later on
for leaf in obj.leaves:
obj.tree[0][leaf]= Branchstruct()
# Iterate over all bipartitions, for each: add extra branch and/or update Branchstruct
for bip1, bip2 in topology:
# If bipartition represents internal branch: add branch to tree
if len(bip1) > 1 and len(bip2) > 1:
mrca1 = obj.find_mrca(bip1)
mrca2 = obj.find_mrca(bip2)
# Determine which group of leaves to move
# Note: one part of bipartition will necessarily have root as its MRCA
# since the members are present on both sides of root. It is the other part of
# the bipartition (where all members are on same side of root) that should be moved
# For a star-tree the resolution will be random (both have root as their MRCA)
if mrca1 == 0: # If mrca is root, move other group
insertpoint = mrca2
active_bip = bip2
else:
insertpoint = mrca1
active_bip = bip1
# Determine which of insertpoints children to move, namely all children
# that are either in the active bipartition OR children whose descendants are
moveset = []
for child in obj.children(insertpoint):
if child in active_bip:
moveset.append(child)
elif (child not in obj.leaves) and (obj.remote_children(child) <= active_bip):
moveset.append(child)
# Construct new internal node (and therefore branch)
maxnode += 1
obj.tree[maxnode] = {}
obj.tree[insertpoint][maxnode] = Branchstruct()
obj.intnodes.add(maxnode) # Add new node to list of internal nodes
# Move relevant children to new node, transfer Branchstructs
for child in moveset:
obj.tree[maxnode][child] = obj.tree[insertpoint][child]
del obj.tree[insertpoint][child]
obj.nodes = set(obj.leaves | obj.intnodes)
return obj
###############################################################################################
@classmethod
def from_leaves(cls, leaflist):
"""Constructor: star-tree object from list of leaves"""
treelist = ["("]
for name in leaflist:
treelist.append(name)
treelist.append(",")
del treelist[-1]
treelist.append(");")
return cls.from_string("".join(treelist))
###############################################################################################
@classmethod
def from_branchinfo(cls, parentlist, childlist, lenlist=None, lablist=None):
"""Constructor: Tree object from information about all branches in tree
Information about one branch is conceptually given as:
parentnodeID, childnodeID, [length], [label]
The function takes as input 2 to 4 separate lists containing:
IDs of parents (internal nodes, so integer values)
ID of children (internal or leaf nodes, so integer or string)
Length of branches (optional)
Label of branches (optional)
The four lists are assumed to have same length and be in same order (so index n in
each list corresponds to same branch).
Note: most IDs appear multiple times in lists
Note 2: can be used as workaround so user can specify IDs for internal nodes"""
nbranches = len(parentlist)
if lenlist is None:
lenlist = [0.0]*nbranches
if lablist is None:
lablist = [""]*nbranches
for lst in [childlist, lenlist, lablist]:
if len(lst) != nbranches:
msg = "All lists provided to from_branchinfo() must have same length:\n"
msg += str(lst)
raise TreeError(msg)
obj = cls() # Ensures class will be correct also for subclasses of Tree
obj.tree = {}
obj.leaves = set()
obj.intnodes = set()
for i in range(nbranches):
parent = parentlist[i] # Perhaps check types are OK?
child = childlist[i]
blen = lenlist[i]
lab = lablist[i]
if parent in obj.tree:
obj.tree[parent][child] = Branchstruct(blen, lab)
else:
obj.tree[parent] = { child:Branchstruct(blen, lab) }
obj.intnodes.add(parent)
if isinstance(child, str):
obj.leaves.add(child)
# Root node is the parent node that is not also in childlist
diffset = set(parentlist) - set(childlist)
obj.root = diffset.pop()
obj.nodes = obj.leaves | obj.intnodes
return obj
###############################################################################################
@classmethod
def randtree(cls, leaflist=None, ntips=None, randomlen=False, name_prefix="s"):
"""Constructor: tree with random topology from list of leaf names OR number of tips"""
# Implementation note: random trees are constructed by randomly resolving star-tree
# Should perhaps use actual bifurcating process to generate random trees instead?
# At least when adding branch lengths (otherwise distribution of brlens on tree will
# be quite different from real trees, thus biasing statistical inference
if leaflist is None and ntips is None:
msg = "Must specify either list of leafnames or number of tips to create random tree"
raise TreeError(msg)
if leaflist is not None and ntips is not None:
msg = "Only specify either list of leafnames or number of tips to create random tree"\
" (not both)"
raise TreeError(msg)
# If leaflist given:
# construct startree using names, then resolve to random bifurcating topology
if leaflist is not None and ntips is None:
tree = cls.from_leaves(leaflist)
# If ntips given:
# construct list of zeropadded, numbered, names,
# then construct startree using names, finally resolve to random topology
else:
ndigits = len(str(ntips)) # Number of digits required to write max taxon number
namelist = []
for i in range(ntips):
name = "{prefix}{num:0{width}d}".format(prefix=name_prefix, num=i, width=ndigits)
namelist.append( name )
tree = cls.from_leaves(namelist) # Star tree with given number of leaves
tree.resolve() # Randomly resolve to bifurcating tree
if randomlen:
for parent in tree.intnodes:
for child in tree.tree[parent]:
tree.tree[parent][child].length = random.lognormvariate(math.log(0.2), 0.3)
return tree
###############################################################################################
def __iter__(self):
"""Returns iterator object for Tree object. Yields subtrees with .basalbranch attribute"""
# Basal branch struct may contain useful information: e.g., label and length below subtree
# Single node trees consisting of leaves are also considered subtrees (REMOVE????)
class SubtreeIterator():
def __init__(self, fulltree):
self.basenodes = fulltree.sorted_intnodes()
self.basenodes.extend(fulltree.leaflist())
self.basenodes.remove(fulltree.root)
self.i = 0
self.fulltree = fulltree
def __iter__(self):
return self
def __next__(self):
if self.i >= len(self.basenodes):
raise StopIteration
self.i += 1
basenode = self.basenodes[self.i - 1]
(subtree, basalbranch) = self.fulltree.subtree(basenode, return_basalbranch=True)
subtree.basalbranch = basalbranch
return subtree
return SubtreeIterator(self)
###############################################################################################
def __str__(self):
"""Prints table of parent-child relationships including branch lengths and labels"""
# Starts by building a table of strings containing all information
# Then formats table into a string
# Headers
table = []
table.append(["Node", "Child", "Distance", "Label"])
# Build table of parent-child relationships
for node in self.sorted_intnodes():
for kid in self.children(node):
nodstr = str(node)
kidstr = str(kid)
dist = "{num:.6g}".format(num=self.tree[node][kid].length)
label = self.tree[node][kid].label
table.append([nodstr, kidstr, dist, label])
# Find widest string in each column
maxwidth = [0]*4
for row in table:
for i, word in enumerate(row):
if len(word) > maxwidth[i]:
maxwidth[i] = len(word)
totwidth = maxwidth[0]+maxwidth[1]+maxwidth[2]+maxwidth[3] + 19 # Flanking space
# Build string from table:
# Header line
tabstring = "|" + "-" * (totwidth) + "|" + "\n"
for j in range(4):
tabstring += "| "+ table[0][j].center(maxwidth[j]) + " "
tabstring += "|\n"
tabstring += "|" + "-" * (totwidth) + "|" + "\n"
# Rest of table
for i in range(1, len(table)):
for j in range(4):
tabstring += "| "+ table[i][j].rjust(maxwidth[j]) + " "
tabstring += "|\n"
tabstring += "|" + "-" * (totwidth) + "|" + "\n"
# Add list of leaves to tablestring
tabstring += "\n%d Leafs:\n" % len(self.leaves)
tabstring += "-" * maxwidth[1] + "\n"
for leaf in sorted(self.leaves):
tabstring += "%s\n" % leaf
return tabstring
###############################################################################################
def __eq__(self, other, blenprecision=0.005):
"""Implements equality testing for Tree objects"""
# Two trees are identical if they have the same leaves, the same topology
# and the same branchlengths. Branch labels are ignored. Rooting is ignored
# NB: floating point comparison of relative difference.
# Precision chosen based on empirical comparison between own and PHYLIP tree (...)
if self.leaves != other.leaves:
return False
if self.topology() != other.topology():
return False
bipself = self.bipdict()
bipother = other.bipdict()
for bipart in bipself:
len1 = bipself[bipart].length
len2 = bipother[bipart].length
if len1 != 0 and len2 != 0:
if (abs(len1 - len2) / len1) > blenprecision: # Floating point comparison of relative diff
return False
if (len1 == 0 and len2 > 0) or (len1 > 0 and len2 == 0):
return False
# If we made it this far without returning, then Tree objects must be identical
return True
###############################################################################################
def __hash__(self):
"""Implements hashing for Tree objects, so they can be used as keys in dicts"""
# Using hash = id of self.
# NOTE: this does NOT live up to reasonable hash-criteria... Change at some point.
# NOTE2: Also unsure about effect on performance
return id(self)
###############################################################################################
def copy_treeobject(self, copylengths=True, copylabels=True):
"""Returns copy of Tree object. Copies structure and branch lengths.
Caches and any user-added attributes are not copied.
Similar to effect of copy.deepcopy but customized and much faster"""
# Python note: reconsider copying attributes besides blen and lab?
obj = Tree()
obj.root = self.root
obj.leaves = self.leaves.copy()
obj.intnodes = self.intnodes.copy()
obj.nodes = self.nodes.copy()
obj.tree = {}
origtree = self.tree
newtree = obj.tree
for parent in origtree:
newtree[parent] = {}
for child in origtree[parent]:
if copylengths:
blen = origtree[parent][child].length
else:
blen = 0.0
if copylabels:
lab = origtree[parent][child].label
else:
lab = ""
newtree[parent][child] = Branchstruct(blen,lab)
return obj
###############################################################################################
def build_dist_dict(self):
"""Construct dictionary keeping track of all pairwise distances between nodes"""
# Data structures and algorithm inspired by the Floyd-Warshall algorithm, but modified and
# faster than O(n^3) since it is on a tree (unique paths)
# Python note: maybe I could check for existence before recomputing
# (but then important to clear after changes!)
# Python note 2: dict.fromkeys does something clever about presizing dict so there is less
# of a performance hit when it is later added to, hence the slightly odd initialisation
# (25% faster than dict comprehension)
dist = self.dist_dict = dict.fromkeys(self.nodes)
for key in dist:
dist[key] = {}
tree = self.tree
combinations = itertools.combinations
# Traverse tree starting from root, breadth-first (sorted_intnodes)
# This is required for below algorithm to work
intnodes = self.sorted_intnodes()
for parent in intnodes:
children = tree[parent].keys()
if dist[parent]:
prev_contacts = dist[parent].keys()
for child in children:
childlen = tree[parent][child].length
for prev_contact in prev_contacts:
totlen = dist[prev_contact][parent] + childlen
dist[prev_contact][child] = totlen
dist[child][prev_contact] = totlen
for (child1, child2) in combinations(children, 2):
totlen = tree[parent][child1].length + tree[parent][child2].length
dist[child1][child2] = totlen
dist[child2][child1] = totlen
for child in children:
totlen = tree[parent][child].length
dist[parent][child] = totlen
dist[child][parent] = totlen
# Fill in diagonal (zero entries), just in case
for node in self.nodes:
dist[node][node] = 0
###############################################################################################
def build_path_dict(self):
"""Construct dictionary keeping track of all pairwise paths between nodes"""
# Data structures and algorithm inspired by the Floyd-Warshall algorithm,
# but modified and faster than O(n^3) since it is on a tree (unique paths)
# Python note: dict.fromkeys does something clever about presizing dict so there is less
# of a performance hit when it is later added to, hence the slightly odd initialisation
path = self.path_dict = dict.fromkeys(self.nodes)
for key in path:
path[key] = {}
tree = self.tree
combinations = itertools.combinations
# Traverse tree starting from root, breadth-first (sorted_intnodes)
# This is required for algorithm to work
intnodes = self.sorted_intnodes()
for parent in intnodes:
children = tree[parent].keys()
if path[parent]:
prev_contacts = path[parent].keys()
for child in children:
for prev_contact in prev_contacts:
path[prev_contact][child] = path[prev_contact][parent]
path[child][prev_contact] = parent
for (child1, child2) in combinations(children, 2):
path[child1][child2] = path[child2][child1] = parent
for child in children:
path[parent][child] = child
path[child][parent] = parent
###############################################################################################
def sorted_intnodes(self, deepfirst=True):
"""Returns sorted intnode list for breadth-first traversal of tree"""
# "intnodes" is a set, meaning iteration occurs in no defined order.
# This function returns a list sorted such that deep nodes generally go before
# shallow nodes (deepfirst=False reverses this)
# Add nodes one tree-level at a time.
# First root, then children of root, then children of those, etc
sorted_nodes = []
curlevel = {self.root}
while curlevel:
sorted_nodes.extend(curlevel)
nextlevel = []
# For each node in current level: add those children that are also internal nodes
for node in curlevel:
nextlevel.extend(self.children(node) & self.intnodes)
curlevel = nextlevel
if not deepfirst:
sorted_nodes.reverse()
return sorted_nodes
###############################################################################################
def is_bifurcation(self, node):
"""Checks if internal node is at bifurcation (has two children)"""
try:
nkids = len(self.children(node))
return (nkids == 2)
except:
raise TreeError("Node is leaf. Can't check for bifurcation when no children")
###############################################################################################
def n_bipartitions(self):
"""Returns the number of bipartitions (= number of internal branches) in tree
Note: if root is at bifurcation, then those 2 branches = 1 bipartition"""
nbip = 0
for n1 in self.intnodes:
for n2 in self.children(n1):
if n2 in self.intnodes:
nbip +=1
if self.is_bifurcation(self.root):
nbip -= 1
return nbip
###############################################################################################
def leaflist(self):
"""Returns list of leaf names sorted alphabetically"""
leafnamelist = list(self.leaves)
leafnamelist.sort()
return leafnamelist
###############################################################################################
def transdict(self):
"""Returns dictionary of {name:number_as_string} for use in translateblocks"""
leafnamelist = self.leaflist()
transdict = {}
for i,leafname in enumerate(leafnamelist):
transdict[leafname] = f"{i+1}"
return transdict
###############################################################################################
def translateblock(self, transdict):
translist = [" translate\n"]
for number,name in transdict.items():
translist.append(f" {name:<4s} {number}")
translist.append(",\n")
translist[-1] = "\n ;\n"
translateblock = "".join(translist)
return translateblock
###############################################################################################
def children(self, parent):
"""Returns set containing parent's immediate descendants"""
# Python note: does not seem to benefit from lru_caching, and leads to multiple problems
try:
return set(self.tree[parent].keys())
except KeyError as err:
msg = "Node %s is not an internal node" % parent
raise TreeError(msg) from err
###############################################################################################
#@functools.lru_cache(maxsize=None)
def remote_children(self, parent):
"""Returns set containing all leaves that are descendants of parent"""
# If "parent" is a leaf, then return a set consisting of only itself
if parent in self.leaves:
return {parent}
# Traverse the tree iteratively to find remote children:
# if kid is leaf: add it to list of remote children.
# if kid is intnode: push its children on stack
kidstack = set( self.tree[parent] )
remotechildren = set()
while kidstack:
curnode = kidstack.pop()
if curnode in self.leaves:
remotechildren.add(curnode)
else:
kidstack.update( self.tree[curnode] )
return remotechildren
###############################################################################################
def remote_nodes(self, parent):
"""Returns set containing all nodes (intnodes and leaves) that are descendants of parent.
This set includes parent itself"""
# If "parent" is a leaf, then return a set consisting of only itself