-
Notifications
You must be signed in to change notification settings - Fork 2
/
hgt_simulation.py
3615 lines (3237 loc) · 130 KB
/
hgt_simulation.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.
Based on https://github.com/tskit-dev/msprime/blob/main/algorithms.py
Modified to support HGT and Tree Fixation.
"""
import argparse
import heapq
import itertools
import logging
import math
import random
import bintrees
import daiquiri
import numpy as np
import tskit
import msprime
import sys
logger = daiquiri.getLogger()
class FenwickTree:
"""
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)]
self.__value = [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_sum(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
self.__value[index] += v
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_value(index)
self.increment(index, v - f)
def get_cumulative_sum(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_value(self, index):
"""
Returns the frequency of the specified index.
"""
return self.__value[index]
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:
"""
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.node = None
self.prev = None
self.next = None
self.population = None
self.label = 0
self.index = index
self.hull = None
self.origin = set()
def __repr__(self):
return repr((self.left, self.right, self.node, self.origin))
@staticmethod
def show_chain(seg):
s = ""
while seg is not None:
s += f"[{seg.left}, {seg.right}: {seg.node}, {seg.origin}], "
seg = seg.next
return s[:-2]
def __lt__(self, other):
return (self.left, self.right, self.population, self.node) < (
other.left,
other.right,
other.population,
self.node,
)
def get_hull(self):
seg = self
assert seg is not None
while seg.prev is not None:
seg = seg.prev
hull = seg.hull
return hull
def get_left_index(self):
seg = self
while seg is not None:
index = seg.index
seg = seg.prev
return index
class Population:
"""
Class representing a population in the simulation.
"""
def __init__(self, id_, num_labels=1, max_segments=100, model="hudson"):
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)]
# ADDITIONAL STATES FOR SMC(k)
# this has to be done for each label
# track hulls based on left
self.hulls_left = [OrderStatisticsTree() for _ in range(num_labels)]
self.coal_mass_index = [FenwickTree(max_segments) for j in range(num_labels)]
# track rank of hulls right
self.hulls_right = [OrderStatisticsTree() for _ in range(num_labels)]
if model == "smc_k":
self.get_common_ancestor_waiting_time = self.get_common_ancestor_waiting_time_smc_k()
else:
self.get_common_ancestor_waiting_time = self.get_common_ancestor_waiting_time_hudson()
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:
print("\t\t" + Segment.show_chain(u))
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_num_pairs(self, label=None):
# can be improved by updating values in self.num_pairs
if label is None:
return sum(mass_index.get_total() for mass_index in self.coal_mass_index)
else:
return self.coal_mass_index[label].get_total()
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, np, t):
"""
Returns the random waiting time until a common ancestor event
occurs within this population.
"""
ret = sys.float_info.max
u = random.expovariate(2 * np)
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_common_ancestor_waiting_time_hudson(self):
def _get_common_ancestor_waiting_time_hudson(t):
k = self.get_num_ancestors()
ret = sys.float_info.max
if k > 1:
np = k * (k - 1) / 2
ret = self._get_common_ancestor_waiting_time(np, t)
return ret
return _get_common_ancestor_waiting_time_hudson
def get_common_ancestor_waiting_time_smc_k(self):
def _get_common_ancestor_waiting_time_smc_k(t):
np = self.get_num_pairs()
ret = sys.float_info.max
if np > 0:
ret = self._get_common_ancestor_waiting_time(np, t)
return ret
return _get_common_ancestor_waiting_time_smc_k
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, int(t))])
last_ind = first_ind + self.get_size(t)
return range(int(first_ind), int(last_ind) + 1)
def increment_avl(self, ost, coal_mass, hull, increment):
right = hull.right
curr_hull = hull
curr_hull, _ = ost.succ_key(curr_hull)
while curr_hull is not None:
if right > curr_hull.left:
ost.avl[curr_hull] += increment
coal_mass.increment(curr_hull.index, increment)
else:
break
curr_hull, _ = ost.succ_key(curr_hull)
def reset_hull_right(self, label, hull, old_right, new_right):
# when resetting the hull.right of a pre-existing hull we need to
# decrement count of all lineages starting off between hull.left and bp
# FIX: logic is almost identical to increment_avl()!!!
ost = self.hulls_left[label]
curr_hull = Hull(-1)
curr_hull.left = new_right
curr_hull.right = math.inf
curr_hull.insertion_order = 0
floor = ost.floor_key(curr_hull)
curr_hull = floor
while curr_hull is not None:
if curr_hull.left >= old_right:
break
if curr_hull.left >= new_right:
ost.avl[curr_hull] -= 1
self.coal_mass_index[label].increment(curr_hull.index, -1)
curr_hull, _ = ost.succ_key(curr_hull)
hull.right = new_right
# adjust rank of hull.right
ost = self.hulls_right[label]
floor = ost.floor_key(HullEnd(old_right))
assert floor.x == old_right
ost.pop(floor)
insertion_order = 0
hull_end = HullEnd(new_right)
floor = ost.floor_key(hull_end)
if floor is not None:
if floor.x == hull_end.x:
insertion_order = floor.insertion_order + 1
hull_end.insertion_order = insertion_order
ost[hull_end] = 0
def remove_hull(self, label, hull):
ost = self.hulls_left[label]
coal_mass_index = self.coal_mass_index[label]
self.increment_avl(ost, coal_mass_index, hull, -1)
# adjust insertion order
curr_hull, _ = ost.succ_key(hull)
count, left_rank = ost.pop(hull)
while curr_hull is not None:
if curr_hull.left == hull.left:
curr_hull.insertion_order -= 1
else:
break
curr_hull, _ = ost.succ_key(curr_hull)
ost = self.hulls_right[label]
floor = ost.floor_key(HullEnd(hull.right))
assert floor.x == hull.right
_, right_rank = ost.pop(floor)
hull.insertion_order = math.inf
self.coal_mass_index[label].set_value(hull.index, 0)
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_hull(self, label, hull):
# logic left end
ost_left = self.hulls_left[label]
ost_right = self.hulls_right[label]
insertion_order = 0
num_starting_after_left = 0
num_ending_before_left = 0
floor = ost_left.floor_key(hull)
if floor is not None:
if floor.left == hull.left:
insertion_order = floor.insertion_order + 1
num_starting_after_left = ost_left.get_rank(floor) + 1
hull.insertion_order = insertion_order
floor = ost_right.floor_key(HullEnd(hull.left))
if floor is not None:
num_ending_before_left = ost_right.get_rank(floor) + 1
count = num_starting_after_left - num_ending_before_left
ost_left[hull] = count
self.coal_mass_index[label].set_value(hull.index, count)
# logic right end
insertion_order = 0
hull_end = HullEnd(hull.right)
floor = ost_right.floor_key(hull_end)
if floor is not None:
if floor.x == hull.right:
insertion_order = floor.insertion_order + 1
hull_end.insertion_order = insertion_order
ost_right[hull_end] = 0
# self.num_pairs[label] += count - correction
# Adjust counts for existing hulls in the avl tree
coal_mass_index = self.coal_mass_index[label]
self.increment_avl(ost_left, coal_mass_index, hull, 1)
def add(self, individual, label=0):
"""
Inserts the specified individual into this population.
"""
assert individual.label == label
self._ancestors[label].append(individual)
def __iter__(self):
# will default to label 0
# iter_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 over all labels.
"""
for ancestors in self._ancestors:
yield from ancestors
def find_indv(self, indv):
"""
find the index of an ancestor in population
"""
return self._ancestors[indv.label].index(indv)
def get_emerged_from_lineage(self, index, label):
"""
Returns the indices of lineages that emerged from a given one.
"""
return [i for i, s in enumerate(self._ancestors[label]) if index.issubset(s.origin)]
class Pedigree:
"""
Class representing a pedigree for use with the DTWF model, as implemented
in C library
"""
def __init__(self, tables):
self.ploidy = 2
self.individuals = []
ts = tables.tree_sequence()
for tsk_ind in ts.individuals():
assert len(tsk_ind.nodes) == self.ploidy
assert len(tsk_ind.parents) == self.ploidy
time = ts.node(tsk_ind.nodes[0]).time
# All nodes must be equivalent
assert len({ts.node(node).flags for node in tsk_ind.nodes}) == 1
assert len({ts.node(node).time for node in tsk_ind.nodes}) == 1
assert len({ts.node(node).population for node in tsk_ind.nodes}) == 1
ind = Individual(
tsk_ind.id,
ploidy=self.ploidy,
nodes=list(tsk_ind.nodes),
parents=list(tsk_ind.parents),
time=time,
)
assert ind.id == len(self.individuals)
self.individuals.append(ind)
def print_state(self):
print("Pedigree")
print("-------")
print("Individuals = ")
for ind in self.individuals:
print("\t", ind)
print("-------")
class Individual:
"""
Class representing a diploid individual in the DTWF pedigree model.
"""
def __init__(self, id_, *, ploidy, nodes, parents, time):
self.id = id_
self.ploidy = ploidy
self.nodes = nodes
self.parents = parents
self.time = time
self.common_ancestors = [[] for i in range(ploidy)]
def __str__(self):
return (
f"(ID: {self.id}, time: {self.time}, "
+ f"parents: {self.parents}, nodes: {self.nodes}, "
+ f"common_ancestors: {self.common_ancestors})"
)
def add_common_ancestor(self, head, ploid):
"""
Adds the specified ancestor (represented by the head of a segment
chain) to the list of ancestors that find a common ancestor in
the specified ploid of this individual.
"""
heapq.heappush(self.common_ancestors[ploid], (head.left, head))
class TrajectorySimulator:
"""
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:
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 RateMap:
def __init__(self, positions, rates):
"""
# For gene conversion:
positions = [0, sequence_length]
rates = [gene_conversion_rate, 0]
cumulative = [0, sequence_length * gene_conversion_rate]
"""
self.positions = positions
self.rates = rates
self.cumulative = RateMap.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 sequence_length(self):
return self.positions[-1]
@property
def total_mass(self):
return self.cumulative[-1] # sequence_length * gene_conversion_rate
@property
def mean_rate(self):
return self.total_mass / self.sequence_length # gene_conversion_rate
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 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 pos
def shift_by_mass(self, pos, mass):
result_mass = self.position_to_mass(pos) + mass
return self.mass_to_position(result_mass)
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:
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, bp): # noqa: A002
"""
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(bp, 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 = bp
def _make_segment(self, left, right, count):
seg = Segment(0)
seg.left = left
seg.right = right
seg.node = count
return seg
class Hull:
"""
A hull keeps track of the outermost boundaries (left, right) of
a segment chain (lineage_head). Hulls allow us to efficiently
keep track of overlapping lineages when simulating under the SMC_K.
"""
def __init__(self, index):
self.left = None
self.right = None
self.lineage_head = None
self.index = index
self.insertion_order = math.inf
def __lt__(self, other):
return (self.left, self.insertion_order) < (other.left, other.insertion_order)
def __repr__(self):
return f"l:{self.left}, r:{self.right}, io:{self.insertion_order}"
def intersects_with(self, other):
return self.left < other.right and other.left < self.right
class HullEnd:
"""
Each HullEnd is associated with a single Hull and keeps track of
Hull.right. This object is used to keep track of the order of Hulls
based on Hull.right in a separate AVLTree when simulating the SMC_K.
"""
def __init__(self, x):
self.x = x
self.insertion_order = math.inf
def __lt__(self, other):
return (self.x, self.insertion_order) < (other.x, other.insertion_order)
def __repr__(self):
return f"x:{self.x}, io:{self.insertion_order}"
class OrderStatisticsTree:
"""
Bintrees AVL tree with added functionality to keep track of the rank
of all nodes in the AVL tree. This is needed for the SMC_K implementation.
The C AVL library has this functionality already baked in.
"""
def __init__(self):
self.avl = bintrees.AVLTree()
self.rank = {}
self.size = 0
self.min = None
def __len__(self):
return self.size
def __setitem__(self, key, value):
first = True
rank = 0
if self.min is not None:
if self.min < key:
prev_key = self.avl.floor_key(key)
rank = self.rank[prev_key]
rank += 1
first = False
if first:
self.min = key
self.avl[key] = value
self.rank[key] = rank
self.size += 1
self.update_ranks(key, rank)
def __getitem__(self, key):
return self.avl[key], self.rank[key]
def get_rank(self, key):
return self.rank[key]
def update_ranks(self, key, rank, increment=1):
while rank < self.size - 1:
key = self.avl.succ_key(key)
self.rank[key] += increment
rank += 1
def pop(self, key):
if self.min == key:
if len(self) == 1:
self.min = None
else:
self.min = self.avl.succ_key(key)
rank = self.rank.pop(key)
self.update_ranks(key, rank, -1)
value = self.avl.pop(key)
self.size -= 1
return value, rank
def succ_key(self, key):
rank = self.rank[key]
if rank < self.size - 1:
key = self.avl.succ_key(key)
rank += 1
return key, rank
else:
return None, None
def prev_key(self, key):
if key == self.min:
return None, None
else:
key = self.avl.prev_key(key)
rank = self.rank[key]
return key, rank
def floor_key(self, key):
if len(self) == 0:
return None
if key < self.min:
return None
return self.avl.floor_key(key)
def ceil_key(self, key):
if len(self) == 0:
return None
return self.avl.ceiling_key(key)
class Simulator:
"""
A reference implementation of the multi locus simulation algorithm.
"""
def __init__(
self,
*,
tables,
recombination_map,
migration_matrix,
population_growth_rates,
population_sizes,
population_growth_rate_changes,
population_size_changes,
migration_matrix_element_changes,
bottlenecks,
census_times,
model="hudson",
max_segments=100,
num_labels=1,
sweep_trajectory=None,
coalescing_segments_only=True,
additional_nodes=None,
time_slice=None,
hgt_rate=0.0,
gene_conversion_rate=0.0,
gene_conversion_length=1,
discrete_genome=True,
coalescent_events_nwk=None,
coalescent_events_ts=None,
):
# Must be a square matrix.
N = len(migration_matrix)
assert len(tables.populations) == 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 gene_conversion_length >= 1
self.tables = tables
self.model = model
self.L = tables.sequence_length
self.recomb_map = recombination_map
self.gc_map = RateMap([0, self.L], [gene_conversion_rate, 0])
self.hgt_map = RateMap([0, self.L], [hgt_rate, 0])
self.hgt_edges = []
self.hgt_tract_length = 1
self.bin_hgt_mask = 0b10
self.tract_length = gene_conversion_length
self.discrete_genome = discrete_genome
self.migration_matrix = migration_matrix
self.num_labels = num_labels
self.num_populations = N
self.max_segments = max_segments
self.coalescing_segments_only = coalescing_segments_only
self.additional_nodes = msprime.NodeType(additional_nodes)
if self.additional_nodes.value > 0:
assert not self.coalescing_segments_only
self.pedigree = None
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.hull_stack = []
self.hulls = [None for _ in range(self.max_segments + 1)]
for j in range(self.max_segments):
h = Hull(j + 1)
self.hulls[j + 1] = h
self.hull_stack.append(h)
self.P = [Population(id_, num_labels, max_segments, model) for id_ in range(N)]
if self.recomb_map.total_mass == 0:
self.recomb_mass_index = None
else:
self.recomb_mass_index = [FenwickTree(self.max_segments) for _ in range(num_labels)]
if self.gc_map.total_mass == 0:
self.gc_mass_index = None
else:
self.gc_mass_index = [FenwickTree(self.max_segments) for _ in range(num_labels)]
if self.hgt_map.total_mass == 0:
self.hgt_mass_index = None
else:
self.hgt_mass_index = [FenwickTree(self.max_segments) for _ in range(num_labels)]
self.S = bintrees.AVLTree()
for pop in self.P:
pop.set_start_size(population_sizes[pop.id])
pop.set_growth_rate(population_growth_rates[pop.id], 0)
self.edge_buffer = []
self.fixed_coalescent_events = False
self.coalescent_events = []
if coalescent_events_nwk:
self.fixed_coalescent_events = True
self.parse_nwk(coalescent_events_nwk)
self.coalescent_events.sort()
logger.debug(self.coalescent_events)
elif coalescent_events_ts:
self.fixed_coalescent_events = True
self.parse_ts(coalescent_events_ts)
self.coalescent_events.sort()
logger.debug(self.coalescent_events)
# set hull_offset for smc_k, deviates from actual pattern
# implemented using `ParametricAncestryModel()`
self.hull_offset = None
if self.model == "smc_k":
self.hull_offset = 0.0
self.initialise(tables.tree_sequence())
self.num_ca_events = 0
self.num_re_events = 0
self.num_gc_events = 0
self.num_hgt_events = 0
# Sweep variables
self.sweep_site = (self.L // 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(self, ts):
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]