-
-
Notifications
You must be signed in to change notification settings - Fork 216
/
tree.pyx
2388 lines (1925 loc) · 91.9 KB
/
tree.pyx
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
import random
import copy
import itertools
from collections import deque, namedtuple
from hashlib import md5
from functools import cmp_to_key
import pickle
import logging
from . import text_viz
from .. import utils
from ete4.parser import newick
from ..parser import ete_format
# the following imports are necessary to set fixed styles and faces
# try:
try:
from ..treeview.main import NodeStyle
from ..treeview.faces import Face
TREEVIEW = True
except ImportError:
TREEVIEW = False
from ..smartview import Face as smartFace
from ..smartview.renderer.nodestyle import NodeStyle as smNodeStyle
from ..smartview.renderer.face_positions import Faces, make_faces
from ..smartview.renderer.layouts.default_layouts import (
LayoutLeafName, LayoutBranchLength, LayoutBranchSupport)
class TreeError(Exception):
pass
cdef class Tree(object):
"""
The Tree class is used to store a tree structure. A tree
consists of a collection of Tree instances connected in a
hierarchical way. Trees can be loaded from the New Hampshire Newick
format (newick).
"""
# TODO: Clean up all the memebers of Tree and leave only:
# up, props, children, size
cdef public Tree up
cdef public dict props
cdef public list _children
cdef public (double, double) size
# All these members below should go away.
cdef public object _img_style
cdef public object _sm_style
cdef public object _smfaces
cdef public object _collapsed_faces
cdef public int _initialized
cdef public int _collapsed
def __init__(self, data=None, children=None, parser=None):
"""
Examples::
t1 = Tree() # empty tree
t2 = Tree({'name': 'A'})
t3 = Tree('(A:1,(B:1,(C:1,D:1):0.5):0.5);')
t4 = Tree(open('/home/user/my-tree.nw'))
"""
self.children = children or []
self._img_style = None
# Do not initialize _faces and _collapsed_faces
# for performance reasons (pickling)
self._initialized = 0 # Layout fns have not been run on node
self.size = (0, 0)
data = data.read().strip() if hasattr(data, 'read') else data
if data is None:
self.props = {}
elif type(data) == dict:
self.props = data.copy()
else: # from newick or ete format
assert not children, 'init from parsed content cannot have children'
assert (type(parser) in [dict, int] or
parser in [None, 'newick', 'ete', 'auto']), 'bad parser'
if parser is None or parser == 'auto':
guess_format = lambda x: 'newick' # TODO
parser = guess_format(data)
if parser == 'newick':
self.init_from_newick(data)
elif type(parser) == dict:
self.init_from_newick(data, parser)
elif parser in newick.INT_PARSERS:
self.init_from_newick(data, newick.INT_PARSERS[parser])
elif parser == 'ete':
self.init_from_ete(data)
def init_from_newick(self, data, parser=None):
tree = newick.loads(data, parser, self.__class__)
self.children = tree.children
self.props = tree.props
def init_from_ete(self, data):
t = ete_format.loads(data)
self.name = t.name
self.dist = t.dist
self.support = t.support
self.children = t.children
@property
def name(self):
return str(self.props.get('name')) if 'name' in self.props else None
@name.setter
def name(self, value):
self.props['name'] = str(value)
@property
def dist(self):
return float(self.props['dist']) if 'dist' in self.props else None
@dist.setter
def dist(self, value):
self.props['dist'] = float(value)
@property
def support(self):
return float(self.props['support']) if 'support' in self.props else None
@support.setter
def support(self, value):
self.props['support'] = float(value)
@property
def children(self):
return self._children
@children.setter
def children(self, value):
self._children = []
self.add_children(value)
@property
def is_leaf(self):
"""Return True if the current node is a leaf."""
return not self.children
@property
def is_root(self):
"""Return True if the current node has no parent."""
return not self.up
@property
def root(self):
"""Return the absolute root node of the current tree structure."""
node = self
while node.up:
node = node.up
return node
@property
def id(self):
"""Return node_id (list of relative hops from root to node)."""
reversed_id = []
node = self
while node.up:
reversed_id.append(node.up.children.index(node))
node = node.up
return reversed_id[::-1] # will look like [0, 0, 1, 0]
@property
def level(self):
"""Return the number of nodes between this node and the root."""
n = 0
node = self.up
while node:
n += 1
node = node.up
return n
# TODO: Move all the next functions out of the Tree class.
def _get_style(self):
if self._img_style is None:
self._img_style = NodeStyle()
return self._img_style
def _set_style(self, value):
self.set_style(value)
def _get_sm_style(self):
if self._sm_style is None:
self._sm_style = smNodeStyle()
return self._sm_style
def _set_sm_style(self, value):
self.set_style(value)
def _get_initialized(self):
return self._initialized == 1
def _set_initialized(self, value):
if value:
self._initialized = 1
else:
self._initialized = 0
def _get_collapsed(self):
return self._collapsed == 1
def _set_collapsed(self, value):
if value:
self._collapsed = 1
else:
self._collapsed = 0
#: Node styling properties
img_style = property(fget=_get_style, fset=_set_style)
sm_style = property(fget=_get_sm_style, fset=_set_sm_style)
#: Whether layout functions have been run on node
is_initialized = property(fget=_get_initialized, fset=_set_initialized)
is_collapsed = property(fget=_get_collapsed, fset=_set_collapsed)
@property
def faces(self):
if self._smfaces is None:
self._smfaces = make_faces()
return self._smfaces
@faces.setter
def faces(self, value):
assert isinstance(value, Faces), 'Not a Faces instance: %r' % value
self._smfaces = value
@property
def collapsed_faces(self):
if self._collapsed_faces is None:
self._collapsed_faces = make_faces()
return self._collapsed_faces
@collapsed_faces.setter
def collapsed_faces(self, value):
assert isinstance(value, Faces), 'Not a Faces instance: %r' % value
self._collapsed_faces = value
def __bool__(self):
# If this is not defined, bool(t) will call len(t).
return True
def __repr__(self):
return 'Tree %r (%s)' % (self.name, hex(self.__hash__()))
def __getitem__(self, node_id):
"""Return the node that matches the given node_id."""
try:
if type(node_id) == str: # node_id can be the name of a node
return next(n for n in self.traverse() if n.name == node_id)
elif type(node_id) == int: # or the index of a child
return self.children[node_id]
else: # or a list/tuple of a descendant
node = self
for i in node_id:
node = node.children[i]
return node
except StopIteration:
raise TreeError(f'No node found with name: {node_id}')
except (IndexError, TypeError) as e:
raise TreeError(f'Invalid node_id: {node_id}')
def __add__(self, value):
"""Sum trees. t1 + t2 returns a new tree with children=[t1, t2]."""
# Should a make the sum with two copies of the original trees?
if type(value) == self.__class__:
new_root = self.__class__()
new_root.add_child(self)
new_root.add_child(value)
return new_root
else:
raise TreeError("Invalid node type")
def __str__(self):
"""Return a string with an ascii drawing of the tree."""
return self.to_str(show_internal=False, compact=True, props=['name'])
def to_str(self, show_internal=True, compact=False, props=None,
px=None, py=None, px0=0, waterfall=False):
return text_viz.to_str(self, show_internal, compact, props,
px, py, px0, waterfall)
def __contains__(self, item):
"""Return True if the tree contains the given item.
:param item: A node instance or its associated name.
"""
if isinstance(item, self.__class__):
return item in self.descendants()
elif type(item) == str:
return any(n.name == item for n in self.traverse())
else:
raise TreeError("Invalid item type")
def __len__(self):
"""Return the number of leaves."""
return sum(1 for _ in self.leaves())
def __iter__(self):
"""Yield all the terminal nodes (leaves)."""
yield from self.leaves()
def add_prop(self, prop_name, value):
"""Add or update node's property to the given value."""
if prop_name == 'dist':
self.dist = value
elif prop_name == 'support':
self.support = value
else:
self.props[prop_name] = value
def add_props(self, **props):
"""Add or update several properties."""
for prop_name, value in props.items():
self.add_prop(prop_name, value)
def del_prop(self, prop_name):
"""Permanently deletes a node's property."""
self.props.pop(prop_name, None)
# DEPRECATED #
def add_feature(self, pr_name, pr_value):
"""Add or update a node's feature."""
logging.warning('add_feature is DEPRECATED use add_prop instead')
self.add_prop(pr_name, pr_value)
def add_features(self, **features):
"""Add or update several features."""
logging.warning('add_features is DEPRECATED use add_props instead')
self.add_props(**features)
def del_feature(self, pr_name):
"""Permanently deletes a node's feature."""
logging.warning('del_feature is DEPRECATED use del_prop instead')
self.del_prop(pr_name)
# DEPRECATED #
# Topology management
def add_child(self, child=None, name=None, dist=None, support=None):
"""Add a new child to this node and return it.
If child node is not suplied, a new node instance will be created.
:param child: Node to be added as a child.
:param name: Name that will be given to the child.
:param dist: Distance from the node to the child.
:param support: Support value of child partition.
"""
if child is None:
child = self.__class__()
if name is not None:
child.name = name
if dist is not None:
child.dist = dist
if support is not None:
child.support = support
if type(child) != type(self):
raise TreeError(f'Incorrect child type: {type(child)}')
child.up = self
self.children.append(child)
return child
def add_children(self, children):
for child in children:
self.add_child(child)
return children
def pop_child(self, child_idx=-1):
try:
child = self.children.pop(child_idx)
except ValueError as e:
raise TreeError("child not found")
else:
child.up = None
return child
def remove_child(self, child):
"""
Removes a child from this node (parent and child
nodes still exit but are no longer connected).
"""
try:
self.children.remove(child)
except ValueError as e:
raise TreeError("child not found")
else:
child.up = None
return child
def remove_children(self):
children = list(self.children)
return [ self.remove_child(child) for child in children ]
def add_sister(self, sister=None, name=None, dist=None):
"""Add a sister to this node and return it.
If sister node is not supplied, a new Tree instance will be created.
"""
if self.up is None:
raise TreeError("A parent node is required to add a sister")
else:
return self.up.add_child(child=sister, name=name, dist=dist)
def remove_sister(self, sister=None):
"""Remove a sister node.
It has the same effect as self.up.remove_child(sister).
If a sister node is not supplied, the first sister will be deleted
and returned.
:param sister: A node instance to be removed as a sister.
:return: The node removed.
"""
sisters = self.get_sisters()
if not sisters:
raise TreeError("Cannot remove sister because there are no sisters")
return self.up.remove_child(sister or sisters[0])
def delete(self, prevent_nondicotomic=True, preserve_branch_length=False):
"""Delete node from the tree structure, keeping its children.
The children from the deleted node are transferred to the old parent.
:param prevent_nondicotomic: If True (default), it will also
delete parent nodes until no single-child nodes occur.
:param preserve_branch_length: If True, branch lengths
of the deleted nodes are transferred (summed up) to the
parent's branch, thus keeping original distances among
nodes.
Example::
t = Tree('(C,(B,A)H)root;')
print(t.to_str(props=['name']))
╭╴C
╴root╶┤
│ ╭╴B
╰╴H╶┤
╰╴A
t['H'].delete() # delete the "H" node
print(t.to_str(props=['name']))
╭╴C
│
╴root╶┼╴B
│
╰╴A
"""
parent = self.up
if not parent:
return # nothing to do, we cannot actually delete the root
if preserve_branch_length and 'dist' in self.props:
if len(self.children) == 1 and 'dist' in self.children[0].props:
self.children[0].dist += self.dist
elif len(parent.children) == 1 and 'dist' in parent.props:
parent.dist += self.dist
for ch in self.children:
parent.add_child(ch)
parent.remove_child(self)
if prevent_nondicotomic and len(parent.children) == 1:
parent.delete(prevent_nondicotomic=prevent_nondicotomic,
preserve_branch_length=preserve_branch_length)
def detach(self):
"""
Detachs this node (and all its descendants) from its parent
and returns the referent to itself.
Detached node conserves all its structure of descendants, and can
be attached to another node through the 'add_child' function. This
mechanism can be seen as a cut and paste.
"""
if self.up:
self.up.children.remove(self)
self.up = None
return self
def prune(self, nodes, preserve_branch_length=False):
"""Prune the topology conserving only the given nodes.
It will only retain the minimum number of nodes that conserve the
topological relationships among the requested nodes. The root node is
always conserved.
:param nodes: List of node names or objects that should be kept.
:param bool preserve_branch_length: If True, branch lengths
of the deleted nodes are transferred (summed up) to its
parent's branch, thus keeping original distances among nodes.
Examples::
t1 = Tree('(((((A,B)C)D,E)F,G)H,(I,J)K)root;', format=1)
t1.prune(['A', 'B'])
# /-A
# /D /C|
# /F| \-B
# | |
# /H| \-E
# | | /-A
#-root \-G -root
# | \-B
# | /-I
# \K|
# \-J
t1 = Tree('(((((A,B)C)D,E)F,G)H,(I,J)K)root;', format=1)
t1.prune(['A', 'B', 'C'])
# /-A
# /D /C|
# /F| \-B
# | |
# /H| \-E
# | | /-A
#-root \-G -root- C|
# | \-B
# | /-I
# \K|
# \-J
t1 = Tree('(((((A,B)C)D,E)F,G)H,(I,J)K)root;', format=1)
t1.prune(['A', 'B', 'I'])
# /-A
# /D /C|
# /F| \-B
# | |
# /H| \-E /-I
# | | -root
#-root \-G | /-A
# | \C|
# | /-I \-B
# \K|
# \-J
t1 = Tree('(((((A,B)C)D,E)F,G)H,(I,J)K)root;', format=1)
t1.prune(['A', 'B', 'F', 'H'])
# /-A
# /D /C|
# /F| \-B
# | |
# /H| \-E
# | | /-A
#-root \-G -root-H /F|
# | \-B
# | /-I
# \K|
# \-J
"""
def cmp_nodes(x, y):
# if several nodes are in the same path of two kept nodes,
# only one should be maintained. This prioritize internal
# nodes that are already in the to_keep list and then
# deeper nodes (closer to the leaves).
if n2depth[x] > n2depth[y]:
return -1
elif n2depth[x] < n2depth[y]:
return 1
else:
return 0
to_keep = set(self._translate_nodes(nodes))
start = self.common_ancestor(to_keep)
node2path = {n: n.lineage() for n in to_keep}
to_keep.add(self)
# Calculate which kept nodes are visiting the same nodes in
# their path to the common ancestor.
n2count = {}
n2depth = {}
for seed, path in node2path.items():
for visited_node in path:
if visited_node not in n2depth:
depth = visited_node.get_distance(visited_node, start,
topological=True)
n2depth[visited_node] = depth
if visited_node is not seed:
n2count.setdefault(visited_node, set()).add(seed)
# if several internal nodes are in the path of exactly the same kept
# nodes, only one (the deepest) should be maintain.
visitors2nodes = {}
for node, visitors in n2count.items():
# keep nodes connection at least two other nodes
if len(visitors)>1:
visitor_key = frozenset(visitors)
visitors2nodes.setdefault(visitor_key, set()).add(node)
for visitors, nodes in visitors2nodes.items():
if not (to_keep & nodes):
sorted_nodes = sorted(nodes, key=cmp_to_key(cmp_nodes))
to_keep.add(sorted_nodes[0])
for n in self.descendants('postorder'):
if n not in to_keep:
if preserve_branch_length:
if len(n.children) == 1:
n.children[0].dist += n.dist
elif len(n.children) > 1 and n.up:
n.up.dist += n.dist
n.delete(prevent_nondicotomic=False)
def swap_children(self):
"""Swap current children order (reversing it)."""
self.children.reverse()
# #####################
# Tree traversing
# #####################
def get_children(self):
"""Return an independent list of the node's children."""
return self.children.copy()
def get_sisters(self):
"""Return an independent list of sister nodes."""
if self.up is not None:
return [ch for ch in self.up.children if ch != self]
else:
return []
def leaves(self, is_leaf_fn=None):
"""Yield the terminal nodes (leaves) under this node."""
is_leaf = is_leaf_fn or (lambda n: n.is_leaf)
for node in self.traverse("preorder", is_leaf):
if is_leaf(node):
yield node
def leaf_names(self, is_leaf_fn=None):
"""Yield the leaf names under this node."""
for n in self.leaves(is_leaf_fn):
yield n.name
def descendants(self, strategy="levelorder", is_leaf_fn=None):
"""Yield all descendant nodes."""
for n in self.traverse(strategy, is_leaf_fn):
if n is not self:
yield n
def traverse(self, strategy="levelorder", is_leaf_fn=None):
"""Traverse the tree structure under this node and yield the nodes.
:param str strategy: Set the way in which tree
will be traversed. Possible values are: "preorder" (first
parent and then children) "postorder" (first children and
the parent) and "levelorder" (nodes are visited in order
from root to leaves).
:param function is_leaf_fn: Function used to interrogate nodes about if
they are terminal or internal. The function should
receive a node instance as first argument and return True
or False. Use this argument to traverse a tree by
dynamically collapsing internal nodes matching `is_leaf_fn`.
"""
if strategy == "preorder":
return self._iter_descendants_preorder(is_leaf_fn)
elif strategy == "levelorder":
return self._iter_descendants_levelorder(is_leaf_fn)
elif strategy == "postorder":
return self._iter_descendants_postorder(is_leaf_fn)
else:
raise TreeError("Unknown strategy: %s" % strategy)
def iter_prepostorder(self, is_leaf_fn=None):
"""Yield all nodes in a tree in both pre and post order.
Each iteration returns a postorder flag (True if node is being visited
in postorder) and a node instance.
"""
is_leaf_fn = is_leaf_fn or (lambda n: n.is_leaf)
to_visit = [self]
while to_visit:
node = to_visit.pop(-1)
if type(node) != list:
yield (False, node)
if not is_leaf_fn(node): # add children
to_visit.extend(reversed(node.children + [[1, node]]))
else: # postorder actions
node = node[1]
yield (True, node)
def _iter_descendants_postorder(self, is_leaf_fn=None):
"""Yield all nodes in a tree in postorder."""
is_leaf = is_leaf_fn or (lambda n: n.is_leaf)
to_visit = [self]
while to_visit:
node = to_visit.pop(-1)
if type(node) != list: # preorder actions
if not is_leaf(node): # add children
to_visit.extend(reversed(node.children + [[1, node]]))
else:
yield node
else: # postorder actions
node = node[1]
yield node
def _iter_descendants_levelorder(self, is_leaf_fn=None):
"""Yield all descendant nodes in levelorder."""
tovisit = deque([self])
while len(tovisit) > 0:
node = tovisit.popleft()
yield node
if not is_leaf_fn or not is_leaf_fn(node):
tovisit.extend(node.children)
def _iter_descendants_preorder(self, is_leaf_fn=None):
"""Yield all descendant nodes in preorder."""
to_visit = deque()
node = self
while node is not None:
yield node
if not is_leaf_fn or not is_leaf_fn(node):
to_visit.extendleft(reversed(node.children))
try:
node = to_visit.popleft()
except:
node = None
def ancestors(self, root=None):
"""Yield all ancestor nodes of this node (up to the root if given)."""
node = self
if node == root:
return # node is not an ancestor of itself
while node.up:
node = node.up
yield node
if node == root:
break # by now, we already yielded root too
if root is not None and node != root:
raise TreeError('node is no descendant from given root: %r' % root)
def lineage(self, root=None):
"""Yield all nodes in the lineage of this node (up to root if given)."""
# Same as ancestors() but also yielding itself first.
yield self
yield from self.ancestors(root)
def _translate_nodes(self, nodes):
"""Return a list of nodes that correspond to the given names or nodes."""
# ['A', self['B'], 'C'] -> [self['A'], self['B'], self['C']]
assert type(nodes) in [list, tuple, set, frozenset]
names = {n for n in nodes if type(n) == str}
if not names:
return list(nodes) # avoid traversing tree if no names to translate
name2node = {}
for node in self.traverse():
if node.name in names:
assert node.name not in name2node, f'Ambiguous node name: {node.name}'
name2node[node.name] = node
return [name2node[n] if type(n) == str else n for n in nodes]
def describe(self):
"""Return a string with information on this node and its connections."""
if len(self.root.children) == 2:
rooting = 'Yes'
elif len(self.root.children) > 2:
rooting = 'No'
else:
rooting = 'No children'
max_node, max_dist = self.get_farthest_leaf()
cached_content = self.get_cached_content()
return '\n'.join([
'Number of leaf nodes: %d' % len(cached_content[self]),
'Total number of nodes: %d' % len(cached_content),
'Rooted: %s' % rooting,
'Most distant node: %s' % (max_node.name or ''),
'Max. distance: %g' % max_dist])
def write(self, outfile=None, props=(), parser=None,
format_root_node=False, is_leaf_fn=None):
"""Return or write to file the newick representation.
:param str outfile: Name of the output file. If present, it will write
the newick to that file instad of returning it as a string.
:param list props: Properties to write for all nodes using the Extended
Newick Format. If None, write all available properties.
:param parser: Parser used to encode the tree in newick format.
:param bool format_root_node: If True, write content of the root node
too. For compatibility reasons, this is False by default.
Example::
t.write(props=['species', 'sci_name'])
"""
parser = newick.INT_PARSERS[parser] if type(parser) == int else parser
if not outfile:
return newick.dumps(self, props, parser, format_root_node, is_leaf_fn)
else:
with open(outfile, 'w') as fp:
newick.dump(self, fp, props, parser, format_root_node, is_leaf_fn)
def common_ancestor(self, nodes):
"""Return the last node common to the lineages of the given nodes.
All the nodes should have self as an ancestor, or an error is raised.
"""
if not nodes:
return None
nodes = self._translate_nodes(nodes)
curr = nodes[0] # current node being the last common ancestor
for node in nodes: # NOTE: not nodes[1:] in case self is no root of node[0]
lin_node = set(node.lineage(self))
curr = next((n for n in curr.lineage(self) if n in lin_node), None)
if curr is not None:
return curr # which is now the last common ancestor of all nodes
else:
raise TreeError(f'No common ancestor for nodes: {nodes}')
def search_nodes(self, **conditions):
"""Yield nodes matching the given conditions.
Example::
for node in tree.iter_search_nodes(dist=0.0, name="human"):
print(node.prop["support"])
"""
for n in self.traverse():
if all(n.props.get(key) == value or getattr(n, key, None) == value
for key, value in conditions.items()):
yield n
def get_leaves_by_name(self, name):
"""Return a list of leaf nodes matching the given name."""
return self.search_nodes(name=name, children=[])
# ###########################
# Distance related functions
# ###########################
def get_distance(self, node1, node2, topological=False):
"""Return the distance between the given nodes.
:param node1: A node within the same tree structure.
:param node2: Another node within the same tree structure.
:param topological: If True, distance will refer to the number of
nodes between target and target2.
"""
d = (lambda node: 1) if topological else (lambda node: node.dist)
node1, node2 = self._translate_nodes([node1, node2])
root = self.root.common_ancestor([node1, node2]) # common root
assert root is not None, 'nodes do not belong to the same tree'
return (sum(d(n) for n in node1.lineage(root)) - d(root) +
sum(d(n) for n in node2.lineage(root)) - d(root))
def get_farthest_node(self, topological=False):
"""Returns the farthest descendant or ancestor node, and its distance.
:param topological: If True, the distance between nodes will be the
number of nodes between them (instead of the sum of branch lenghts).
"""
# Init farthest node to current farthest leaf
farthest_node, farthest_dist = self.get_farthest_leaf(topological=topological)
dist = lambda node: node.dist if 'dist' in node.props else (0 if node.is_root else 1)
prev = self
cdist = 0.0 if topological else dist(prev)
current = prev.up
while current is not None:
for ch in current.children:
if ch != prev:
if not ch.is_leaf:
fnode, fdist = ch.get_farthest_leaf(topological=topological)
else:
fnode = ch
fdist = 0
if topological:
fdist += 1.0
else:
fdist += dist(ch)
if cdist+fdist > farthest_dist:
farthest_dist = cdist + fdist
farthest_node = fnode
prev = current
if topological:
cdist += 1
else:
cdist += dist(prev)
current = prev.up
return farthest_node, farthest_dist
def _get_farthest_and_closest_leaves(self, topological=False, is_leaf_fn=None):
# if called from a leaf node, no necessary to compute
if (is_leaf_fn and is_leaf_fn(self)) or self.is_leaf:
return self, 0.0, self, 0.0
dist = lambda node: node.dist if 'dist' in node.props else 1
min_dist = None
min_node = None
max_dist = None
max_node = None
d = 0.0
for post, n in self.iter_prepostorder(is_leaf_fn=is_leaf_fn):
if n is self:
continue
if post:
d -= dist(n) if not topological else 1.0
else:
if (is_leaf_fn and is_leaf_fn(n)) or n.is_leaf:
total_d = d + dist(n) if not topological else d
if min_dist is None or total_d < min_dist:
min_dist = total_d
min_node = n
if max_dist is None or total_d > max_dist:
max_dist = total_d
max_node = n
else:
d += dist(n) if not topological else 1.0
return min_node, min_dist, max_node, max_dist
def get_farthest_leaf(self, topological=False, is_leaf_fn=None):
"""Return the node's farthest descendant (a leaf), and its distance.
:param topological: If True, the distance between nodes will be the
number of nodes between them (instead of the sum of branch lenghts).
"""
min_node, min_dist, max_node, max_dist = \
self._get_farthest_and_closest_leaves(topological=topological,
is_leaf_fn=is_leaf_fn)
return max_node, max_dist
def get_closest_leaf(self, topological=False, is_leaf_fn=None):
"""Return the node's closest descendant leaf, and its distance.
:param topological: If True, the distance between nodes will be the
number of nodes between them (instead of the sum of branch lenghts).
"""
min_node, min_dist, max_node, max_dist = \
self._get_farthest_and_closest_leaves(topological=topological,
is_leaf_fn=is_leaf_fn)
return min_node, min_dist
def get_midpoint_outgroup(self, topological=False):
"""Return the node dividing into two distance-balanced partitions.
:param topological: If True, the distance between nodes will be the
number of nodes between them (instead of the sum of branch lenghts).
"""
# Start at the farthest leaf from the root.
current, _ = self.root.get_farthest_leaf(topological=topological)
_, diameter = current.get_farthest_node(topological=topological)
dist = 0
while current.up:
dist += 1 if topological else current.dist
if dist > diameter / 2:
return current
current = current.up