Skip to content

Finish simulate from - #581

Merged
jeromekelleher merged 14 commits into
tskit-dev:masterfrom
mcveanlab:finish-simulate-from
Aug 24, 2018
Merged

jeromekelleher merged 14 commits into
tskit-dev:masterfrom
mcveanlab:finish-simulate-from

Conversation

@jeromekelleher

Copy link
Copy Markdown
Member

This has been another long journey, but I think it's almost done now. I'm pretty sure it's statistically correct now, and it's also fast. Here's a benchmark I did with 50 megabases of human-ish sequence:

====================
n =  1000
====================
Full sim required 13.25 sec
Initial sim required 2.19 sec
         87237 trees, mean roots =  13.927931955477607
Final sim required 11.21 sec
====================
n =  10000
====================
Full sim required 14.94 sec
Initial sim required 5.10 sec
         130141 trees, mean roots =  14.901230204163177
Final sim required 12.39 sec
====================
n =  100000
====================
Full sim required 34.59 sec
Initial sim required 20.16 sec
         178233 trees, mean roots =  14.033069072506214
Final sim required 12.31 sec

Basically, there's no cost to doing this.

The trick is to stick on extra edges to represent the ancient ancestor that we must recreate. This is a bit fiddly, but I think it basically works in the coalescent simulation case.

The requirements for forward simulations are actually quite straightforward. Basically, we need to mark the nodes from the initial population (i.e., generation 0) in the simulation as samples, and always keep these around. The trick then is to unmark these as samples before you output the final tree sequence, keeping only the extant population as samples. Consider the following WF simulation example (these trees probably won't render properly for everyone; curse the lack of monospace fonts in the world!):

   1        3   
   ┃        ┃   
   15       ┃   
┏━┳┻━━┓     ┃   
┃ ┃   13    12  
┃ ┃  ┏┻┓   ┏┻┓  
6 11 7 10  8 9  

  3       1     
  ┃       ┃     
  14      15    
┏━┻━┓   ┏━┻┓    
┃   12  ┃  13   
┃  ┏┻┓  ┃ ┏┻┓   
11 8 9  6 7 10  

 1    0    3     
 ┃    ┃    ┃     
 ┃    ┃    14    
 ┃    ┃  ┏━┻━┓   
 13   ┃  ┃   12  
┏┻┓   ┃  ┃  ┏┻┓  
7 10  6  11 8 9  

These are three adjacent trees, where the samples are 6-11. The nodes for the initial population were marked as samples, and these are showing up here as 0, 1 and 3. Note that they are no longer samples though, as 0 does not show up as a root in the first two trees. We can then finish this simulation using simulate_from, and the first tree we get is:

    15       
 ┏━━┻━┓      
 ┃    9      
 ┃  ┏━╋━━┓   
 6  ┃ ┃  7   
┏┻┓ ┃ ┃ ┏┻┓  
2 3 0 5 1 4  

The nodes have been renumbered, but you can see where the topology is preserved.

The way I ended up doing it was by using the root segments of the trees. I spent most of today on a different algorithm in which we just look at the root segments, but there proved to be very tricky corner cases.

One nasty thing about the current algorithm is that we have to run simplify() at the end to get rid of the unary nodes (we need to do this as (a) it's hard to compare things statistically if we don't; and (b) it'll confuse users if we don't). I'm sure there is an algorithm in which we remove the unary edges from the table and the nodes corresponding to ancient individuals, but it seems quite fiddly to me.

A good thing about this approach also is that I'm sure that in 99% of the cases there's no need to specify start_time. If we follow the recipe above and keep track of our generation-zero nodes, then we know exactly how long the simulation was run for.

There's still quite a few test-cases to fill out, but I think it's mostly working now.

@jeromekelleher
jeromekelleher force-pushed the finish-simulate-from branch 2 times, most recently from 133614d to 91edc1e Compare August 20, 2018 19:37
@jeromekelleher

Copy link
Copy Markdown
Member Author

I think this is basically done now @petrelharp, other than documentation. Would you mind taking a look through this please, and maybe trying it out with SLiM? It should work with any tree sequence as input, but will only produce statistically correct output if the initial population is retained, as discussed above.

I'll do the documentation ASAP if you agree with what's been done here.

(Note to self: revert the implementation in algorithms.py, as the current version doesn't match the real one.)

@petrelharp

Copy link
Copy Markdown
Contributor

(trying it out now; in the meantime:) I think this is a good solution; but, for clarity - did you come across a problem with the proposal to have simplify record uncoalesced root segments, or was that option ditched for expediency?

@jeromekelleher

Copy link
Copy Markdown
Member Author

(trying it out now; in the meantime:) I think this is a good solution; but, for clarity - did you come across a problem with the proposal to have simplify record uncoalesced root segments, or was that option ditched for expediency?

I had a good hard look at this, and I can't see how it could be done with the current version of simplify. In an older version we were taking the trouble to maintain ancestry, so that at the end of the process we should have the root segments. But in the current version we deliberately don't bother with this which makes things much faster. Reverting back to this older version of simplify just didn't seem worth it to me (and, going by recent experience, it wouldn't have worked out that easily either!).

The current approach seems more elegant to me in any case, as it also solves the start_time problem too. Should be an easy update for SLiM and something we can document for forward-simulator developers?

@petrelharp

Copy link
Copy Markdown
Contributor

Ok, I've messed around with this a good bit with SLiM, and it all checks out. I've also added a .recapitate() method to pyslim that does this unmarking of the first generation. Happily, recapitating my terrible messy tree sequence that previously caused my computer to thrash now works with very little memory. =) I'll take a better pass through the code now, but it's probably good to go.

