Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions _msprimemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -8710,7 +8710,7 @@ Simulator_init(Simulator *self, PyObject *args, PyObject *kwds)
Py_ssize_t node_mapping_block_size = 10;
tree_sequence_t *from_ts = NULL;
int store_migrations = 0;
double start_time = 0;
double start_time = -1;

self->sim = NULL;
self->random_generator = NULL;
Expand Down Expand Up @@ -8769,10 +8769,12 @@ Simulator_init(Simulator *self, PyObject *args, PyObject *kwds)
goto out;
}
}
sim_ret = msp_set_start_time(self->sim, start_time);
if (sim_ret != 0) {
handle_input_error(sim_ret);
goto out;
if (start_time >= 0) {
sim_ret = msp_set_start_time(self->sim, start_time);
if (sim_ret != 0) {
handle_input_error(sim_ret);
goto out;
}
}
sim_ret = msp_set_store_migrations(self->sim, (bool) store_migrations);
if (sim_ret != 0) {
Expand Down
79 changes: 50 additions & 29 deletions algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ def __init__(
self.P[pop_index].set_start_size(population_sizes[pop_index])
self.P[pop_index].set_growth_rate(population_growth_rates[pop_index], 0)
self.edge_buffer = []
self.from_ts = from_ts
if from_ts is None:
self.tables = msprime.TableCollection(sequence_length=num_loci)
for pop_index in range(N):
Expand All @@ -290,33 +291,7 @@ def __init__(
raise ValueError("Sequence length in from_ts must match")
if ts.num_populations != N:
raise ValueError("Number of populations in from_ts must match")
self.tables = ts.dump_tables()
prev_map = {}
for tree in ts.trees():
left, right = tree.interval
if int(left) != left or int(right) != right:
raise ValueError("Coordinates must be integers")
if tree.num_roots == 1:
self.S[left] = 0
else:
for root in tree.roots:
population = ts.node(root).population
prev = prev_map.get(root, None)
x = self.alloc_segment(left, right, root, population, prev=prev)
if prev is None:
self.L.set_value(x.index, right - left - 1)
self.P[pop_index].add(x)
else:
self.L.set_value(x.index, right - prev.right)
prev.next = x
prev_map[root] = x
self.S[left] = tree.num_roots
self.S[self.m] = -1
self.t = self.tables.nodes.time.max()
for j in range(N):
for x in self.P[j]:
self.defrag_segment_chain(x)
self.defrag_breakpoints()
self.initialise_from_ts(ts)

self.num_ca_events = 0
self.num_re_events = 0
Expand All @@ -337,6 +312,52 @@ def __init__(
(time, self.bottleneck_event, (int(pop_id), intensity)))
self.modifier_events.sort()

def initialise_from_ts(self, ts):
self.tables = ts.dump_tables()
root_time = np.max(self.tables.nodes.time)
self.t = root_time

root_segments_head = [None for _ in range(ts.num_nodes)]
root_segments_tail = [None for _ in range(ts.num_nodes)]
last_S = -1
for tree in ts.trees():
left, right = tree.interval
S = 0 if tree.num_roots == 1 else tree.num_roots
if S != last_S:
self.S[left] = S
last_S = S
# If we have 1 root this is a special case and we don't add in
# any ancestral segments to the state.
if tree.num_roots > 1:
for root in tree.roots:
population = ts.node(root).population
if root_segments_head[root] is None:
seg = self.alloc_segment(left, right, root, population)
root_segments_head[root] = seg
root_segments_tail[root] = seg
else:
tail = root_segments_tail[root]
if tail.right == left:
tail.right = right
else:
seg = self.alloc_segment(left, right, root, population, tail)
tail.next = seg
root_segments_tail[root] = seg
self.S[self.m] = -1

# Insert the segment chains into the algorithm state.
for node in range(ts.num_nodes):
seg = root_segments_head[node]
if seg is not None:
self.L.set_value(seg.index, seg.right - seg.left - 1)
self.P[seg.population].add(seg)
prev = seg
seg = seg.next
while seg is not None:
self.L.set_value(seg.index, seg.right - prev.right)
prev = seg
seg = seg.next

def change_population_size(self, pop_id, size):
print("Changing pop size to ", size)
self.P[pop_id].set_start_size(size)
Expand Down Expand Up @@ -407,7 +428,8 @@ def finalise(self):
Finalises the simulation returns an msprime tree sequence object.
"""
self.flush_edges()
return self.tables.tree_sequence()
ts = self.tables.tree_sequence()
return ts

def simulate(self, model='hudson'):
if self.model == 'hudson':
Expand All @@ -417,7 +439,6 @@ def simulate(self, model='hudson'):
else:
print("Error: bad model specification -", self.model)
raise ValueError

return self.finalise()

def hudson_simulate(self):
Expand Down
71 changes: 71 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,77 @@ Variable recombination rates
.. autoclass:: msprime.RecombinationMap
:members:

.. _sec_api_simulate_from:

+++++++++++++++++++++++++++++++++++++++++++++
Initialising simulations from a tree sequence
+++++++++++++++++++++++++++++++++++++++++++++

By default ``msprime`` simulations are initialised by specifying a set of samples,
using the ``sample_size`` or ``samples`` parameters to :func:`.simulate`. This
initialises the simulation with segments of ancestral material covering the
whole sequence. Simulation then proceeds backwards in time until a most recent
common ancestor has been found at all points along this sequence. We can
also start simulations from different initial conditions by using the
``from_ts`` argument to :func:`.simulate`. Informally, we take an 'unfinished'
tree sequence as a parameter to simulate, initialise the simulation
from the state of this tree sequence and then run the simulation until
coalescence. The returned tree sequence is then the result of taking the
input tree sequence and completing the trees using the coalescent.

This is useful for forwards-time simulators such as
`SLiM <https://messerlab.org/slim/>`_ that can output tree sequences. By running
forward-time simulation for a certain number of generations we obtain a
tree sequence, but these trees may not have had sufficient time to
reach a most recent common ancestor. By using the ``from_ts`` argument
to :func:`.simulate` we can combine the best of both forwards- and
backwards-time simulators. The recent past can be simulated forwards
in time and the ancient past by the coalescent. The coalescent
simulation is initialised by the root segments of the
input tree sequence, ensuring that the minimal amount of ancestral
material possible is simulated.

Please see the :ref:`tutorial <sec_tutorial_simulate_from>` for an example of how to use this
feature with a simple forwards-time Wright-Fisher simulator

------------------
Input requirements
------------------

Any tree sequence can be provided as input to this process, but there is a
specific topological requirement that must be met for the simulations to be
statistically correct. To ensure that ancestral segments are correctly associated within chromosomes
when constructing the initial conditions for the coalescent simulation,
forward-time simulators **must** retain the nodes corresponding to the
initial generation. Furthermore, for every sample in the final generation
(i.e. the extant population at the present time) there must be a path
to one of the founder population nodes. (Please see the :ref:`tutorial <sec_tutorial_simulate_from>`
for further explanation of this point and an example.)

-----------------------------
Recombination map limitations
-----------------------------

Because of the way that ``msprime`` handles recombination internally, care must
be taken when specifying recombination when using the ``from_ts`` argument.
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`` use::

L = int(from_ts.sequence_length)
recomb_map = msprime.RecombinationMap.uniform_map(L, r, L)
final_ts = mpsrime.simulate(from_ts=from_ts, recomb_map=recomb_map)


++++++++++++++++++++
Simulating mutations
++++++++++++++++++++
Expand Down
82 changes: 81 additions & 1 deletion docs/examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import matplotlib.pyplot as pyplot
import matplotlib.collections

import random
import tqdm
import threading

Expand Down Expand Up @@ -338,17 +339,96 @@ def historical_samples_example():
for u in range(tree_seq.get_num_nodes()):
print(u, tree.get_parent(u), tree.get_time(u), sep="\t")


def wright_fisher(N, T, L=100, random_seed=None):
"""
Simulate a Wright-Fisher population of N haploid individuals with L
discrete loci for T generations. Based on Algorithm W from
https://www.biorxiv.org/content/biorxiv/early/2018/01/16/248500.full.pdf
"""
random.seed(random_seed)
tables = msprime.TableCollection(L)
P = np.arange(N, dtype=int)
# Mark the initial generation as samples so that we remember these nodes.
for j in range(N):
tables.nodes.add_row(time=T, flags=msprime.NODE_IS_SAMPLE)
t = T
while t > 0:
t -= 1
Pp = P.copy()
for j in range(N):
u = tables.nodes.add_row(time=t, flags=0)
Pp[j] = u
a = random.randint(0, N - 1)
b = random.randint(0, N - 1)
x = random.randint(1, L - 1)
tables.edges.add_row(0, x, P[a], u)
tables.edges.add_row(x, L, P[b], u)
P = Pp

# Now do some table manipulations to ensure that the tree sequence
# that we output has the form that msprime needs to finish the
# simulation. Much of the complexity here is caused by the tables API
# not allowing direct access to memory, which will change soon.

# Mark the extant population as samples also
flags = tables.nodes.flags
flags[P] = msprime.NODE_IS_SAMPLE
tables.nodes.set_columns(flags=flags, time=tables.nodes.time)
tables.sort()
# Simplify with respect to the current generation, but ensuring we keep the
# ancient nodes from the initial population.
tables.simplify()
# Unmark the initial generation as samples
flags = tables.nodes.flags
time = tables.nodes.time
flags[:] = 0
flags[time == 0] = msprime.NODE_IS_SAMPLE
# The final tables must also have at least one population which
# the samples are assigned to
tables.populations.add_row()
tables.nodes.set_columns(
flags=flags, time=time,
population=np.zeros_like(tables.nodes.population))
return tables.tree_sequence()


def simulate_from_example():

num_loci = 2
wf_ts = wright_fisher(10, 5, L=num_loci, random_seed=3)
for tree in wf_ts.trees():
tree.draw(path="_static/simulate_from_wf_{}.svg".format(tree.index))

recomb_map = msprime.RecombinationMap.uniform_map(num_loci, 1, num_loci)
coalesced_ts = msprime.simulate(
from_ts=wf_ts, recombination_map=recomb_map, random_seed=5)

for tree in coalesced_ts.trees():
tree.draw(path="_static/simulate_from_coalesced_{}.svg".format(tree.index))

final_ts = coalesced_ts.simplify()

for tree in final_ts.trees():
print("interval = ", tree.interval)
print(tree.draw(format="unicode"))





if __name__ == "__main__":
# single_locus_example()
# multi_locus_example()
# mutations_example()
# set_mutations_example()
# variants_example()
# variant_matrix_example()
historical_samples_example()
# historical_samples_example()
# segregating_sites_example(10, 5, 100000)
# migration_example()
# out_of_africa()
# variable_recomb_example()
# ld_matrix_example()
# threads_example()
simulate_from_example()
Loading