Skip to content

Replace mean_descendants with a node stat - #328

Closed
jeromekelleher wants to merge 6 commits into
tskit-dev:mainfrom
jeromekelleher:mean_descendants_node
Closed

jeromekelleher wants to merge 6 commits into
tskit-dev:mainfrom
jeromekelleher:mean_descendants_node

Conversation

@jeromekelleher

Copy link
Copy Markdown
Member

Closes #273

(I had to base this off #313, so ignore everything except the last commit here in the initial version)

I had a go at this @petrelharp, and managed to duplicate the original code using node stats and numpy operations, but I had to introduce two strict-failing summary functions to do it. It's not totally trivial to do, I think, and we'll end up having to do some of the work in C at least I think (by the time we'd have defined the operations in C we'd have done most of the work). So, this needs to be updated to follow the pattern of the rest of the API and do/not do the funky normalising it's got at the moment.

Given that there's a bit of work to do here, I suggest we push this out to beyond 0.2.0 and maybe put a bigger warning on the documentation stating that this really is preliminary and we reserve the right to change it any way we feel like.

@jeromekelleher

Copy link
Copy Markdown
Member Author

There's a few changes that I'll need to backport to #313 also --- turns out we weren't handling dimensions in the general stats properly.

Comment thread python/tskit/trees.py Resolved
Comment thread python/tskit/trees.py Outdated
C *= tree_span

# To replicate the existing code, take the mean weighted by node span.
C = np.sum(C, axis=0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the following does the same thing without having to do the windows="trees" stuff yourself:

denom = self.sample_count_stat(
            [self.samples()], lambda x: x > 0, output_dim=1, polarised=True,
            strict=False, mode="node", span_normalise=False)
numer = self.sample_count_stat(
        reference_sets, lambda x: x, output_dim=len(reference_sets), polarised=True, span_normalise=False,
        strict=False, mode="node")
C = numer / denom

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sort of normalization by denom is a pretty common node statistic operation that we should maybe even define as an option to those methods.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or maybe (as we had said on this topic before) just provide a method that gives us the denominator. As a site statistic this'd give the number of segregating-or-fixed sites, and as a branch statistic would give us the total tree length plus any branches above the MRCA. So maybe it should be an option to segregating_sites, say, include_fixed=False.

@petrelharp

Copy link
Copy Markdown
Contributor

I've got this a good ways towards being a normal node statistic. There's some API questions here, ping @hyanwong and @gtsambos:

  1. Do we want to allow computation of the branch and site versions? For instance, the site version would ask for the mean allele frequency among each of the sample sets across derived alleles found in all samples. (This seems interesting, so yes?)

  2. Should we rename reference_sets to sample_sets (I think yes, if the answer to (1) is yes).

  3. Should we rename this based on the "site" version, like the other statistics? It could be "mean_segregating_frequency"?

This is somewhat in a different class than previous statistics because of the normalisation, but after talking it through, it's not feeling very different.

@petrelharp

Copy link
Copy Markdown
Contributor

Oh, and: I'm ok leaving this until after 0.2.0.

Comment thread python/tests/test_tree_stats.py Outdated
yield [[s] for s in samples]
if min_size == 1:
yield [samples[:1]]
if ts.num_samples <= 2 and min_size >= 2:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realized that this was never getting called.

Comment thread python/tests/test_tree_stats.py Outdated
# Determine output_dim of the function
M = len(f(W[0]))
py_ssc = PythonSiteStatCalculator(ts)
sigma1 = py_ssc.naive_general_stat(W, f, windows, polarised=polarised)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removing some cruft

Comment thread python/tests/test_tree_stats.py Outdated
def setUp(self):
self.rng = random.Random(self.random_seed)
self.stat_type = "branch"
self.py_stat_class = PythonBranchStatCalculator

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only place this was mentioned; unused.

Comment thread python/tests/test_tree_stats.py Outdated
# specific calculattors. These definititions have been
# move to stat-specific regions above
# The only thing left to port is the SFS code.
############################################

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can get rid of this, yay!

Comment thread python/tests/test_tree_stats.py Outdated
return out
def verify(self, ts, reference_sets, windows=None):
C1 = mean_descendants(ts, reference_sets, mode=self.mode, windows=windows)
# C2 = tsutil.mean_descendants(ts, reference_sets, windows=windows)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to compare to the tsutil version we need to make that one windowed as well

@petrelharp

petrelharp commented Aug 22, 2019 •

Copy link
Copy Markdown
Contributor

Gah; I found a "why did this ever work" error in the naive, test-only versions of two of the statistics, uncaught previously because we weren't looking at very many sample sets. Fixed now, but I'll pull those changes off into another PR. First I'm adding a "shuffle" to the samples in example_sample_sets and running on all combinations to be paranoid.

@codecov

codecov Bot commented Aug 22, 2019 •

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 86.48%. Comparing base (67a8335) to head (38bad3e).
Report is 2246 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #328      +/-   ##
==========================================
+ Coverage   86.47%   86.48%   +0.01%     
==========================================
  Files          20       20              
  Lines       14035    14048      +13     
  Branches     2751     2751              
==========================================
+ Hits        12137    12150      +13     
  Misses        979      979              
  Partials      919      919              
Flag Coverage Δ
c_tests 87.57% <100.00%> (+0.01%) ⬆️
python_c_tests 90.32% <100.00%> (+0.01%) ⬆️
python_tests 99.24% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
python/tskit/trees.py 98.68% <100.00%> (+0.01%) ⬆️

This was referenced Aug 23, 2019
@petrelharp

Copy link
Copy Markdown
Contributor

I don't think we need to get this all sorted for 0.2.0, but if we're going to rename reference_sets to sample_sets, that'd be nice to do first, and that seems like an easy decision. (I vote yes.)

Comment thread python/tskit/trees.py
out_slice = tuple([slice(None)] * (len(C.shape) - 1) + [slice(0, -1)])
denom_slice = tuple([slice(None)] * (len(C.shape) - 1) + [-1])
out = C[out_slice]
denom = C[denom_slice].reshape(list(C.shape[:-1]) + [1])

@petrelharp petrelharp Aug 23, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This implementation is more opaque than the previous implementation but is closer to how we'd do it in C (and more efficient).

@jeromekelleher

Copy link
Copy Markdown
Member Author

I don't think we need to get this all sorted for 0.2.0, but if we're going to rename reference_sets to sample_sets, that'd be nice to do first, and that seems like an easy decision. (I vote yes.)

OK, great. Agreed on renaming to sample_sets, I'll get that in for 0.2.0.

@hyanwong

Copy link
Copy Markdown
Member

Agreed on renaming to sample_sets

Just to check for this renaming: I'm assuming that we are never going to want to define sets that include non-sample nodes?

For example, there's Gil's idea of anonymising data by using the inferred ancestors as data points, rather than using the samples themselves. But it may be that this is done by redefining them as samples (especially now that we can have samples which are not complete sequences)

@jeromekelleher

Copy link
Copy Markdown
Member Author

Just to check for this renaming: I'm assuming that we are never going to want to define sets that include non-sample nodes?

We might do I guess, but I think it's OK to have this slight inconsistency in favour of greater consistency across the various stats functions. We already allow for non-sample 'samples' in the samples argument to the variants method, so it's not without precedent.

In either case, it's the first positional parameter so the name isn't totally critical.

@jeromekelleher

Copy link
Copy Markdown
Member Author

OK, so the decision is to bring this stat up to date to make it more like the other general stats. This means that the API we're shipping in 0.2.0 for this function isn't going to be stable, but that's OK because we'll clearly document it as experimental.

I'll update this PR once the dust has settled a bit so it's a cleaner diff.

@gtsambos

Copy link
Copy Markdown
Member

fyi everyone: as this is my last day in Oxford I've been busy wrapping up some other things, so haven't had time to think about this properly yet - but I will soon!

@jeromekelleher

Copy link
Copy Markdown
Member Author

I've brought this up to date @petrelharp. We've reproduced the old behaviour successfully, but we want to have options for normalising by how long the node was in trees for. How would you like to proceed with this (possibly something it'd be better to talk over?)

@jeromekelleher

Copy link
Copy Markdown
Member Author

@awohns, you're the main user of mean_descendents at the moment. Can you comment on what normalisation options you'd like to see please?

@awohns

awohns commented Aug 28, 2019 via email •

Copy link
Copy Markdown
Member

@jeromekelleher

Copy link
Copy Markdown
Member Author

In addition to length of genome (which is default), normalising by the size of the reference sets is the only option that comes to mind at the moment.

Do you always want to normalise by the length of genome? I've gone round in circles in this one.

@awohns

awohns commented Aug 28, 2019

Copy link
Copy Markdown
Member

Just reread the various threads on this. I agree with @petrelharp in #273, normalising by the span which the node is an ancestor to any sample should be an option, I think there are cases where you would want to normalise (for instance, if you're solely interested in which samples copy from an individual ancestor) and cases were you wouldn't (if you're comparing the relative contribution of a number of ancestors to the samples).

@benjeffery
benjeffery changed the base branch from master to main September 28, 2020 12:12
@benjeffery

Copy link
Copy Markdown
Member

@petrelharp is this still a desirable feature?

@jeromekelleher

Copy link
Copy Markdown
Member Author

(Basically I can't remember why I did this now, so happy to close unless someone else would like to have it in)

@petrelharp

Copy link
Copy Markdown
Contributor

This seems like a nice thing to do in terms of (a) making it more obvious what's going on with mean_descendants, (b) removing a bunch of code (since now mean_descendants would just use the general stat interface), and (c) making the interface consistent ("sample_sets"). However, it probably doesn't change much in practice, so it is not high priority. (Unless someone's come up with a use case for the branch or site mode stats here?)

@jeromekelleher

Copy link
Copy Markdown
Member Author

I agree, let's close. We can always reopen and pick up again later if someone really wants this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

implement mean_descendants as a node statistic

6 participants