forked from tskit-dev/msprime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithms.py
2201 lines (2008 loc) · 80.5 KB
/
algorithms.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Python version of the simulation algorithm.
"""
import sys
import random
import argparse
import heapq
import math
import numpy as np
import bintrees
import msprime
import tskit
class FenwickTree(object):
"""
A Fenwick Tree to represent cumulative frequency tables over
integers. Each index from 1 to max_index initially has a
zero frequency.
This is an implementation of the Fenwick tree (also known as a Binary
Indexed Tree) based on "A new data structure for cumulative frequency
tables", Software Practice and Experience, Vol 24, No 3, pp 327 336 Mar
1994. This implementation supports any non-negative frequencies, and the
search procedure always returns the smallest index such that its cumulative
frequency <= f. This search procedure is a slightly modified version of
that presented in Tech Report 110, "A new data structure for cumulative
frequency tables: an improved frequency-to-symbol algorithm." available at
https://www.cs.auckland.ac.nz/~peter-f/FTPfiles/TechRep110.ps
"""
def __init__(self, max_index):
assert max_index > 0
self.__max_index = max_index
self.__tree = [0 for j in range(max_index + 1)]
# Compute the binary logarithm of max_index
u = self.__max_index
while u != 0:
self.__log_max_index = u
u -= (u & -u)
def get_total(self):
"""
Returns the total cumulative frequency over all indexes.
"""
return self.get_cumulative_frequency(self.__max_index)
def increment(self, index, v):
"""
Increments the frequency of the specified index by the specified
value.
"""
assert 0 < index <= self.__max_index
j = index
while j <= self.__max_index:
self.__tree[j] += v
j += (j & -j)
def set_value(self, index, v):
"""
Sets the frequency at the specified index to the specified value.
"""
f = self.get_frequency(index)
self.increment(index, v - f)
def get_cumulative_frequency(self, index):
"""
Returns the cumulative frequency of the specified index.
"""
assert 0 < index <= self.__max_index
j = index
s = 0
while j > 0:
s += self.__tree[j]
j -= (j & -j)
return s
def get_frequency(self, index):
"""
Returns the frequency of the specified index.
"""
assert 0 < index <= self.__max_index
j = index
v = self.__tree[j]
p = j & (j - 1)
j -= 1
while p != j:
v -= self.__tree[j]
j = j & (j - 1)
return v
def find(self, v):
"""
Returns the smallest index with cumulative sum >= v.
"""
j = 0
s = v
half = self.__log_max_index
while half > 0:
# Skip non-existant entries
while j + half > self.__max_index:
half >>= 1
k = j + half
if s > self.__tree[k]:
j = k
s -= self.__tree[j]
half >>= 1
return j + 1
class Segment(object):
"""
A class representing a single segment. Each segment has a left
and right, denoting the loci over which it spans, a node and a
next, giving the next in the chain.
"""
def __init__(self, index):
self.left = None
self.right = None
self.left_mass = None
self.right_mass = None
self.node = None
self.prev = None
self.next = None
self.population = None
self.label = 0
self.index = index
def __str__(self):
s = "({}:{}-{}->{}: prev={} next={})".format(
self.index, self.left, self.right, self.node, repr(self.prev),
repr(self.next))
return s
def __lt__(self, other):
return ((self.left, self.right, self.population, self.node)
< (other.left, other.right, other.population, self.node))
class Population(object):
"""
Class representing a population in the simulation.
"""
def __init__(self, id_, num_labels=1):
self._id = id_
self._start_time = 0
self._start_size = 1.0
self._growth_rate = 0
# Keep a list of each label.
# We'd like to use AVLTrees here for P but the API doesn't quite
# do what we need. Lists are inefficient here and should not be
# used in a real implementation.
self._ancestors = [[] for _ in range(num_labels)]
def print_state(self):
print("Population ", self._id)
print("\tstart_size = ", self._start_size)
print("\tgrowth_rate = ", self._growth_rate)
print("\tAncestors: ", len(self._ancestors))
for label, ancestors in enumerate(self._ancestors):
print("\tLabel = ", label)
for u in ancestors:
s = ""
while u is not None:
s += "({}-{}->{}({});lab:{})".format(
u.left, u.right, u.node, u.index, u.label)
u = u.next
print("\t\t" + s)
def get_cleft(self, tracklength):
cleft = 0
for ancestors in self._ancestors:
for u in ancestors:
left = u.left
while u.next is not None:
u = u.next
right = u.right
dist = right - left
cleft += 1 - ((tracklength-1) / tracklength) ** (dist - 1)
return cleft
def find_cleft(self, rvalue, tracklength):
for ancestors in self._ancestors:
for u in ancestors:
left = u.left
index = u.index
while u.next is not None:
u = u.next
right = u.right
dist = right - left
rvalue -= 1 - ((tracklength-1)/tracklength) ** (dist - 1)
if rvalue <= 0:
break
return rvalue, index, dist
def set_growth_rate(self, growth_rate, time):
# TODO This doesn't work because we need to know what the time
# is so we can set the start size accordingly. Need to look at
# ms's model carefully to see what it actually does here.
new_size = self.get_size(time)
self._start_size = new_size
self._start_time = time
self._growth_rate = growth_rate
def set_start_size(self, start_size):
self._start_size = start_size
self._growth_rate = 0
def get_num_ancestors(self, label=None):
if label is None:
return sum(len(label_ancestors) for label_ancestors in self._ancestors)
else:
return len(self._ancestors[label])
def get_size(self, t):
"""
Returns the size of this population at time t.
"""
dt = t - self._start_time
return self._start_size * math.exp(-self._growth_rate * dt)
def get_common_ancestor_waiting_time(self, t):
"""
Returns the random waiting time until a common ancestor event
occurs within this population.
"""
ret = sys.float_info.max
k = self.get_num_ancestors()
if k > 1:
u = random.expovariate(k * (k - 1))
if self._growth_rate == 0:
ret = self._start_size * u
else:
dt = t - self._start_time
z = (
1 + self._growth_rate * self._start_size
* math.exp(-self._growth_rate * dt) * u)
if z > 0:
ret = math.log(z) / self._growth_rate
return ret
def get_ind_range(self, t):
""" Returns ind labels at time t """
first_ind = np.sum([self.get_size(t_prev) for t_prev in range(0, t)])
last_ind = first_ind + self.get_size(t)
return range(int(first_ind), int(last_ind)+1)
def remove(self, index, label=0):
"""
Removes and returns the individual at the specified index.
"""
return self._ancestors[label].pop(index)
def remove_individual(self, individual, label=0):
"""
Removes the given individual from its population.
"""
return self._ancestors[label].remove(individual)
def add(self, individual, label=0):
"""
Inserts the specified individual into this population.
"""
self._ancestors[label].append(individual)
def __iter__(self):
# will default to label 0
# inter_label() extends behavior
return iter(self._ancestors[0])
def iter_label(self, label):
"""
Iterates ancestors in popn from a label
"""
return iter(self._ancestors[label])
def iter_ancestors(self):
"""
Iterates over all ancestors in a population.
"""
for ancestors in self._ancestors:
for ancestor in ancestors:
yield ancestor
def find_indv(self, indv):
"""
find the index of an ancestor in population
"""
return self._ancestors[indv.label].index(indv)
class Pedigree(object):
"""
Class representing a pedigree for use with the DTWF model, as implemented
in C library
"""
def __init__(self, num_individuals, ploidy):
self.ploidy = ploidy
self.num_individuals = num_individuals
self.inds = []
self.samples = []
self.num_samples = 0
self.ind_heap = []
self.is_climbing = False
# Stores most recently merged segment
self.merged_segment = None
def set_pedigree(self, inds, parents, times, is_sample):
self.ploidy = parents.shape[1]
self.inds = [Individual(ploidy=self.ploidy)
for i in range(self.num_individuals)]
num_samples = 0
for i in range(self.num_individuals):
ind = self.inds[i]
ind.id = inds[i]
assert ind.id > 0
ind.time = times[i]
for j, parent in enumerate(parents[i]):
if parent != tskit.NULL:
assert(parent >= 0)
ind.parents[j] = self.inds[parent]
if is_sample[i] != 0:
assert is_sample[i] == 1
self.samples.append(ind)
num_samples += 1
self.num_samples = num_samples
def load_pop(self, pop):
"""
Loads segments from a given pop into the pedigree samples
"""
if self.num_sample_lineages() != pop.get_num_ancestors():
err_str = "Ped samples: " + str(self.num_sample_lineages()) + \
" Samples: " + str(pop.get_num_ancestors()) + \
" - must be equal!"
raise ValueError(err_str)
# for i, anc in enumerate(pop):
for i in range(pop.get_num_ancestors()-1, -1, -1):
anc = pop.remove(i)
# Each individual gets 'ploidy' lineages
ind = self.samples[i // self.ploidy]
parent_ix = i % self.ploidy
ind.add_segment(anc, parent_ix=parent_ix)
# Add samples to queue to prepare for climbing - might be better if
# included in previous loop
for ind in self.samples:
self.push_ind(ind)
def assign_times(self, check=False):
"""
For pedigrees without specified times, crudely assigns times to
all individuals.
"""
if len(self.samples) == 0:
self.set_samples()
assert len(self.samples) > 0
climbers = [s for s in self.samples]
t = 0
while len(climbers) > 0:
next_climbers = []
for climber in climbers:
if climber.time < t:
climber.time = t
for parent in climber.parents:
if parent is not None:
next_climbers.append(parent)
climbers = next_climbers
t += 1
if check:
for ind in self.inds:
for parent in ind.parents:
if parent is not None:
assert ind.time < parent.time
def build_ind_queue(self):
"""
Set up heap queue of samples, so most recent can be popped for merge.
Heapify in case samples are not all at t=0.
"""
self.ind_heap = [(ind.time, ind) for ind in self.samples]
heapq.heapify(self.ind_heap)
def push_ind(self, ind):
"""
Adds an individual to the heap queue
"""
assert ind.queued is False
ind.queued = True
heapq.heappush(self.ind_heap, ind)
def pop_ind(self):
"""
Pops the most recent individual off the heap queue
"""
ind = heapq.heappop(self.ind_heap)
assert ind.queued
ind.queued = False
return ind
def num_sample_lineages(self):
return len(self.samples) * self.ploidy
def print_samples(self):
for s in self.samples:
print(s)
class Individual(object):
"""
Class representing a diploid individual in the DTWF model. Trying to make
arbitrary ploidy possible at some point in the future.
"""
def __init__(self, ploidy=2):
self.id = None # This is the index of the individual in pedigree.inds
self.ploidy = ploidy
self.parents = [None for i in range(ploidy)]
self.segments = [[] for i in range(ploidy)]
self.sex = None
self.time = -1
self.queued = False
# For debugging - to ensure we only merge once
self.merged = False
def __str__(self):
parents = []
for p in self.parents:
if p is not None:
parents.append(str(p.id))
else:
parents.append("None")
parents_str = ",".join(parents)
return "(ID: {}, time: {}, parents: {})".format(
self.id, self.time, parents_str)
def __repr__(self):
return self.__str__()
def __lt__(self, other):
return self.time < other.time
def add_segment(self, seg, parent_ix):
"""
Adds a segment to a parental segment heap, which allows easy merging
later.
"""
heapq.heappush(self.segments[parent_ix], (seg.left, seg))
def num_lineages(self):
return sum([len(s) for s in self.segments])
class TrajectorySimulator(object):
"""
Class to simulate an allele frequency trajectory on which to condition
the coalescent simulation.
"""
def __init__(self, initial_freq, end_freq, alpha, time_slice):
self._initial_freq = initial_freq
self._end_freq = end_freq
self._alpha = alpha
self._time_slice = time_slice
self._reset()
def _reset(self):
self._allele_freqs = []
self._times = []
def _genic_selection_stochastic_forwards(self, dt, freq, alpha):
ux = (alpha * freq * (1 - freq)) / np.tanh(alpha * freq)
sign = 1 if random.random() < 0.5 else -1
freq += (ux * dt) + sign * np.sqrt(freq * (1.0 - freq) * dt)
return freq
def _simulate(self):
"""
Proposes a sweep trajectory and returns the acceptance probability.
"""
x = self._end_freq # backward time
current_size = 1
t_inc = self._time_slice
t = 0
while x > self._initial_freq:
# print("x: ",x)
self._allele_freqs.append(max(x, self._initial_freq))
self._times.append(t)
# just a note below
# current_size = self._size_calculator(t)
#
x = 1.0 - self._genic_selection_stochastic_forwards(
t_inc, 1.0 - x, self._alpha * current_size)
t += self._time_slice
# will want to return current_size / N_max
# for prototype this always equals 1
return 1
def run(self):
while random.random() > self._simulate():
self.reset()
return self._allele_freqs, self._times
class RecombinationMap(object):
def __init__(self, positions, rates, discrete):
self.positions = positions
self.rates = rates
self.discrete = discrete
self.cumulative = RecombinationMap.recomb_mass(positions, rates)
@staticmethod
def recomb_mass(positions, rates):
recomb_mass = 0
cumulative = [recomb_mass]
for i in range(1, len(positions)):
recomb_mass += (positions[i] - positions[i-1]) * rates[i-1]
cumulative.append(recomb_mass)
return cumulative
@property
def total_recombination_rate(self):
return self.cumulative[-1]
def mass_between(self, left, right):
left_mass = self.position_to_mass(left)
right_mass = self.position_to_mass(right)
return right_mass - left_mass
def mass_between_left_exclusive(self, left, right):
left_bound = left + 1 if self.discrete else left
return self.mass_between(left_bound, right)
def position_to_mass(self, pos):
if pos == self.positions[0]:
return 0
if pos >= self.positions[-1]:
return self.cumulative[-1]
index = self._search(self.positions, pos)
assert index > 0
index -= 1
offset = pos - self.positions[index]
return self.cumulative[index] + offset * self.rates[index]
def mass_to_position(self, recomb_mass):
if recomb_mass == 0:
return 0
index = self._search(self.cumulative, recomb_mass)
assert index > 0
index -= 1
mass_in_interval = recomb_mass - self.cumulative[index]
pos = self.positions[index] + (mass_in_interval / self.rates[index])
return math.floor(pos) if self.discrete else pos
def shift_by_mass(self, pos, mass):
result_mass = self.position_to_mass(pos) + mass
return self.mass_to_position(result_mass)
def sample_poisson(self, start):
left_bound = start + 1 if self.discrete else start
mass_to_next_recomb = np.random.exponential(1.0)
return self.shift_by_mass(left_bound, mass_to_next_recomb)
def _search(self, values, query):
left = 0
right = len(values) - 1
while left < right:
m = (left + right) // 2
if values[m] < query:
left = m + 1
else:
right = m
return left
class OverlapCounter(object):
def __init__(self, seq_length):
self.seq_length = seq_length
self.overlaps = self._make_segment(0, seq_length, 0)
def overlaps_at(self, pos):
assert 0 <= pos < self.seq_length
curr_interval = self.overlaps
while curr_interval is not None:
if curr_interval.left <= pos < curr_interval.right:
return curr_interval.node
curr_interval = curr_interval.next
raise ValueError("Bad overlap count chain")
def increment_interval(self, left, right):
"""
Increment the count that spans the interval
[left, right), creating additional intervals in overlaps
if necessary.
"""
curr_interval = self.overlaps
while left < right:
if curr_interval.left == left:
if curr_interval.right <= right:
curr_interval.node += 1
left = curr_interval.right
curr_interval = curr_interval.next
else:
self._split(curr_interval, right)
curr_interval.node += 1
break
else:
if curr_interval.right < left:
curr_interval = curr_interval.next
else:
self._split(curr_interval, left)
curr_interval = curr_interval.next
def _split(self, seg, breakpoint):
"""
Split the segment at breakpoint and add in another segment
from breakpoint to seg.right. Set the original segment's
right endpoint to breakpoint
"""
right = self._make_segment(breakpoint, seg.right, seg.node)
if seg.next is not None:
seg.next.prev = right
right.next = seg.next
right.prev = seg
seg.next = right
seg.right = breakpoint
def _make_segment(self, left, right, count):
seg = Segment(0)
seg.left = left
seg.right = right
seg.node = count
return seg
class Simulator(object):
"""
A reference implementation of the multi locus simulation algorithm.
"""
def __init__(
self, sample_size, num_loci, recombination_rate, recombination_map,
migration_matrix,
sample_configuration, population_growth_rates, population_sizes,
population_growth_rate_changes, population_size_changes,
migration_matrix_element_changes, bottlenecks, census_times,
model='hudson', from_ts=None, max_segments=100, num_labels=1,
sweep_trajectory=None, full_arg=False, time_slice=None,
gene_conversion_rate=0.0, gene_conversion_length=1, pedigree=None):
# Must be a square matrix.
N = len(migration_matrix)
assert len(sample_configuration) == N
assert len(population_growth_rates) == N
assert len(population_sizes) == N
for j in range(N):
assert N == len(migration_matrix[j])
assert migration_matrix[j][j] == 0
assert sum(sample_configuration) == sample_size
self.model = model
self.n = sample_size
self.m = num_loci
self.recomb_map = recombination_map
self.g = gene_conversion_rate
self.tracklength = gene_conversion_length
self.pc = (self.tracklength-1)/self.tracklength
if self.tracklength == 1:
self.lnpc = -math.inf
else:
self.lnpc = math.log(1.0-1.0/self.tracklength)
self.migration_matrix = migration_matrix
self.num_labels = num_labels
self.num_populations = N
self.max_segments = max_segments
self.full_arg = full_arg
self.segment_stack = []
self.segments = [None for j in range(self.max_segments + 1)]
for j in range(self.max_segments):
s = Segment(j + 1)
self.segments[j + 1] = s
self.segment_stack.append(s)
self.P = [Population(id_, num_labels) for id_ in range(N)]
self.L = [FenwickTree(self.max_segments) for j in range(num_labels)]
self.S = bintrees.AVLTree()
for pop_index in range(N):
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
self.pedigree = pedigree
if from_ts is None:
self.tables = msprime.TableCollection(sequence_length=num_loci)
for pop_index in range(N):
self.tables.populations.add_row()
sample_size = sample_configuration[pop_index]
for k in range(sample_size):
j = len(self.tables.nodes)
x = self.alloc_segment(
0, self.m, 0,
self.recomb_map.position_to_mass(self.m),
j, pop_index)
self.set_single_segment_mass(x)
self.P[pop_index].add(x)
self.tables.nodes.add_row(
flags=msprime.NODE_IS_SAMPLE,
time=0,
population=pop_index)
j += 1
self.S[0] = self.n
self.S[self.m] = -1
self.t = 0
else:
ts = msprime.load(from_ts)
if ts.sequence_length != self.m:
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.initialise_from_ts(ts)
if pedigree is not None:
assert N == 1 # <- only support single pop/pedigree for now
pop = self.P[0]
pedigree.load_pop(pop)
self.num_ca_events = 0
self.num_re_events = 0
self.num_gc_events = 0
# Sweep variables
self.sweep_site = (self.m // 2) - 1 # need to add options here
self.sweep_trajectory = sweep_trajectory
self.time_slice = time_slice
self.modifier_events = [(sys.float_info.max, None, None)]
for time, pop_id, new_size in population_size_changes:
self.modifier_events.append(
(time, self.change_population_size, (int(pop_id), new_size)))
for time, pop_id, new_rate in population_growth_rate_changes:
self.modifier_events.append(
(time, self.change_population_growth_rate,
(int(pop_id), new_rate, time)))
for time, pop_i, pop_j, new_rate in migration_matrix_element_changes:
self.modifier_events.append(
(time, self.change_migration_matrix_element,
(int(pop_i), int(pop_j), new_rate)))
for time, pop_id, intensity in bottlenecks:
self.modifier_events.append(
(time, self.bottleneck_event, (int(pop_id), 0, intensity)))
for time in census_times:
self.modifier_events.append((time[0], self.census_event, time))
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,
self.recomb_map.position_to_mass(left),
self.recomb_map.position_to_mass(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,
self.recomb_map.position_to_mass(left),
self.recomb_map.position_to_mass(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 ancestors_remain(self):
"""
Returns True if the simulation is not finished, i.e., there is some ancestral
material that has not fully coalesced.
"""
return sum(pop.get_num_ancestors() for pop in self.P) != 0
def change_population_size(self, pop_id, size):
print("Changing pop size to ", size)
for i in range(self.num_labels):
self.P[i][pop_id].set_start_size(size)
def change_population_growth_rate(self, pop_id, rate, time):
print("Changing growth rate to ", rate)
for i in range(self.num_labels):
self.P[i][pop_id].set_growth_rate(rate, time)
def change_migration_matrix_element(self, pop_i, pop_j, rate):
print("Changing migration rate", pop_i, pop_j, rate)
self.migration_matrix[pop_i][pop_j] = rate
def get_cleft_total(self, tracklength):
cleft = 0
for pop in self.P:
cleft += pop.get_cleft(tracklength)
return cleft
def find_cleft_individual(self, rvalue, tracklength):
for pop in self.P:
if rvalue > 0:
rvalue, index, distance = pop.find_cleft(rvalue, tracklength)
return index, distance
def alloc_segment(
self, left, right,
left_mass, right_mass, node,
pop_index, prev=None, next=None):
"""
Pops a new segment off the stack and sets its properties.
"""
s = self.segment_stack.pop()
s.left = left
s.right = right
s.left_mass = left_mass
s.right_mass = right_mass
s.node = node
s.population = pop_index
s.next = next
s.prev = prev
s.label = 0
return s
def free_segment(self, u):
"""
Frees the specified segment making it ready for reuse and
setting its weight to zero.
"""
self.L[u.label].set_value(u.index, 0)
self.segment_stack.append(u)
def store_node(self, population, flags=0):
self.flush_edges()
self.tables.nodes.add_row(time=self.t, flags=flags, population=population)
def flush_edges(self):
"""
Flushes the edges in the edge buffer to the table, squashing any adjacent edges.
"""
if len(self.edge_buffer) > 0:
parent = len(self.tables.nodes) - 1
self.edge_buffer.sort(key=lambda e: (e.child, e.left))
left = self.edge_buffer[0].left
right = self.edge_buffer[0].right
child = self.edge_buffer[0].child
assert self.edge_buffer[0].parent == parent
for e in self.edge_buffer[1:]:
assert e.parent == parent
if e.left != right or e.child != child:
self.tables.edges.add_row(left, right, parent, child)
left = e.left
child = e.child
right = e.right
self.tables.edges.add_row(left, right, parent, child)
self.edge_buffer = []
def store_edge(self, left, right, parent, child):
"""
Stores the specified edge to the output tree sequence.
"""
self.edge_buffer.append(
msprime.Edge(left=left, right=right, parent=parent, child=child))
def finalise(self):
"""
Finalises the simulation returns an msprime tree sequence object.
"""
self.flush_edges()
ts = self.tables.tree_sequence()
return ts
def simulate(self, model='hudson'):
if self.model == 'hudson':
self.hudson_simulate()
elif self.model == 'dtwf':
self.dtwf_simulate()
elif self.model == 'wf_ped':
self.pedigree_simulate()
elif self.model == 'single_sweep':
# self.print_state()
self.single_sweep_simulate()
else:
print("Error: bad model specification -", self.model)
raise ValueError
return self.finalise()
def hudson_simulate(self):
"""
Simulates the algorithm until all loci have coalesced.
"""
infinity = sys.float_info.max
# only worried about label 0 below
while self.ancestors_remain():
self.verify()
recomb_mass = self.L[0].get_total()
rate = recomb_mass
t_re = infinity
if rate != 0:
t_re = random.expovariate(rate)
# Gene conversion can occur within segments ..
rate = self.g * self.recomb_map.mass_to_position(recomb_mass)
t_gcin = infinity
if rate != 0:
t_gcin = random.expovariate(rate)
# .. or left of the first segment
cleft = self.get_cleft_total(self.tracklength)
assert cleft <= sum(pop.get_num_ancestors() for pop in self.P)
rate = self.g * self.tracklength * cleft
t_gcleft = infinity
if rate != 0:
t_gcleft = random.expovariate(rate)
# Common ancestor events occur within demes.
t_ca = infinity
for index, pop in enumerate(self.P):
t = pop.get_common_ancestor_waiting_time(self.t)
if t < t_ca:
t_ca = t
ca_population = index
t_mig = infinity
# Migration events happen at the rates in the matrix.
for j in range(len(self.P)):
source_size = self.P[j].get_num_ancestors()
for k in range(len(self.P)):
rate = source_size * self.migration_matrix[j][k]
if rate > 0:
t = random.expovariate(rate)
if t < t_mig:
t_mig = t
mig_source = j
mig_dest = k
min_time = min(t_re, t_ca, t_gcin, t_gcleft, t_mig)
assert min_time != infinity
if self.t + min_time > self.modifier_events[0][0]:
t, func, args = self.modifier_events.pop(0)
self.t = t
func(*args)
else:
self.t += min_time
if min_time == t_re:
# print("RE EVENT")
self.hudson_recombination_event(0)
elif min_time == t_gcin:
# print("GCI EVENT")
self.wiuf_geneconversion_within_event(0)
elif min_time == t_gcleft:
# print("GCL EVENT")
self.wiuf_geneconversion_left_event(0)
elif min_time == t_ca:
# print("CA EVENT")
self.common_ancestor_event(ca_population, 0)
else:
# print("MIG EVENT")
self.migration_event(mig_source, mig_dest)