Comment thread lib/msprime.c
goto out;
}
/* Reset the tables to their correct position for replication */
ret = table_collection_reset_position(&self->tables, &self->from_position);

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 is a bit confusing. As far as I can tell, the tables can't have been modified since this position was set over here. Is this just paranoia? Or could the tables have been actually modified?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think the confusion is because of the commented out code I've left lying around. But it's being reset at the start of every replicate back to the where the input tree sequence started.

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.

ah, re-use across replicates .I see. that's what "for replication" means. =)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yep -- there's a lot of effort in there to make replication as efficient as possible.

Comment thread lib/msprime.c
} else {
tail = root_segments_tail[root];
if (tail->right == left) {
tail->right = right;

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.

👍

Comment thread lib/msprime.c
goto out;
}
if (!msp_is_completed(self)) {
ret = msp_insert_uncoalesced_edges(self, tables);

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.

👍

@petrelharp

Copy link
Copy Markdown
Contributor

LGTM!

One question: I think that if you remove this simplify then the tables from the input from_ts will remain, unchanged, up at the top of the resulting tree sequence. Is that right? If so, should we document that fact? (It could be useful, but then we couldn't change it...)

@petrelharp

Copy link
Copy Markdown
Contributor

Thanks a ton for all this good work.

@jeromekelleher

Copy link
Copy Markdown
Member Author

One question: I think that if you remove this simplify then the tables from the input from_ts will remain, unchanged, up at the top of the resulting tree sequence. Is that right? If so, should we document that fact? (It could be useful, but then we couldn't change it...)

Getting rid of it now --- it's much nicer having this property.

@jeromekelleher

Copy link
Copy Markdown
Member Author

OK, the simplify is gone and the code tidied up. I think it's basically done except for documentation.

I've made a first pass at a tutorial for this @petrelharp --- would you mind taking a look over it and see what you think?

Comment thread docs/examples.py
print("interval = ", tree.interval)
print(tree.draw(format="unicode"))

recomb_map = msprime.RecombinationMap.uniform_map(num_loci, 1, num_loci)

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.

shouldn't that be

     recomb_map = msprime.RecombinationMap.uniform_map(num_loci, 0.01, num_loci) 

, since the rate argument is per unit of length, and the sequence length is L=100?
(Or, to be more clear, it could be rate = 1/wf_ts.sequence_length?)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, it probably should, but L=2 here, so it'd be 1/2. Also, I'm not setting Ne here, which should be either N, N / 2 or 2N I guess (I have to look this up every time).

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.

Ne is diploid, and N is haploid, so it'd be N/2 = 5 (I think :)

@petrelharp

Copy link
Copy Markdown
Contributor

That tutorial looks great.

Comment thread docs/tutorial.rst Outdated

.. code-block:: python

recomb_map = msprime.RecombinationMap.uniform_map(num_loci, 1, num_loci)

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.

same comment as above

@jeromekelleher

Copy link
Copy Markdown
Member Author

I've updated this with more docs @petrelharp. I'm hoping to wrap this up tomorrow and release, so it'd be great if you could have a scan through the docs to see if you can spot any problems.

Comment thread docs/api.rst Outdated
that are not valid topologically. In general, if the same recombination map
that was used to generate the initial tree sequence is provided as input to
to the coalescent simulation, then everything should work (although there may
still be unexpected effects due to numerical rounding issues.)

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 statement is too strong, I think. How about

If recombination positions are generated in the same way in both the initial tree sequence and the coalescent simulation, then everything should work. However, the fine scale details of the underlying recombination model
matter, so matching nonuniform recombination maps between simulators may not be possible at present.
(To make it work, we must ensure that every recombination breakpoint in ``from_ts`` matches exactly to
a possible recombination breakpoint in msprime's recombination map, which is not guaranteed because of
msprime's discrete recombination model.)

One case in which it is guaranteed to work is if ``from_ts`` has integer coordinates, and we want to simulate
a coalescent with a uniform recombination rate. In this case, to have a uniform recombination rate ``r``, ...

Comment thread docs/tutorial.rst Outdated

[(0, 2, 0), (0, 2, 7), (1, 2, 8), (1, 2, 4)]

where each segment is a ``(left, right, node)`` tuple. As nodes 0 and 7 are present in both

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.

how about add

For instance, root ``8`` has not coalesced over the interval from ``1.0`` to ``2.0``, while root ``0`` has not coalesced over the entire segment from ``0.0`` to ``2.0``.

Comment thread docs/tutorial.rst
but has the redundant nodes and edges removed. Note also that he node IDs have been
reassigned so that the samples are 0 to 9 --- if you need the IDs from the original
tree sequence, please set ``map_nodes=True`` when calling ``simplify`` to get a
mapping between the two sets of IDs.

@petrelharp petrelharp Aug 23, 2018 •

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.

Perhaps add here:

----------------------------------------------
Why recording the initial generation?
----------------------------------------------

We can now see why it is essential that the forwards simulator records the *initial* generation in a tree sequence
that will later be used as a ``from_ts`` argument to ``msprime.simulate( )``. In the example above, if node ``7`` was not in the tree sequence, we would not know that the segment that node ``20`` inherits from on ``[0.0, 1.0)`` and the segment that node ``12`` inherits from on ``[1.0, 2.0)`` both exist in the same node (here, node ``7``).

However, note that although the intial generation (above, nodes ``0``, ``4``, ``7``, and ``8``) must be in the tree
sequence, they do *not* have to be samples. The easiest way to do this (as is what is done in ``pyslim``) is to
(a) retain the initial generation as samples throughout the forwards simulation (so they persist through ``simplify()``), but then (b) before recapitation, removing the flags that mark them as samples, so that 
``simulate()`` does not simulate their entire history as well.

Comment thread docs/tutorial.rst Outdated
are usually quite slow compared to similar coalescent simulations. In this
section we show how to combine the best of both approaches by simulating
the recent past using a forwards-time simulator and then complete the
simulation of the ancient past using ``msprime``.

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.

Add

We refer to this process as "recapitation".

Comment thread docs/tutorial.rst Outdated
Wright-Fisher simulation with a coalescent simulation: hooray! However, these
trees have some slightly odd properties which are important to be aware of.
In both trees we can see that the old roots are still present in the trees,
even through they have only one child and are clearly redundant. While this

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.

Insert here, maybe:

This is because the tables of ``from_ts`` have been retained, without modification, at the top of the tables of the output tree sequence. 

@petrelharp

Copy link
Copy Markdown
Contributor

I've had a good pass through. I kinda wanted to insert text about how the from_ts tables are retained in the docs for simulate, but it seemed like it'd clutter that up too much. LGTM!

@jeromekelleher

Copy link
Copy Markdown
Member Author

Thanks @petrelharp! One issue though: I mildly object to the term 'recapitation', simply because it implies that the thing had a head in the first place. These are headless tree sequences that we're grafting a head on (or, possibly many different heads!). "Encapitate" or just "capitate" would be less inaccurate, but they're not very catchy.

I'll admit that what I've gone with doesn't roll off the tongue as well as 'recaptitation'. I just think it's going to confuse people...

@petrelharp

Copy link
Copy Markdown
Contributor

I mildly object to the term 'recapitation'

No problem. it's just so much shorter than "run simulate with from_ts specified".

@jeromekelleher

Copy link
Copy Markdown
Member Author

Ahh, interesting point here:

(a) retain the initial generation as samples throughout the forwards simulation (so they persist through simplify()), but then (b) before recapitation, removing the flags that mark them as samples, so that
simulate() does not simulate their entire history as well.

I would have said the right thing to do here is to (a) retain the initial generation as samples throughout the forwards simulation; and (b) just before final output unmark these ancient individuals as samples.

Why output the initial generation as samples? This seems quite confusing to me, and not what I would expect when I load a forward-time tree sequence.

I'm changing the text for now so I can merge this, but we can change it back if I'm wrong.

Jerome Kelleher added 3 commits August 24, 2018 13:27
@jeromekelleher

Copy link
Copy Markdown
Member Author

Merging this so the docs go live on RTD. Happy to make changes though.

@jeromekelleher
jeromekelleher merged commit 152aa4d into tskit-dev:master Aug 24, 2018
@jeromekelleher
jeromekelleher deleted the finish-simulate-from branch August 24, 2018 12:54
@petrelharp

Copy link
Copy Markdown
Contributor

I would have said the right thing to do here is to (a) retain the initial generation as samples throughout the forwards simulation; and (b) just before final output unmark these ancient individuals as samples.

Ah, good point. Er, I figured that output tree sequences should be simplified, so they need to be marked as samples. And, I've added the unmarking to the pyslim.SlimTreeSequence.recapitate method. I guess I think this is confusing, but stil maybe the right way to go? Currently it is the user's responsibility to mark the first generation; but you're right, it probably should not be. I will discuss with @bhaller

@jeromekelleher

Copy link
Copy Markdown
Member Author

Ah, good point. Er, I figured that output tree sequences should be simplified, so they need to be marked as samples. And, I've added the unmarking to the pyslim.SlimTreeSequence.recapitate method. I guess I think this is confusing, but stil maybe the right way to go? Currently it is the user's responsibility to mark the first generation; but you're right, it probably should not be. I will discuss with @bhaller

OK, keep me posted. I'm happy to delay the release until tomorrow/next week so we can get this nailed down in the docs.

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.

2 participants