Repository navigation
Compare msprime against seq-gen #1018 - #1032
Conversation
e861412 to
7c430ac
Compare
|
This is great, thanks @GertjanBisschop! The main thing you need to do to keep the CI services happy is to let Black format your code. The tskit docs explain the setup and how to use pre-commit to set things up for you. Can you paste in an example of the plots here? How sensitive do you think these statistics are to picking up problems? Say if we change the mutation rate a small bit, or use a slightly different mutation model, how well would they pick these things up? Are there other sequence comparison stats we could include? |
|
Excellent! Wrt to the sensitivity, an easy check to try now would be to specify the wrong model for Seq-Gen and see if we do pick that up. That's a good point about hitting the same base - maybe we should do this for three different sequence lengths (say, 10, 100, 1000) so we should get absurdly many mutations per site on one extreme, and often just one mutation per site at another. |
|
Gee, this is very nice. What's your plan for counting mutations by state? Ideally, we'd compare things by ancestral/derived state, eg theta for A to T mutations, etc? |
|
@petrelharp Yes! I've been thinking about that today. As well as getting out the actual sample sequences I can also retrieve the ancestral sequence with Seq-Gen. We can even get the sequences for all internal nodes. The same is true for variants simulated with msprime. I guess there are two possibilities here then. Either we use all information (= the sequences at the internal nodes) and determine the rate of transitions, explicitely taking into account the possibility of multiple hits on the same sites. Or we only compare ancestral sequences to the sequences at the tips. If the mutation rate is not particularly high then this won't be all that different from the first possibility. And this involves less parsing and bookkeeping I guess. Secondly, in mutations.py, alleles are listed as alleles = ["A", "C", "T", "G"] but there is also a remark stating '#ACGT order'. Does the transition matrix assume a particular order (being ACGT ) or does the order depend on the order in the alleles list? |
I'm guessing this is a typo, and we should have the alleles in ACGT order. The ordering matters all right, i.e., transition_matrix[0, 1] is the rate of mutation from |
|
Well, maybe the easiest way to compare is with a chi-squared test for the table of (ancestral, derived) states across all the branches. This'll make it easy to compare to the theoretical expectation as well, computed from the matrix exponential of the mutation rate matrix. I thought about this sort of thing in these statistical tests. How's that sound? |
|
Thanks, I didn't realize this was implemented. Wonderful. So we can compare against theoretical expectations. As well as implement a similar comparison to Seq-Gen. (I think we are (almost) on the same page now). |
Sorry, I thought you knew about that. |
|
My bad @GertjanBisschop, @petrelharp, I should have pointed out the existing stats tests to Gertjan (although, independence of these tests and the statistical checks is nice). I'd rather keep the verification tests to visual plots rather than test/fail status too. BTW, if you need a matrix exponential function @GertjanBisschop, we have one in the demography module. |
|
I have been testing both the Jukes-Cantor as well as the HKY model. So we're making progress. I have been using some of @petrelharp 's code to parse trough the mutations of of each simulated tree. The transition matrix built in this way is more accurate then the one I can make from the seq-gen generated sequences as I can't telll whether more than one mutation has occurred on a particular site along a branch connecting two nodes. This is a qqplot for the sum of chisquare statistics for each matrix row, for the HKY model for a transition to transversion ratio of 1. Note the outlier, to get rid of that I will reconstruct the sequences at the interal nodes such that everything is perfectly comparable with the seq-gen implementation. This means 'collapsing' mutations on top of each other, so ignoring all mutations happening between the state of the parent node and the derived state of the next node. I don't think any code exists to do that, right? Also, thank god for well-document software. I spent quite some time trying to figure out in what order Seq-Gen returns sequences for internal nodes. |
|
Gee, this would be easier if we had a method to get genotypes at internal nodes, https://GitHub.com/tskit-dev/tskit/issues/605 |
We can do this now: ts = msprime.simulate(5, mutation_rate=0.5, random_seed=2)
for var in ts.variants(
samples=np.arange(ts.num_nodes).astype(np.int32),
impute_missing_data=True):
print(var.genotypes)Here |
|
I have run quite a few checks now, most come up as expected. However when testing Secondly, the tests that are in place check whether all row sums of the transition matrix equal one. However, do to floating point precision this is sometimes not the case. What can I do to overcome this (or is it just a case of adapting the test to @jeromekelleher I have now done the pre-commit checks, all passed but I still see three tests have failed. I will check how I can fix this. |
I think using |
|
|
||
| def __init__(self): | ||
| alleles = [b"A", b"C", b"T", b"G"] | ||
| alleles = [b"A", b"C", b"G", b"T"] |
There was a problem hiding this comment.
Gee, we should have these defined in just one place, to avoid errors like this? At least, just in this file as _ACGT_ALLELES?
| transition_matrix[transition_pos] = kappa | ||
| transition_matrix *= root_distribution | ||
| row_sums = transition_matrix.sum(axis=1, dtype="float64") | ||
| transition_matrix = transition_matrix / row_sums[:, np.newaxis] |
There was a problem hiding this comment.
Ah-ha. This is an infinitesimal rate matrix, not a discrete transition matrix, so normalizing the rows separately changes the model. We are parameterizing things so that the the overall rate matrix, denoted Q here is defined so that
Q[i,j] = mutation_rate * transition_matrix[i,j]
for i != j. Under the hood, we lay down mutations at rate mutation_rate without looking at the state of each site, then use the corresponding row of the transition_matrix to pick the next state. This means that the Q[i,i] entries will correspond to "mutations" that we don't actually include since they don't change the state; so our implementation will be most efficient if these are as small as possible - meaning the smallest one should be zero. So, let's see, I'd do it like this:
transition_matrix /= max(row_sums)
row_sums = transition_matrix.sum(axis=1, dtype="float64")
np.fill_diagonal(transition_matrix, 1.0 - row_sums)
... and then we can say in the documentation that the mutation model will be be the HKY rates such that (a) the maximum mutation rate is mutation_rate and the stationary distribution is root_distribution. (oh wait, I have a thought about the parameterization though; I"ll put it in the discussion).
There was a problem hiding this comment.
OK, thanks for taking the time to lay this out so clearly.
Now this part of the verify_model_ts
for j, (row, p) in enumerate(zip(transitions, model.transition_matrix)):
p[j] = 0
p /= sum(p)
self.chisquare(row, sum(row) * p)
makes total sense.
|
I see that you're setting the root distribution and the stationary distribution equal. I agree this is usually what people should do, but they can be different. I'd propose that the HKY model has five parameters that specify the transition matrix: kappa, pi_A, pi_C, pi_G, and pi_T, and then also a root distribution. The root distribituion should default to pi, and the documentation should say something strong about how the user should not specify the root distribution unless they really know what they're doing. |
| transitions_ts, transition_matrix | ||
| ) | ||
| exp_roots_d_ts = ( | ||
| np.sum(roots_d_ts) * model_dict[model]["model_id"].root_distribution |
There was a problem hiding this comment.
This is only the expectation if the chance of not mutating (the diagonal) is the same for all alleles, since sites with no mutations are not added.
There was a problem hiding this comment.
The actual probability that a partticular location has ancestral allele k is mutation_rate * root_distribution[k] * (1 - exp(-transition_matrix[k,k] * total_branch_length)). We could get the expected number of ancestral alleles by computing this iterating over the trees, like (untested):
expected_ancestral_states = np.zeros(num_alleles)
for t in ts.trees():
expected_ancestral_states += mutation_rate * root_distribution * (1 - np.exp(-np.diag(transition_matrix)*t.total_branch_length))
There was a problem hiding this comment.
@petrelharp , a few more questions. I now realize I went head in first without thinking enough about whether I understood the concepts of the root distribution and the transition matrix enough (in terms of how they are being used by the machinery). Sorry about that. I was assuming the root distribution is the frequency distribution from which ancestral state is drawn as soon as a site gets hit by the first mutation. And that from then on, everything is determined by the transition matrix.
So your code exp_roots = num_muts * model.root_distribution in the test_mutations.py modulee made total sense to me. This is what we expect to see in terms of ancestral states for the root of the tree.
Now in the code you are proposing here, you calculate the probability of no mutation happening on a certain site for each of the samples, right? And I assume that transition_matrix[k,k] means -row_sum(transition matrix), so the total probability of leaving a certain state? (Otherwise this is 0 for JukesCantor)
If root distribution is indeed what I think it is, doesn't it suffice to calculate the expectation as you were doing before in your test code?
There was a problem hiding this comment.
Whoops - I made a mistake above. Instead of the diagonal of the transition matrix I should have put the sum of the offdiagonal terms. Also, I had the mutation rate in the wrong place. I think it should be this:
expected_ancestral_states = np.zeros(num_alleles)
change_probs = transition_matrix.sum(axis=1) - np.diag(transition_matrix)
for t in ts.trees():
expected_ancestral_states += root_distribution * (1 - np.exp(-mutation_rate * change_probs*t.total_branch_length))
... but, I see that I should draft up some documentation on how the mutation matrix models work. I'll do that now, which will hopefully answer the other questions.
There was a problem hiding this comment.
... and fixing this up to account for span:
expected_ancestral_states = np.zeros(num_alleles)
change_probs = transition_matrix.sum(axis=1) - np.diag(transition_matrix)
for t in ts.trees():
if discrete:
t_span = np.ceil(t.span[1]) - np.ceil(t.span[0])
else:
t_span = t.span[1] - t.span[0]
expected_ancestral_states += root_distribution * t_span * (1 - np.exp(-mutation_rate * change_probs*t.total_branch_length))
|
I haven't figured out yet why you're using triplets to count transitions? Why is this? |
|
For computing the expected number of transitions I was imagining something like this: where |
I am using this as a way to link parent-nodes to children-nodes (triplet = parent: child1 and child 2). But just iterating over edges without building the triplets dict would do the same. So overkill. |
|
Then to get all other definitions clear. pi_A, pi_C, pi_G, pi_T in the HKY-model then represent the stationary distribution or the equilibrium frequencies as referred to in Seq-Gen right? Can we give it a name (as for the root distribution) so we can specify it as a list? |
Yes - either |
|
See #1045 - and please feel free to improve what I"ve started there. |
|
I have implemented all comments and necessary changes. This is now the HKY mutation model code: However, when running a first test, the diversity compared to Seq-Gen is off. This is not the case for JukesCantor. Still something wrong? |
| self.chisquare(row, sum(row) * p) | ||
|
|
||
| def verify_model_ts_general(self, ts, model, discrete, verify_roots, mutation_rate): | ||
| def verify_model_ts_general_old( |
There was a problem hiding this comment.
we can get rid of this one, now?
Very nice. And yes, looks good! A minor comment or two in the testing code. |
|
@GertjanBisschop, have Peter's comments been addressed? If so, I'll bring this up to date and merge it. |
Yes, all comments have been addressed.
Thanks! |
|
Great, thanks @GertjanBisschop. I'll bring this up to date and merge ASAP. |
97bd757 to
b72fef6
Compare
|
I've updated the PR here to use the newer framework for defining stats checks, and I also refactored things a bit while I was in there to reduce code duplication. Things could still be factored a little bit better (for example, we're computing the expectations over and over again, I think, but they're always the same) but this is a huge step forward. Thanks again for contributing this @GertjanBisschop ! The merge was hideous (I'm glad I didn't subject anyone else to it!), so I'm not 100% confident that everything has come through cleanly. Would you mind taking a quick look through please @GertjanBisschop to see if I've left anything out? |
Codecov Report
@@ Coverage Diff @@
## master #1032 +/- ##
==========================================
+ Coverage 88.25% 88.29% +0.04%
==========================================
Files 23 23
Lines 8717 8774 +57
Branches 1832 1838 +6
==========================================
+ Hits 7693 7747 +54
Misses 506 506
- Partials 518 521 +3
Continue to review full report at Codecov.
|
| def _transition_matrix_chi_sq(self, transitions, transition_matrix): | ||
| tm_chisq = [] | ||
| for row, p in zip(transitions, transition_matrix): | ||
| not_zeros = row > 0 |
There was a problem hiding this comment.
This is a mistake from my side. Should be not_zeros = p > 0. Given the mutation rates we are using, this does not change much.
| 1 - np.exp(-mutation_rate * t.total_branch_length * change_probs) | ||
| ) | ||
| expected_ancestral_states_ts /= expected_ancestral_states_ts.sum() | ||
| expected_num_ancestral_states_ts = expected_ancestral_states_ts * num_sites |
There was a problem hiding this comment.
Normalisation is not necessary, but then we need to multiply by the span of the tree:
expected_ancestral_states_ts += root_distribution * t.span ( 1 - np.exp(-mutation_rate * t.total_branch_length * change_probs) )
Thanks Jerome for reducing duplication. Everything seems to be there. I spotted two minor mistakes of mine. Can I correct those myself? It is true that we are now calculating the matrixexponential too often. It would suffice to do that only once for each branch and store that result. Should I do this in a seperate PR afterwards? |
Meh - does the test take a long time to run? There's no need to add complexity just to be efficient in testing code. |
I can run 250 replicates in a minute |
They do take a fair bit to run, but more than that, it helps to understand what the code is doing. If I see something done inside the loop, I expect it needs to be done inside the loop. I don't think it'd add complexity, it just needs a bit of refactoring. |
b72fef6 to
4cfd6c8
Compare
|
You can add another commit here if you like @GertjanBisschop, but as I've forced pushed to the branch, you'll need to be a bit nasty: then you can add a commit fixing the errors, and push as before. I think it would be better to wait for a follow up PR for any refactorings though, there's other people working on the file and we want to get the big stuff in. |
|
Or we can merge this now and you can fix the issues in a follow-up @GertjanBisschop - it's up to you. |
|
I'll try the nasty stuff. Seems straightforward. Thanks for the commands. |
|
Worked. Mistakes are fixed. |
|
Great, merging. Thanks @GertjanBisschop! Have you stuff you're planning on following up on @GertjanBisschop? I can make some issues if that'll help. |
I will defnitely optimise the code: not calculating matrix exponentials unnecessarily, ... |







closes #1018 . Completes initial code for comparing with Seq-Gen for JC69. Will be extended to accommodate for the mutation models that will be implemented later on.