Skip to content

Commit

Permalink
Implement tree.ancestors
Browse files Browse the repository at this point in the history
Fixes #2706
  • Loading branch information
hyanwong committed Oct 16, 2024
1 parent 2fb6ab8 commit ba3004a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
17 changes: 17 additions & 0 deletions python/tests/test_highlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3822,6 +3822,23 @@ def test_num_children(self):
for u in tree.nodes():
assert tree.num_children(u) == len(tree.children(u))

def test_ancestors(self):
tree = tskit.Tree.generate_balanced(10, arity=3)
ancestors_arrays = {u: [] for u in np.arange(tree.tree_sequence.num_nodes)}
ancestors_arrays[-1] = []
for u in tree.nodes(order="preorder"):
parent = tree.parent(u)
if parent != tskit.NULL:
ancestors_arrays[u] = [parent] + ancestors_arrays[tree.parent(u)]
for u in tree.nodes():
assert list(tree.ancestors(u)) == ancestors_arrays[u]

def test_ancestors_empty(self):
ts = tskit.Tree.generate_comb(10).tree_sequence
tree = ts.delete_intervals([[0, 1]]).first()
for u in ts.samples():
assert len(list(tree.ancestors(u))) == 0

@pytest.mark.parametrize("ts", get_example_tree_sequences())
def test_virtual_root_semantics(self, ts):
for tree in ts.trees():
Expand Down
9 changes: 9 additions & 0 deletions python/tskit/trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,15 @@ def parent_array(self):
"""
return self._parent_array

def ancestors(self, u):
"""
Returns an iterator over the ancestors of node ``u`` in this tree.
"""
u = self.parent(u)
while u != -1:
yield u
u = self.parent(u)

# Quintuply linked tree structure.

def left_child(self, u):
Expand Down

0 comments on commit ba3004a

Please sign in to comment.