Skip to content

Simulate from - #541

Merged
jeromekelleher merged 37 commits into
tskit-dev:masterfrom
mcveanlab:simulate_from
Aug 15, 2018
Merged

jeromekelleher merged 37 commits into
tskit-dev:masterfrom
mcveanlab:simulate_from

Conversation

@jeromekelleher

Copy link
Copy Markdown
Member

WIP

@jeromekelleher
jeromekelleher force-pushed the simulate_from branch 2 times, most recently from 91b248f to 5bdeef5 Compare July 15, 2018 20:22
@jeromekelleher

Copy link
Copy Markdown
Member Author

FYI, I'm making progress here @petrelharp and @bhaller. The algorithm for simulate-from is easy and I've implemented here in the Python prototyper (see the changes in algorithms.py, if you're interested).

I've ended up having to do a fair bit of refactoring and tidying up to get me to the point where I can actually implement this algorithm though, which is what 95% of this patch is about. I'm getting there though, and I'm confident I can get it finished in a few more passes.

@bhaller

bhaller commented Jul 15, 2018

Copy link
Copy Markdown

Sounds very encouraging! :->

@petrelharp

Copy link
Copy Markdown
Contributor

The amount of replumbing is a bit daunting. Thanks!

@jeromekelleher
jeromekelleher force-pushed the simulate_from branch 5 times, most recently from 49cbceb to f9fb050 Compare July 22, 2018 16:37
@jeromekelleher

jeromekelleher commented Jul 22, 2018 •

Copy link
Copy Markdown
Member Author

Pinging @DomNelson.

This PR is all about starting a backwards-in-time simulation from an arbitrary tree sequence, and is mostly working now. In the process of doing this, I realise that it'd be quite a bit simpler now if we got rid of the ModelChangedEvents and instead implemented the hybrid coalescent-DTWF simulations like this (this should work fine now in this branch):

initial_ts = msprime.simulate(100, Ne=1000, max_time=100, model="dtwf")
full_ts = msprime.simulate(from_ts=initial_ts, Ne=1000)

I guess there is a bit more overhead here in creating an intermediate tree sequence and so on, but it's probably not worth worrying about. Arguably it's more useful to have the two tree sequences lying around anyway, in case you want to do some analysis on the separate bits.

What do you think? If you agree, I'll chop out the ModelChange stuff which should simplify things a bit.

Also, it'd be great if you could take a skim through the C code to see if you can spot anything!

@jeromekelleher

Copy link
Copy Markdown
Member Author

@petrelharp and @bhaller: This is basically working now. I have a lot of work still to do on testing with demographic events, ancient samples and so on, but for simple single-population simulations this should work fine:

slim_ts = msprime.load("slim.trees")
full_ts = msprime.simulate(from_ts=slim_ts, Ne=1000)

It's not ready for use yet or merging as there's a whole bunch of stuff I haven't tested like mutations and replication, and I haven't done any statistical tests yet either.

Any thoughts on the API? I would have preferred to make the argument from, but this is a keyword in Python, so I kludged it to from_ts...

@jeromekelleher

jeromekelleher commented Jul 22, 2018 •

Copy link
Copy Markdown
Member Author

TODO:

  • Tests with mutations (throwing mutations over the entire tree sequence, but keeping any existing mutations seems like the right behaviour for the mutation_rate argument.
  • Tests for replication. Generate many ancient histories for a given recent past.
  • Specifying the correct number of populations
  • Demographic events: do we correctly skip events that happen before the first node in from_ts and correctly apply those that are older?
  • Do we deal with historical samples correctly? (Should the semantics of the initial time be changed? Currently we take the oldest node time as the start, but it should probably be the oldest non-sample time or zero. We would then have to deal with ancient sampling events, but could just disallow these initially.)
  • Statistical tests
  • Documentation.
  • Ensure subclasses of TreeSequence will be accepted as arguments

@bhaller

bhaller commented Jul 22, 2018

Copy link
Copy Markdown

Any thoughts on the API? I would have preferred to make the argument from, but this is a keyword in Python, so I kludged it to from_ts...

Seems fine. Perhaps there's some other term, rather than "from", that would not be reserved and would feel a bit nicer? "begin", "initial", "basis", "start", etc...?

As far as usage with SLiM is concerned: would it work just as well to call pyslim.load instead of msprime.load? And would the SLiM-specific metadata, etc., then be preserved? That's where we want to end up, I think.

How does it tell which genomes, exactly, are to be simulated backward from? All genomes with no ancestor? Or the genomes of all defined individuals, tracing backward through the population's history? Or what? I'm thinking here of the way that SLiM lets you add genomes to the sample permanently, as "remembered genomes", which – by the time a .trees file is written out – may no longer represent any extant individual. I'm not sure whether one would want such "remembered genomes" to be included in a recapitation operation or not. @petrelharp what do you think? Possibly there should be an (optional) way to specify exactly which genomes should be recapitated? Or do you think the standard behavior can always be what the user wants?

Great to hear that it's coming together. Thanks for all the work. I'll be dropping off the radar for a while, starting in two days; I'm heading off to a place in remote Colorado with no internet. After that break I'll be back in Eugene, and I imagine I'll then get up to speed with this stuff and put it to use! :->

@jeromekelleher

Copy link
Copy Markdown
Member Author

@bhaller:

As far as usage with SLiM is concerned: would it work just as well to call pyslim.load instead of msprime.load? And would the SLiM-specific metadata, etc., then be preserved? That's where we want to end up, I think.

That should all just work. There might an issue with using subclasses of TreeSequence (which pyslim.load returns, I think) in the current code, but I'll sort that out.

How does it tell which genomes, exactly, are to be simulated backward from? All genomes with no ancestor? Or the genomes of all defined individuals, tracing backward through the population's history? Or what? I'm thinking here of the way that SLiM lets you add genomes to the sample permanently, as "remembered genomes", which – by the time a .trees file is written out – may no longer represent any extant individual. I'm not sure whether one would want such "remembered genomes" to be included in a recapitation operation or not. @petrelharp what do you think? Possibly there should be an (optional) way to specify exactly which genomes should be recapitated? Or do you think the standard behavior can always be what the user wants?

It's just the roots of the trees. Roots are defined as the unique ancestors of samples, so the user can specify which lineages are to be simulated from by changing the sample status of nodes. All we do is look at each tree, and if there is more than one root we create ancestral segments for each root spanning the interval of this tree. I'm not sure how this would interact with the "remembered genomes" stuff in SLiM though.

Great to hear that it's coming together. Thanks for all the work. I'll be dropping off the radar for a while, starting in two days; I'm heading off to a place in remote Colorado with no internet. After that break I'll be back in Eugene, and I imagine I'll then get up to speed with this stuff and put it to use! :->

Cool; have fun!

@DomNelson

Copy link
Copy Markdown
Member

Looks like a good strategy to me. I agree the overhead is manageable, especially since hybrid sims will tend to be pretty large-scale. I've skimmed through the changes in msprime.c and all looks good as far as I can tell - this is a lot of work! I'll let you know if I spot anything odd as I go through the rest

@jeromekelleher

Copy link
Copy Markdown
Member Author

Thanks @DomNelson, good to know. Most of the change is an overdue refactoring to use updated APIs; it seemed as well to do this as I was rummaging around in there anyway.

@petrelharp

Copy link
Copy Markdown
Contributor

Great! I've not got the big picture of how the simulator gets set up, but:

Currently we take the oldest node time as the start, but it should probably be the oldest non-sample time or zero. We would then have to deal with ancient sampling events, but could just disallow these initially.)

I think we need to have the time to simulate above as a parameter that's passed in (which is not currently a parameter, right?). Otherwise: suppose you forwards simulate for 10 generations, and all of the roots happen to be at 5 generations; then when you run the coalescent simulation to fill in prior history you might get a coalescence at 7 generations before present, which is inconsistent with the forwards simulation. And, i'd vote for making this a required parameter, as guessing the right thing seems complicated (maybe impossible in general).

@petrelharp

Copy link
Copy Markdown
Contributor

I'm not sure how this would interact with the "remembered genomes" stuff in SLiM though.

The remembered genomes are just samples at some previous time, nothing special, so there's nothing to worry about there.

@petrelharp

Copy link
Copy Markdown
Contributor

Throwing mutations over the entire tree sequence, but keeping any existing mutations seems like the right behaviour for the mutation_rate argument.

I guess this is the natural use case for fowards-simulating with only selected mutations. We should definately document this well, though, as it'd be easy for people to end up with twice as many mutations as they want on the lower bit of the trees.

@bhaller

bhaller commented Jul 25, 2018

Copy link
Copy Markdown

I think we need to have the time to simulate above as a parameter that's passed in (which is not currently a parameter, right?). Otherwise: suppose you forwards simulate for 10 generations, and all of the roots happen to be at 5 generations; then when you run the coalescent simulation to fill in prior history you might get a coalescence at 7 generations before present, which is inconsistent with the forwards simulation. And, i'd vote for making this a required parameter, as guessing the right thing seems complicated (maybe impossible in general).

Hmm. But typically you want to reach coalescence, not just go backwards to whatever generation 0 happens to be, right? Would it continue into "negative time" until coalescence was reached? If not, how would one achieve the result that one typically wants to achieve – coalescence, guaranteed?

@jeromekelleher

Copy link
Copy Markdown
Member Author

I think we need to have the time to simulate above as a parameter that's passed in (which is not currently a parameter, right?). Otherwise: suppose you forwards simulate for 10 generations, and all of the roots happen to be at 5 generations; then when you run the coalescent simulation to fill in prior history you might get a coalescence at 7 generations before present, which is inconsistent with the forwards simulation. And, i'd vote for making this a required parameter, as guessing the right thing seems complicated (maybe impossible in general).

This is a subtle point @petrelharp... Thinking it through I think you're right. We need to specify a time from which the coalescent model starts... For forward sims in general then this would be the number of generations that you've simulated, right?

This is fine, and can be used in the standard case as well (for what, I don't know, but it easier to just make it a full parameter). I'll add it in.

I'm also adding an end_time argument here (currently called max_time), mainly to make it easy to generate tree sequences that need to be completed. I'm planning on making the semantics of this parameter "simulate until the first event happens whose time would exceed end_time, and terminate without actually applying this event". This would guarantee that the time of any node is strictly less than end_time. This seems more useful than the alternative, which would mean that any number of nodes could have times greater than end_time. It also seems nice to keep the general "half closed" pattern going so that start_time is inclusive and end_time is exclusive. What do you think?

@jeromekelleher

Copy link
Copy Markdown
Member Author

Agh! Slip of the "close" button here. I was responding to @bhaller here:

Hmm. But typically you want to reach coalescence, not just go backwards to whatever generation 0 happens to be, right? Would it continue into "negative time" until coalescence was reached? If not, how would one achieve the result that one typically wants to achieve – coalescence, guaranteed

This is at the other end of time @bhaller, specifying what time the coalescent model starts (in backward time). We'll always simulate to full coalescence by default.

@petrelharp

Copy link
Copy Markdown
Contributor

We need to specify a time from which the coalescent model starts... For forward sims in general then this would be the number of generations that you've simulated, right?

Yes, as long as the tree sequence has had times shifted so that time in the tree sequence is measured in units before the end of the simulation. (Recall that it's easiest to measure time in units before the start of the simulation; in which case we'd want to start at 0.0.)

I think your proposal for end_time is the right one.

It'd be nice to think of something to call these things that doesn't connote a directionality to time. Like instead of end_time, how about oldest_time? longest_ago_time? Or maybe I even like max_time better. The corresponding time-ago from which to run coalescence could be called youngest_time or most_recent_time_ago? Or start_time_ago and end_time_ago? Hmph.

@petrelharp

Copy link
Copy Markdown
Contributor

Just to add a bit:

Hmm. But typically you want to reach coalescence, not just go backwards to whatever generation 0 happens to be, right? Would it continue into "negative time" until coalescence was reached? If not, how would one achieve the result that one typically wants to achieve – coalescence, guaranteed

This is at the other end of time @bhaller, specifying what time the coalescent model starts (in backward time). We'll always simulate to full coalescence by default.

"Time" here is "time ago", i.e., units of time before the zero-time. (I think "time ago" is better than "backwards time"?)

@bhaller

bhaller commented Jul 26, 2018

Copy link
Copy Markdown

Well, this time-related stuff just makes my head spin. :-> It sounds like you guys have a good sense of what needs to be done, and I'm clearly just confused, so I will leave it to you. I would add just one suggestion: Peter, perhaps you could throw together a proof-of-concept of Example 4 from our TreeSeq paper, recapitating a SLiM run, and make sure that it works with what Jerome is doing? "Works" in both the technical sense and in the semantic sense of the APIs being sensical and easy to use for that usage pattern. If you could put that together (hopefully should be completely trivial), that would be great; I can then leverage what you have done when I get around to doing the example.

@petrelharp

Copy link
Copy Markdown
Contributor

Well, this should work:

decap = pyslim.load("decapitated.trees", slim_format=True)
recap = msprime.simulate(
            from_ts=decap,
            # start_time_ago=decap.slim_generation,
            Ne=1000)

but I'm getting a MSP_ERR_INCOMPATIBLE_FROM_TS error, possibly because the number of populations hasn't been set. (setting length=decap.sequence_length doesn't fix the problem, but shouldn't be necessary?)

@jeromekelleher

Copy link
Copy Markdown
Member Author

but I'm getting a MSP_ERR_INCOMPATIBLE_FROM_TS error, possibly because the number of populations hasn't been set. (setting length=decap.sequence_length doesn't fix the problem, but shouldn't be necessary?)

Yes, you have to set the number of populations in the simulation to whatever is in the tree sequence. We could set this up automatically, but them we wouldn't know the migration rates so the most likely thing to happen is that the simulation will run forever. In the interest of "fail early, fail loudly", I think requiring the user to explicitly set the populations is the most user-friendly thing to do.

There should be better errors thrown though; I'll put in some checks in the Python code.

Jerome Kelleher added 18 commits August 14, 2018 14:37
Implementing and verifying the semantics of max_time precisely and
correctly is a little involved, so has been put off to some other time.
Also remove support for mutation_generator in simulate, and make sure
that we cannot specify mutation rate along with from_ts.
Also fixed a couple of minor bugs:

- TableCollection.__str__ wasn't showing individuals.
- Setting NodeTable.individuals nuked the population column.
Identified issue with L != 1 for single locus simulation.
simulate_from will currently only run if the recomb_map has a single
locus.
@jeromekelleher

Copy link
Copy Markdown
Member Author

I've written some statistical tests here @petrelharp, and hit a bit of head-scratcher. The idea is that we should obtain identical tree sequences in distribution if we simulate a model the whole way through, or if we stop it some time in the middle and complete the simulation using simulate_from.

However, with a reasonable amount of recombination, this isn't what I'm seeing:

original        mean trees =  89.668    mean nodes =  85.828    mean edges =  292.912
t =  0.5        mean trees =  80.279    mean nodes =  87.882    mean edges =  289.993
t =  1.0        mean trees =  81.806    mean nodes =  91.515    mean edges =  302.945
t =  1.5        mean trees =  82.028    mean nodes =  92.129    mean edges =  299.409
t =  5.0        mean trees =  88.08     mean nodes =  88.437    mean edges =  293.974

The first line is what we get for the mean number of trees, nodes and edges if we simulate all the way until coalescence. The remaining lines are what we get when we stop at different time points.

It looks like we get too many nodes and edges, and too few trees, and I'm puzzled about how this would happen.

Do you think the basic test makes sense? There must either be some weird bug which didn't show up with unit tests, or some subtle effect regarding the initial conditions I didn't think of. Any thoughts?

@petrelharp

Copy link
Copy Markdown
Contributor

That is confusing. Are you sure that you have got a large enough sample size so that it's not statistical noise? I am suspicious because it looks like t = 5.0 is getting close to original, but it's still quite far away (at least for nodes). If you ran one with t = 20, say, then that should be just like the original, at least.

Also, are you running these through simplify before comparing? It seems like you shouldn't have to, but maybe there's something subtle. Ah -- what about when a block of genome splits apart along an edge of the tree, but then coalesces together again before the end of the branch? msprime makes it so you don't see those (right?), but any of these self loops that are pending at the recapitation time might not be erased (but they should be by simplify?).

@jeromekelleher

Copy link
Copy Markdown
Member Author

Aha! I see what the problem is. But, ouch, this complicates things.

I've been assuming that we can completely restore the state of a simulation just by looking at the edges and finding the roots of the trees. This is only partially true, unfortunately. Here is the state of a simulation which has been stopped early:

        [0][(1084-10000) 0] 
        [0][(2033-10000) 2] 
        [0][(0-6840) 12] [(6840-10000) 1] 
        [0][(6840-10000) 11] 
        [0][(0-3066) 13] [(3066-10000) 7] 
        [0][(5804-10000) 4] 
        [0][(0-5804) 4] 
        [0][(0-10000) 3] 
        [0][(0-2033) 2] 
        [0][(0-1084) 0] [(3066-10000) 5] 

Each line here is a list of (left, right, node) segments representing a single ancestor. Here's what we reconstruct:

        [0][(6840-10000) 1] 
        [0][(6840-10000) 11] 
        [0][(3066-10000) 5] 
        [0][(3066-10000) 7] 
        [0][(0-3066) 13] 
        [0][(0-10000) 4] 
        [0][(0-10000) 3] 
        [0][(0-10000) 2] 
        [0][(0-6840) 12] 
        [0][(0-10000) 0] 

So, we get all of the interval->node mappings correct, but we lose all the information about which segments go together within individuals. This is rather a poor approximation I think, which is why we're seeing these statistical departures from the coalescent.

Hmm. As this PR contains a lot of refactoring which will be useful in any case, I'm going to merge this much, and move discussion of how we fix the problem to #572.

@jeromekelleher
jeromekelleher merged commit d74eacd into tskit-dev:master Aug 15, 2018
@jeromekelleher
jeromekelleher deleted the simulate_from branch August 15, 2018 10:05
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.

4 participants