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
An operation that came up as being a useful feature in the recent PopSim meeting is to be able to count the number of extant lineages in each tree at a given time. This is equivalent to (a) deleting all edges older than t and truncating all edges intersecting with it (this would require the planned time argument to delete_interval in #382); and (b) counting the number of roots in each tree. We could define the operation by just doing this, but it seems a bit inefficient, especially if we do this for lots of different times.
We can code this up pretty efficiently in C, and return the numpy array. Should we do it this way? Should we call the method TreeSequence.num_roots(time=None), which returns a numpy array like the above? (If time is None, it defaults to the oldest time in the ts)
We definately want to do this, somehow! Note that another way to do it would be to remove everything belowt and count the number of tips.
And gee, your algorithm is very nice. num_roots is a good name; but it might be nice to connote somehow the fact that these aren't actually roots in the trees unless time=None, maybe num_lineages_at( ) or num_roots_at( )?
p.s. Asking about number of lineages in the trees irregardless of whether they are above samples is even easier. Here is, for instance, a function that I think tells you how many lineages there are in the tree at position pos at time t:
def num_lineages(ts, pos, t):
left = ts.tables.edges.left
right = ts.tables.edges.right
a = ts.tables.nodes.time[ts.tables.edges.parent]
b = ts.tables.nodes.times[ts.tables.edges.child]
return np.sum((left <= pos) * (right > pos) * (a < t) * (b >= t))
Very nice @petrelharp, that's another great way to look at it. It does assume that the trees have one root though (what happens in the degenerate case of no edges?). The algorithm I have above isn't complete either though, I think I'm assuming that all leaves are samples at the moment (but, I'm sure that can be fixed).
I agree num_roots will confuse people, so num_lineages is a better choice. I'm not crazy about the _at suffix though --- isn't that a bit like putting a _where at the end of a bunch of other methods that query stuff?
Resurrecting this one - @petrelharp, does this do what we need for the Relate selection stat? It's probably something we should just stick in, since we know how to do it. TreeSequence.num_lineages(time), where time is a mandatory positional argument seems like a good option?
defnum_lineages(time):
""" Returns the number of lineages ancestral to samples in each tree along the genome at the specified time. """
It's not the only way that we'll want to use this type of information, but it's a useful operation to add to the suite I think?
I suppose we should add a Tree.num_lineages(time) operation as well, which computes the same thing. This would probably need to do a top-down traversal of some sort I guess (but we could imagine adding some options to make it faster).
Ah, what we really want to do here is to return the number of lineages at a vector of time points. So, we'd have something like
defnum_lineages(self, time, windows=None):
""" Returns the number of lineages ancestral to samples in each tree along the genome at the specified time points. The windows parameter is interpreted in a same way as for the stats API. The returned value is a (num_windows, num_times) array, where dimensions are dropped in the same ways as the stats API, when defaults are used. """
(This wouldn't be the real docstring, just a sketch)
One application would be to make a genome x time plot of number of lineages (This would be like the genome x time plot of branch-segregating-sites if we had time windows in for statistics.)
To compute the Relate selection statistic or the number of coalescences we need "number of lineages" information, but in the particular tree that the mutation appears in, not averaged across a window; so although this is related it's not exactly what we need for those, I think?
defnum_tree_lineages_simple(tree, t):
lineages=0foruintree.nodes():
iftree.time(u) <=t<tree.time(tree.parent(u)):
lineages+=1returnlineagesdefnum_tree_lineages_preorder(tree, t):
# Only descend the tree as far as we need to.lineages=0stack= [tree.virtual_root]
whilelen(stack) >0:
parent=stack.pop()
forchildintree.children(parent):
child_time=tree.time(child)
ifchild_time>t:
stack.append(child)
elifchild_time<=t:
lineages+=1returnlineagesdefnum_tree_lineages_vector_simple(tree, t):
""" Return a vector N counting the number of lineages present at each time in the specified vector t. """t=np.array(t)
k=t.shape[0]
N=np.zeros(k, dtype=int)
foruintree.nodes():
forjinrange(k):
iftree.time(u) <=t[j] <tree.time(tree.parent(u)):
N[j] +=1returnN
Notes:
This code isn't very robust as it's not taking into account what happens when we specify a time that's greater than the root(s) time. We'll currently get an error.
We should be able to do a version with the vector of input times where we use the traversal stack to index into the time array. I think this is probably the most efficient way that it can be done, for a single tree. We'd required that the input vector of times is sorted in nondecreasing order, and then push (tree.virtual_root, len(t) - 1) on as the first element of the stack, like so
defnum_tree_lineages_vector_stack(tree, t):
""" Return a vector N counting the number of lineages present at each time in the specified vector t. """t=np.array(t)
k=t.shape[0]
N=np.zeros(k, dtype=int)
stack= [(tree.virtual_root, k-1)]
whilelen(stack) >0:
parent, j=stack.pop()
forchildintree.children(parent):
child_time=tree.time(child)
ifchild_time>t[j]:
stack.append((child, j)) # This is probably right?else:
# do the thingsreturnN
It's probably best to get a fully working version of the tree method before we start thinking about how to make this work across many trees.
@a-ignatieva would you mind taking a quick look at these functions in the comment just above to see if they do what you want? I'm trying to figure out what we want here in terms of implementing this operation as efficiently as we can.
Here's a note spurred on by #1314. I think there are two general things we want to do:
Make a plot of "number of extant lineages through time". We could do that by taking the average number of lineages across a time window and across a window of the genome, which would be what we get by adding time windows to segregating_sites.
Compute things that require knowing the number of extant lineages at a bunch of specific places on the genome and times (e.g., at all the mutations, for the Relate statistic). So, this requires knowing how to keep track of that sort of information, but isn't necessarily part of the python API, as we'd do those things in C. But, now that I think about it, maybe adding the ability to the .trees( ) operator to be able to return that sort of information would be the way to go? Or, I suppose that your code above, @jeromekelleher, is proposing a method of the Tree object that does this?
Things that I can think of that fall in the second category are:
Thanks @petrelharp, that does clarify things. I think it's worth having the method to return the number of lineages at a set of times as part of the Python API anyway, even if it's just something we use as a building block later for testing things like the Relate statistic.
We can build other methods up from there once this basic building block is in place I think (even if they don't use it, under the hood).
@jeromekelleher this looks good to me, but just to point out: for the Relate test specifically, for mutation m we want the number of lineage just below m.node (not the number of lineages at m.time). So if we want to compute the p-value for each mutation in a tree we would use the functions above with the time vector being [t.time(m.node) for m in t.mutations()] I guess.
for the Relate test specifically, for mutation m we want the number of lineage just below m.node (not the number of lineages at m.time)
Oh, good point - but, arguably the Relate test would be better if we used the number of lineages at the time the mutation arose rather than the time of the next node; however, we can't really know what that time was, so "next node time" is a good choice.
Yeah it makes sense - the test is basically conditioning on the mutation having frequency at least 2 (and thus takes the number of lineages at the time just below the first split).
Activity
petrelharp commentedon Oct 16, 2019
We definately want to do this, somehow! Note that another way to do it would be to remove everything below
tand count the number of tips.And gee, your algorithm is very nice.
num_rootsis a good name; but it might be nice to connote somehow the fact that these aren't actually roots in the trees unlesstime=None, maybenum_lineages_at( )ornum_roots_at( )?p.s. Asking about number of lineages in the trees irregardless of whether they are above samples is even easier. Here is, for instance, a function that I think tells you how many lineages there are in the tree at position
posat timet:jeromekelleher commentedon Oct 16, 2019
Very nice @petrelharp, that's another great way to look at it. It does assume that the trees have one root though (what happens in the degenerate case of no edges?). The algorithm I have above isn't complete either though, I think I'm assuming that all leaves are samples at the moment (but, I'm sure that can be fixed).
I agree
num_rootswill confuse people, sonum_lineagesis a better choice. I'm not crazy about the_atsuffix though --- isn't that a bit like putting a_whereat the end of a bunch of other methods that query stuff?jeromekelleher commentedon Mar 29, 2022
Resurrecting this one - @petrelharp, does this do what we need for the Relate selection stat? It's probably something we should just stick in, since we know how to do it.
TreeSequence.num_lineages(time), where time is a mandatory positional argument seems like a good option?It's not the only way that we'll want to use this type of information, but it's a useful operation to add to the suite I think?
jeromekelleher commentedon Mar 29, 2022
I suppose we should add a
Tree.num_lineages(time)operation as well, which computes the same thing. This would probably need to do a top-down traversal of some sort I guess (but we could imagine adding some options to make it faster).jeromekelleher commentedon Mar 30, 2022
Ah, what we really want to do here is to return the number of lineages at a vector of time points. So, we'd have something like
(This wouldn't be the real docstring, just a sketch)
What do you think @petrelharp?
I think we want to sample the number of lineages at specific times rather than to average them out in windows.
cc @percyfal
petrelharp commentedon Mar 30, 2022
I like it! Very nice, clean.
Do you remember what the original motivation was?
One application would be to make a genome x time plot of number of lineages (This would be like the genome x time plot of branch-segregating-sites if we had time windows in for statistics.)
To compute the Relate selection statistic or the number of coalescences we need "number of lineages" information, but in the particular tree that the mutation appears in, not averaged across a window; so although this is related it's not exactly what we need for those, I think?
jeromekelleher commentedon Apr 4, 2022
Here's some doodling for tree versions:
Notes:
(tree.virtual_root, len(t) - 1)on as the first element of the stack, like soIt's probably best to get a fully working version of the tree method before we start thinking about how to make this work across many trees.
jeromekelleher commentedon Apr 7, 2022
@a-ignatieva would you mind taking a quick look at these functions in the comment just above to see if they do what you want? I'm trying to figure out what we want here in terms of implementing this operation as efficiently as we can.
petrelharp commentedon Apr 7, 2022
Here's a note spurred on by #1314. I think there are two general things we want to do:
Make a plot of "number of extant lineages through time". We could do that by taking the average number of lineages across a time window and across a window of the genome, which would be what we get by adding time windows to
segregating_sites.Compute things that require knowing the number of extant lineages at a bunch of specific places on the genome and times (e.g., at all the mutations, for the Relate statistic). So, this requires knowing how to keep track of that sort of information, but isn't necessarily part of the python API, as we'd do those things in C. But, now that I think about it, maybe adding the ability to the
.trees( )operator to be able to return that sort of information would be the way to go? Or, I suppose that your code above, @jeromekelleher, is proposing a method of the Tree object that does this?Things that I can think of that fall in the second category are:
jeromekelleher commentedon Apr 7, 2022
Thanks @petrelharp, that does clarify things. I think it's worth having the method to return the number of lineages at a set of times as part of the Python API anyway, even if it's just something we use as a building block later for testing things like the Relate statistic.
We can build other methods up from there once this basic building block is in place I think (even if they don't use it, under the hood).
petrelharp commentedon Apr 7, 2022
Sounds perfect.
a-ignatieva commentedon Apr 7, 2022
@jeromekelleher this looks good to me, but just to point out: for the Relate test specifically, for mutation
mwe want the number of lineage just belowm.node(not the number of lineages atm.time). So if we want to compute the p-value for each mutation in a tree we would use the functions above with the time vector being[t.time(m.node) for m in t.mutations()]I guess.petrelharp commentedon Apr 7, 2022
Oh, good point - but, arguably the Relate test would be better if we used the number of lineages at the time the mutation arose rather than the time of the next node; however, we can't really know what that time was, so "next node time" is a good choice.
a-ignatieva commentedon Apr 7, 2022
Yeah it makes sense - the test is basically conditioning on the mutation having frequency at least 2 (and thus takes the number of lineages at the time just below the first split).
Implement Tree.num_lineages
Implement Tree.num_lineages
Implement Tree.num_lineages
Implement Tree.num_lineages