You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
It is sometimes useful to iterate over nodes in the tree in 'time' order, where we guarantee that the time of each node visited is >= the time of the previous one. Add this to the options in the order argument.
Thought I'd spend an evening looking at this to see what it's like working with the codebase and as it had some friendly labels! I've implemented your trivial implementation above and an additional one using a priority queue from the heapq module. Code at benjeffery@5feba1b
To make it a fairer comparison between the methods, the order of traversal is the reverse of the one specified as this lets the priority queue method start at the root. Maybe there is a use case I am unaware of that strongly motivates the original order, but (unless sample_lists=True) you'd have to first traverse to get the leaves then work backwards.
But do we need to? The trivial method is faster than some of the existing methods, about a ~70-80% perf hit compared to levelorder and uses num_nodes * 2 * 8bytes of additional memory to do the sort.
Anyway, that's how far I got for now, happy to document and then make a PR if needed.
This is great, thanks @benjeffery! We should definitely work this up as a PR.
I forget what the original motivation for having this ordering is, but I think it was from an application where we needed the nodes time-increasing order. Think of it as a stronger form of postorder. I can't really see what one would use time descending down the tree for (but, perhaps we should consider the names so that both are possible?).
Performance-wise, you're right, it looks like there's no point in doing much beyond the trivial method since it's already so fast. But, this is fun, and you've gone to the trouble of putting the harness together so let's explore!
Going leaf-up is possible doing something like this:
heap= []
foruintree.tree_sequence.samples():
heapq.heappush((u, tree.time(u))
# Basically same as your algorithm from here
Would this be any faster? There's a subtle difference here though, that we'd only visit nodes that are reachable from samples, and so in some weirdo corner cases this traversal would not reach the same set of nodes as other top-down ones.
I'm also amazed that preorder is slower than level order: preorder should be super-simple and fast. I wonder if using the low-level operations directly would make this quicker (see here for documentation on the underlying tree structures). E.g.,
I've looked a little into the performance of preorder vs levelorder. I'll checkout the "leaves up" idea another day.
Here's the current time taken for both (100 trees, n=50000):
preorder: 19.56s
levelorder: 17.43s
Both have an unneeded call to is_internal before they add their children to the queue/stack. (is_internal calls is_leaf which just does len(self.children(u)) == 0)
Removing this saves 4 python function calls and a call to Tree_get_children in both methods:
preorder: 14.20s
levelorder: 9.86s
levelorder is using a deque, changing preorder to use one too:
preorder: 11.09s
levelorder: 9.75s (change is just noise)
At this point the only difference between the methods is pop vs popleft and an extra call to reversed for preorder. Removing this call makes them take the same time (also reassuringly breaks the tests!) so levelorder still reigns supreme!
I then removed all . usage in the tight loop:
preorder: 9.54s
levelorder: 8.05s
I then tried your more low-level code, with the same tweaks, but the best I could get was:
preorder: 11.69s
Which I think makes sense as there's quite few more python function calls per loop.
If these functions are really perf sensitive they could be pushed to the C layer, as you can return an iterator from C. I also haven't looked at optimising any C code.
Here's the code of my final fastest versions:
def _preorder_traversal(self, u):
stack = collections.deque([u])
#For perf we store these to avoid lookups
pop = stack.pop
ext = stack.extend
children = self.children
while stack:
v = pop()
ext(reversed(children(v)))
yield v
def _levelorder_traversal(self, u):
queue = collections.deque([u])
#For perf we store these to avoid lookups
pop = queue.popleft
ext = queue.extend
children = self.children
while queue:
v = pop()
ext(children(v))
yield v
If I find time I'll give the other traversal methods the same treatment and do a separate PR.
Very cool, thanks @benjeffery! We should try to make these methods as fast as we reasonably can, since they are basic building blocks.
It might be worth implementing preorder in C as it's the default if there's a significant perf gain, but it's probably pretty marginal --- as soon as anyone starts doing anything with the nodes we're generating then the client side processing will surely dominate the time we're spending.
Activity
jeromekelleher commentedon Jun 24, 2019
This is trivial to do:
the trick is to do it efficiently.
benjeffery commentedon Oct 24, 2019
Thought I'd spend an evening looking at this to see what it's like working with the codebase and as it had some friendly labels! I've implemented your trivial implementation above and an additional one using a priority queue from the
heapqmodule. Code at benjeffery@5feba1bTo make it a fairer comparison between the methods, the order of traversal is the reverse of the one specified as this lets the priority queue method start at the root. Maybe there is a use case I am unaware of that strongly motivates the original order, but (unless
sample_lists=True) you'd have to first traverse to get the leaves then work backwards.I generated some trees to traverse with

msprime.simulate(n)and then traversed over the first 20 trees.Code for the plot at https://gist.github.com/benjeffery/8c06f75effdc020b09a7ae0e2ab99246
So the priority queue method is pretty slow - this is due to it not being quite the right algorithm as we are not taking advantage of the fact that we only have need for a monotonic priority queue. In this case to doing something like a radix heap (e.g. https://github.com/iwiwi/radix-heap) would be better, but I couldn't find anything to quickly drop into python.
But do we need to? The trivial method is faster than some of the existing methods, about a ~70-80% perf hit compared to
levelorderand usesnum_nodes * 2 * 8bytesof additional memory to do the sort.Anyway, that's how far I got for now, happy to document and then make a PR if needed.
jeromekelleher commentedon Oct 25, 2019
This is great, thanks @benjeffery! We should definitely work this up as a PR.
I forget what the original motivation for having this ordering is, but I think it was from an application where we needed the nodes time-increasing order. Think of it as a stronger form of postorder. I can't really see what one would use time descending down the tree for (but, perhaps we should consider the names so that both are possible?).
Performance-wise, you're right, it looks like there's no point in doing much beyond the trivial method since it's already so fast. But, this is fun, and you've gone to the trouble of putting the harness together so let's explore!
Going leaf-up is possible doing something like this:
Would this be any faster? There's a subtle difference here though, that we'd only visit nodes that are reachable from samples, and so in some weirdo corner cases this traversal would not reach the same set of nodes as other top-down ones.
I'm also amazed that preorder is slower than level order: preorder should be super-simple and fast. I wonder if using the low-level operations directly would make this quicker (see here for documentation on the underlying tree structures). E.g.,
benjeffery commentedon Oct 27, 2019
I've looked a little into the performance of
preordervslevelorder. I'll checkout the "leaves up" idea another day.Here's the current time taken for both (100 trees, n=50000):
Both have an unneeded call to
is_internalbefore they add their children to the queue/stack. (is_internalcallsis_leafwhich just doeslen(self.children(u)) == 0)Removing this saves 4 python function calls and a call to
Tree_get_childrenin both methods:levelorderis using adeque, changingpreorderto use one too:At this point the only difference between the methods is
popvspopleftand an extra call toreversedforpreorder. Removing this call makes them take the same time (also reassuringly breaks the tests!) solevelorderstill reigns supreme!I then removed all
.usage in the tight loop:I then tried your more low-level code, with the same tweaks, but the best I could get was:
Which I think makes sense as there's quite few more python function calls per loop.
If these functions are really perf sensitive they could be pushed to the C layer, as you can return an iterator from C. I also haven't looked at optimising any C code.
Here's the code of my final fastest versions:
If I find time I'll give the other traversal methods the same treatment and do a separate PR.
jeromekelleher commentedon Oct 28, 2019
Very cool, thanks @benjeffery! We should try to make these methods as fast as we reasonably can, since they are basic building blocks.
It might be worth implementing preorder in C as it's the default if there's a significant perf gain, but it's probably pretty marginal --- as soon as anyone starts doing anything with the nodes we're generating then the client side processing will surely dominate the time we're spending.
jeromekelleher commentedon Nov 22, 2019
Closed in #399 and #400