Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add order argument to ts.nodes() #2471

Merged
merged 1 commit into from
Sep 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions python/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
- ``ts.subset()`` produces valid tree sequences even if nodes are shuffled
out of time order (:user:`hyanwong`, :pr:`2479`, :issue:`2473`)

**Features**

- The ``ts.nodes`` method now takes an ``order`` parameter so that nodes
can be visited in time order (:user:`hyanwong`, :pr:`2471`, :issue:`2370`)

**Changes**

- Single statistics computed with ``TreeSequence.general_stat`` are now
Expand Down
23 changes: 23 additions & 0 deletions python/tests/test_highlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,8 @@ def make_example_tree_sequences():
)
tables = ts.dump_tables()
tables.populations.metadata_schema = tskit.MetadataSchema(None)
ts = tskit.Tree.generate_balanced(8).tree_sequence
yield ("rev node order", ts.subset(np.arange(ts.num_nodes - 1, -1, -1)))
ts = tables.tree_sequence()
assert ts.num_trees > 1
yield (
Expand Down Expand Up @@ -1441,6 +1443,27 @@ def verify_pairwise_diversity(self, ts):
def test_pairwise_diversity(self, ts):
self.verify_pairwise_diversity(ts)

@pytest.mark.parametrize("order", ["abc", 0, 1, False])
def test_bad_node_iteration_order(self, order):
ts = tskit.TableCollection(1).tree_sequence()
with pytest.raises(ValueError, match="order"):
ts.nodes(order=order)

@pytest.mark.parametrize("ts", get_example_tree_sequences())
def test_node_iteration_order(self, ts):
order = [n.id for n in ts.nodes()]
assert order == list(range(ts.num_nodes))
order = [n.id for n in ts.nodes(order="id")]
assert order == list(range(ts.num_nodes))
order = np.array([n.id for n in ts.nodes(order="timeasc")], dtype=int)
assert np.all(ts.nodes_time[order] == np.sort(ts.nodes_time))
# Check it conforms to the order of parents in the edge table
parent_only_order = order[np.isin(order, ts.edges_parent)]
edge_parents = np.concatenate(
(ts.edges_parent[:-1][np.diff(ts.edges_parent) != 0], ts.edges_parent[-1:])
)
assert np.all(parent_only_order == edge_parents)

def verify_edgesets(self, ts):
"""
Verifies that the edgesets we return are equivalent to the original edges.
Expand Down
30 changes: 26 additions & 4 deletions python/tskit/trees.py
Original file line number Diff line number Diff line change
Expand Up @@ -3800,10 +3800,16 @@ class SimpleContainerSequence:
Simple wrapper to allow arrays of SimpleContainers (e.g. edges, nodes) that have a
function allowing access by index (e.g. ts.edge(i), ts.node(i)) to be treated as a
python sequence, allowing forward and reverse iteration.

To generate a sequence of items in a different order, the ``order`` parameter allows
an array of indexes to be passed in, such as returned from np.argsort or np.lexsort.
"""

def __init__(self, getter, length):
self.getter = getter
def __init__(self, getter, length, order=None):
if order is None:
self.getter = getter
else:
self.getter = lambda index: getter(order[index])
self.length = length

def __len__(self):
Expand Down Expand Up @@ -4463,15 +4469,31 @@ def individuals(self):
"""
return SimpleContainerSequence(self.individual, self.num_individuals)

def nodes(self):
def nodes(self, *, order=None):
"""
Returns an iterable sequence of all the :ref:`nodes <sec_node_table_definition>`
in this tree sequence.

.. note:: Although node ids are commonly ordered by node time, this is not a
formal tree sequence requirement. If you wish to iterate over nodes in
time order, you should therefore use ``order="timeasc"`` (and wrap the
resulting sequence in the standard Python :func:`python:reversed` function
if you wish to iterate over older nodes before younger ones)

:param str order: The order in which the nodes should be returned: must be
one of "id" (default) or "timeasc" (ascending order of time, then by
ascending node id, matching the first two ordering requirements of
parent nodes in a :meth:`sorted <TableCollection.sort>` edge table).
:return: An iterable sequence of all nodes.
:rtype: Sequence(:class:`.Node`)
"""
return SimpleContainerSequence(self.node, self.num_nodes)
order = "id" if order is None else order
if order not in ["id", "timeasc"]:
raise ValueError('order must be "id" or "timeasc"')
odr = None
if order == "timeasc":
odr = np.lexsort((np.arange(self.num_nodes), self.nodes_time))
return SimpleContainerSequence(self.node, self.num_nodes, order=odr)

def edges(self):
"""
Expand Down