Last active
August 31, 2018 11:55
-
-
Save pchtsp/91612fa4bdc110cc2d97f1db9b27a9b3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ete3 | |
def get_node_pos(node): | |
if node.up is None: | |
return 0 | |
pos = node.up.children.index(node) | |
return pos | |
def post_traverse_from_node(node1, is_leaf_fn=None, node_end=None): | |
to_visit = [(node1, 0)] | |
pos = get_node_pos(node1) | |
pos += 1 | |
node1_ancestors = set(node1.get_ancestors() + [node1]) | |
if is_leaf_fn is not None: | |
_leaf = is_leaf_fn | |
else: | |
_leaf = node1.__class__.is_leaf | |
while to_visit: | |
node, pos = to_visit.pop(-1) | |
try: | |
node = node[1] | |
except TypeError: | |
# PREORDER ACTIONS | |
if node in node1_ancestors and node.up: | |
pos_new = get_node_pos(node) | |
to_visit.append((node.up, pos_new + 1)) | |
if not _leaf(node): | |
# ADD CHILDREN | |
nodes_to_add = node.children | |
if pos: | |
nodes_to_add = nodes_to_add[pos:] | |
to_visit.extend( | |
zip( | |
reversed(node.children + [[1, node]]), | |
np.zeros(len(nodes_to_add) + 1) | |
) | |
) | |
else: | |
yield node | |
else: | |
#POSTORDER ACTIONS | |
yield node | |
if node_end and node == node_end: | |
break | |
if __name__ == "__main__": | |
t = ete3.Tree('(((a,b)I1, (c,d)I2)I3, (e,(f,g)I4)I5);', format=1) | |
node1 = t&"a" | |
node_end = t&"f" | |
ancestors = set(node1.get_ancestors()) | set(node_end.get_ancestors()) | |
def is_leaf_fn(node2): | |
return node2 not in ancestors | |
result_list = [n for n in post_traverse_from_node(node1, is_leaf_fn=is_leaf_fn, node_end=node_end)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment