-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSAIsim.py
More file actions
4567 lines (4290 loc) · 188 KB
/
SAIsim.py
File metadata and controls
4567 lines (4290 loc) · 188 KB
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
# The Object Oriented implementation of Sexually Antagonistic mutation accumulation
# in Inversions in a forward Population simulation
# Ideally, models large inversion polymorphisms in populations with high reproductive skew
# REWRITE WITH NUMPY ARRAYS/VECTORS?
# TODO:
# fix chrom length by collapsing to just recomb. rate or length param. (prob. recomb. rate)
# add full record of offspring/values for individuals/gen. instead of means/var (also use coeff. of var. for surv.)
# combine record keeping into the step function to speed up/make simpler (how much benefit?)
#
import numpy as np
# import pickle as p
import itertools
from collections import Counter
# For counting chromosome proportions to compare to expected proportions
class HashableList(object):
def __init__(self, val):
self.val = val
def __hash__(self):
return hash(str(self.val))
def __repr__(self):
# define this method to get clean output
return str(self.val)
def __eq__(self, other):
return str(self.val) == str(other.val)
# The object representing an individual in the population under simulation,
# contains methods for generating mutation position and effects, and new recombinant gametes
# recombRate is the expected number of recombination events per chromosome per reproductive event
# meanMutEffect is the expected effect size of a new mutation
# mutEffectDiffSD is the SD of the difference in survival/rep effect size of a new mutation (normal dist)
# genome defaults to 2 copies of a single chormosome,
# ideally: genome = [[[chr1hom1],[chr1hom2]],[[chr2hom1],[chr2hom2]],..]
class individual(object):
"""individuals represent members of simSAIpopulations"""
def __init__(self, sex, mutEffectDiffSD, recombRate, conversionRate, minInvLen, lenChrom,
maleAchiasmy, willConvert, willRecombine, oneInvPerChrom, genome = [[[[],[]],[[],[]]]]):
# super(individual, self).__init__()
self.sex = sex
self.mutEffectDiffSD = mutEffectDiffSD
self.recombRate = recombRate
self.conversionRate = conversionRate
self.minInvLen = minInvLen
self.lenChrom = lenChrom
# CONSIDER JUST PASSING VARIABLES WHEN NEEDED
self.maleAchiasmy = maleAchiasmy
self.willConvert = willConvert
self.willRecombine = willRecombine
self.oneInvPerChrom = oneInvPerChrom
# genome = [[[chr1hom1],[chr1hom2]],[[chr2hom1],[chr2hom2]],..]
# where chomosome homologs = [mutist, InvList]
self.genome = genome
# For getting the insertion index of a position from a list of mutations
# or inversions, represented individually as [position, ..] lists
def __getInsInd(self,mutInvList,mutInvPos):
i = 0
while (i < len(mutInvList)) and (mutInvList[i][0] <= mutInvPos):
i += 1
return i
# For inserting a mutation or inversion into a corresponding list
# May rely on passing the list as a reference (doesn't currently)
def __insert(self,mutInvList,mutInv):
i = 0
while (i < len(mutInvList)) and (mutInvList[i][0] <= mutInv[0]):
i += 1
mutInvList[i:i] = [mutInv]
return mutInvList
# Generates mutation survival and reproductive quality effect values,
# from the population class parameters of mean and SD
# Consider alternate distributions? Lognormal?
def __genEffectSizes(self):
base = np.random.ranf()
offset = np.random.normal(scale=self.mutEffectDiffSD)
mutEffects = []
while (min(1-base,base) < offset) or (offset < max(base-1,-base)):
offset = np.random.normal(scale=self.mutEffectDiffSD)
# Survival (multiplicative), Quality (additive)
return [1-base+offset,base+offset]
# Generates mutation survival and reproductive quality effect values,
# with ranges (0, 1] and [0, 1)
def __genEffectSizesRand(self):
return [1-np.random.ranf(),np.random.ranf()]
# Generates a mutation of the form [position, survival effect, rep effect, ID]
# and inserts it into a random position in the genome
def mutate(self,ID):
# print(self.genome)
mutPos = np.random.ranf()*self.lenChrom
mutEffects = self.__genEffectSizesRand()
mutation = [mutPos]+mutEffects+[ID]
# Pick a chromosome
chromIndex = np.random.randint(0,len(self.genome))
# Pick a homolog
homIndex = np.random.randint(0,2)
# Insert the mutation into the list of mutations for the homolog
# print(self.genome[chromIndex][homIndex][0])
self.genome[chromIndex][homIndex][0] = \
self.__insert(self.genome[chromIndex][homIndex][0],mutation)
# print(self.genome[chromIndex][homIndex][0])
# Return the mutation data for recording
return mutation[0:3]+[chromIndex]
# Generates data on uninverted segments of the
# In order to pick where the inversion mutant may be placed
def __genOpenUninvRegData(self,chromHomInv):
openRegLengths = []
openRegStarts = []
openRegIndexes = []
potentialStart = 0
index = 0
for inversion in chromHomInv:
length = inversion[0] - potentialStart
if length > self.minInvLen:
openRegLengths += [length]
openRegStarts += [potentialStart]
openRegIndexes += [index]
potentialStart = inversion[1]
index += 1
length = self.lenChrom - potentialStart
# length = 1 - potentialStart
if length > self.minInvLen:
openRegLengths += [length]
openRegStarts += [potentialStart]
openRegIndexes += [index]
return (openRegLengths,openRegStarts,openRegIndexes)
# Generates and inserts an inversion into the genome,
# unless there is no open region >= minInvLen
# Inversions cover the region [pos1,pos2)
# Does not use resampling
# ADD A VERSION THAT ONLY CHECKS ONE RANDOM POSITION AND GIVES UP, OR HANDLING OF OVERLAPS
def mutateInvOpenReg(self,ID):
# Pick a chromosome
chromIndex = np.random.randint(0,len(self.genome))
# Put it on one of the two homologs
homIndex = np.random.randint(0,2)
chromHomInv = self.genome[chromIndex][homIndex][1]
# return None if one one inversion per chromosome is allowed,
# and there is already an inversion present
if self.oneInvPerChrom and len(chromHomInv) > 0:
return
# Pick where the insertion may be placed
(openRegLengths,openRegStarts,openRegIndexes) = self.__genOpenUninvRegData(chromHomInv)
# If there is no space for a new inversion >= minInvLen, don't add one, return None
if len(openRegStarts) == 0:
return
# Now sample which open region to add the inversion to
regChoice = np.random.choice(len(openRegStarts),p=[l/sum(openRegLengths) for l in openRegLengths])
# Generate the inversion
posA = openRegStarts[regChoice] + np.random.ranf()*(openRegLengths[regChoice]-self.minInvLen)
posB = openRegStarts[regChoice] + np.random.ranf()*(openRegLengths[regChoice]-self.minInvLen)
inversion = [min(posA,posB),max(posA,posB)+self.minInvLen,ID]
index = openRegIndexes[regChoice]
chromHomInv[index:index] = [inversion]
# Return the inversion data to record
return inversion[0:2]+[chromIndex]
# Generates a random inversion position and length >= minInvLen,
# and inserts an it into the genome,
# if that position isn't already occupied in the selected chromosome homolog
# Inversions cover the region [pos1,pos2)
# Does not use resampling
def mutateInv(self,ID):
# Pick a chromosome
chromIndex = np.random.randint(0,len(self.genome))
# Put it on one of the two homologs
homIndex = np.random.randint(0,2)
chromHomInv = self.genome[chromIndex][homIndex][1]
# Randomly generate an inversion
posA = np.random.ranf()*(self.lenChrom-self.minInvLen)
posB = np.random.ranf()*(self.lenChrom-self.minInvLen)
inversion = [min(posA,posB),max(posA,posB)+self.minInvLen,ID]
# Check if this inversion may be added, and do so if it can
if len(chromHomInv) > 0:
# return None if only one inversion per chromosome is allowed,
# and there is already an inversion present
if self.oneInvPerChrom:
return
else:
# Check if the inversion may be placed
invIndex = 0
while invIndex < len(chromHomInv) and chromHomInv[invIndex][1]<=inversion[0]:
invIndex += 1
if invIndex < len(chromHomInv):
if chromHomInv[invIndex][0]<inversion[1]:
# Found a conflicting inversion: return None, don't mutate
return
# Otherwise, add the inversion and return the inversion itself
else:
chromHomInv[invIndex:invIndex] = [inversion]
return inversion[0:2]+[chromIndex]
# return inversion
else:
chromHomInv += [inversion]
return inversion[0:2]+[chromIndex]
# return inversion
else:
chromHomInv += [inversion]
return inversion[0:2]+[chromIndex]
# return inversion
# # For updating the repQuality and survival if pre-calculated
# # Not currently used (obviously)
# def updatePhenotypes(self):
# return
# Negative survival effects are independent and multiplicative
def survival(self):
# listSurvival = 1.0
# for chrom in self.genome:
# for mut in chrom[0][0]:
# listSurvival *= mut[1]
# for mut in chrom[1][0]:
# listSurvival *= mut[1]
muts = []
for chrom in self.genome:
muts += chrom[0][0]+chrom[1][0]
if muts != []:
# print(np.array(muts))
survival = np.prod(np.array(muts)[...,1])
# print(survival)
else:
survival = 1
# print("Survival: "+str(survival)+" by vect; "+str(listSurvival)+" by for loop")
# assert(survival == listSurvival), "Survival calculation differs between np and list calcs: "+\
# str(survival)+" and "+str(listSurvival)+" respectively"
return survival
# FIX THIS - what quality accounting process is biological? (This doesn't seem tooo bad, tbh)
# ALSO - maybe calculate it once to save time? probably recalculated several times in choosing fathers
def repQuality(self):
# listQuality = 0.0
# for chrom in self.genome:
# for mut in chrom[0][0]:
# listQuality += mut[2]
# # For modeling effects multiplicatively? - requires changing effect generation
# # listQuality *= mut[2]
# for mut in chrom[1][0]:
# listQuality += mut[2]
# # For modeling effects multiplicatively? - requires changing effect generation
# # listQuality *= mut[2]
muts = []
for chrom in self.genome:
muts += chrom[0][0]+chrom[1][0]
if muts != []:
# print(np.array(muts))
quality = np.sum(np.array(muts)[...,2])
# print(quality)
else:
quality = 0
# print("Rep Quality: "+str(quality)+" by vect; "+str(listQuality)+" by for loop")
# assert(quality == listQuality), "Reproductive quality calculation differs between np and list calcs: "+\
# str(quality)+" and "+str(listQuality)+" respectively"
return quality
def __convCheck(self, chrom, parChrom):
mutIDs0 = [x[3] for x in chrom[0][0]]
invIDs0 = [x[2] for x in chrom[0][1]]
mutIDs1 = [x[3] for x in chrom[1][0]]
invIDs1 = [x[2] for x in chrom[1][1]]
# print(mutIDs0+mutIDs1)
mutCounts = Counter(mutIDs0+mutIDs1)
# print(mutCounts)
invCounts = Counter(invIDs0+invIDs1)
if len(mutCounts) > 0:
highestMutCount = mutCounts.most_common(1)[0][1]
if highestMutCount > 2:
print("Failed Conversion: "+str(highestMutCount)+" copies of mut "+str(mutCounts.most_common(1)[0][0]))
print("ParHap0: "+str([x[3] for x in parChrom[0][0]]))
print("ParHap1: "+str([x[3] for x in parChrom[0][1]]))
print("ConHap0: "+str(mutIDs0))
print("ConHap1: "+str(mutIDs1))
print(parChrom)
print(chrom)
if len(invCounts) > 0:
highestInvCount = invCounts.most_common(1)[0][1]
if highestInvCount > 2:
print("Failed Conversion from crossover? / too many inversions? Inv data shouldn't be changed")
# Takes a chromosome and returns the chromosome with converted mutations
# Setting the boolean willConvert in the population object will turn conversion off in the simulation
def __convertChrom(self,chrom):
# parChrom = [[list(chrom[0][0]),list(chrom[0][1])],[list(chrom[1][0]),list(chrom[1][1])]]
homInd1 = 0
homInd2 = 0
# Check for heterozygosity and add/remove mutations following conversionRate probability
# !!!! Relies on the invariant that earlier indexed mutations have earlier position
while homInd1 < len(chrom[0][0]) and homInd2 < len(chrom[1][0]):
mut1 = chrom[0][0][homInd1]
mut2 = chrom[1][0][homInd2]
if mut1[0] == mut2[0]:
homInd1 += 1
homInd2 += 1
if mut1[0] < mut2[0]:
if np.random.ranf() < self.conversionRate:
# print("Attempting Conversion")
if np.random.randint(2):
chrom[0][0][homInd1:homInd1+1] = []
else:
chrom[1][0][homInd2:homInd2] = [mut1]
homInd2 += 1
homInd1 += 1
else:
homInd1 += 1
if mut1[0] > mut2[0]:
if np.random.ranf() < self.conversionRate:
if np.random.randint(2):
chrom[1][0][homInd2:homInd2+1] = []
else:
chrom[0][0][homInd1:homInd1] = [mut2]
homInd1 += 1
homInd2 += 1
else:
homInd2 += 1
# Deal with the remaining mutations
# when one chromosome has no mutations it is dealt with here immediately
while homInd1 < len(chrom[0][0]):
if np.random.ranf() < self.conversionRate:
if np.random.randint(2):
chrom[0][0][homInd1:homInd1+1] = []
else:
chrom[1][0] += [chrom[0][0][homInd1]]
homInd1 += 1
homInd2 += 1 # IMPORTANT - so homInd2 is still == len
else:
homInd1 += 1
while homInd2 < len(chrom[1][0]):
if np.random.ranf() < self.conversionRate:
if np.random.randint(2):
chrom[1][0][homInd2:homInd2+1] = []
else:
chrom[0][0] += [chrom[1][0][homInd2]]
homInd2 += 1
else:
homInd2 += 1
# self.__convCheck(chrom, parChrom)
return chrom
# Takes two inversion lists for homologous chromosomes,
# indexes of the closest inversions to start <= the position of interest,
# and the position of interest
# Returns the position following the position of interest such that an odd # of crossovers
# between the two would generate aneuploid gametes, returns -1 if it isn't in such a region
def __getAllAneupRegion(self,invHom1,invHom2):
unbalancedRegions = []
ind1 = 0
ind2 = 0
startForward = False # Check unbalanced region starts inside one of the inversions
unbalStart = 0 # The start of the unbalanced region ^ (when )
retainFirst = True # For knowing which inversion it is inside of
while (ind1 < len(invHom1)) and (ind2 < len(invHom2)):
(start1,end1,ID1) = invHom1[ind1]
(start2,end2,ID2) = invHom2[ind2]
if ID1 == ID2: # CHECK POSITIONS DIRECTLY?
ind1 += 1
ind2 += 1
elif startForward:
if retainFirst:
if start2 < end1:
if end2 < end1:
unbalancedRegions += [(unbalStart,start2),(start2,end2)]
ind2 += 1
unbalStart = end2
if end2 == end1:
unbalancedRegions += [(unbalStart,start2),(start2,end2)]
ind1 += 1
ind2 += 1
startForward = False
else:
unbalancedRegions += [(unbalStart,start2),(start2,end1)]
ind1 += 1
else:
unbalancedRegions += [(unbalStart,end1)]
ind1 += 1
elif start1 <= start2:
if end1 < start2:
unbalancedRegions += [(start1,end1)]
ind1 += 1
elif start2 <= start1:
if end2 < start1:
unbalancedRegions += [(start2,end2)]
ind2 += 1
elif end2 < end1:
unbalancedRegions += []
# Deal with no inversions present on the chromosome
if len(invHom1) == 0:
if (len(invHom2) == 0) or (recPos >= invHom2[ind2][1]):
return unbalancedRegions
else:
return invHom2[ind2][1]
elif len(invHom2) == 0:
if recPos >= invHom1[ind1][1]:
return -1
else:
return invHom1[ind1][1]
else:
# print(invHom1[ind1][:2])
# print(invHom2[ind2][:2])
# print(invHom1[ind1] == invHom2[ind2])
if invHom1[ind1][:2] == invHom2[ind2][:2]:
return -1
end1 = invHom1[ind1][1]
end2 = invHom2[ind2][1]
# Currently, inversions are counted as [1,2), so crossovers are inside or not following such
if recPos < end1:
if recPos < end2:
return min(end1,end2)
if (ind2 < len(invHom2)-1) and invHom2[ind2+1][0] < end1:
return invHom2[ind2+1][0]
return end1
elif recPos < end2:
if (ind1 < len(invHom1)-1) and invHom1[ind1+1][0] < end2:
return invHom1[ind1+1][0]
return end2
else:
return -1
# # Takes two inversion lists for homologous chromosomes,
# # indexes of the closest inversions to start <= the position of interest,
# # and the position of interest
# # Returns the position following the position of interest such that an odd # of crossovers
# # between the two would generate aneuploid gametes, returns -1 if it isn't in such a region
# def __getAllAneupRegion(self,invHom1,invHom2):
# unbalancedRegions = []
# ind1 = 0
# ind2 = 0
# breaks1 = []
# breaks2 = []
# (start1,end1,ID1) = invHom1[ind1]
# (start2,end2,ID2) = invHom2[ind2]
# while (ind1 < len(invHom1)) and (ind2 < len(invHom2)):
# if ID1 == ID2: # CHECK POSITIONS DIRECTLY?
# ind1 += 1
# ind2 += 1
# while end1 < start2
# elif start1 <= start2:
# if end1 < start2:
# unbalancedRegions += [(start1,end1)]
# ind1 += 1
# elif start2 <= start1:
# if end2 < start1:
# unbalancedRegions += [(start2,end2)]
# ind2 += 1
# elif end2 < end1:
# unbalancedRegions += []
# isEnd1 = False
# isEnd2 = False
# while (ind1 < len(invHom1)) and (ind2 < len(invHom2)):
# (start1,end1,ID1) = invHom1[ind1]
# (start2,end2,ID2) = invHom2[ind2]
# if ID1 == ID2: # CHECK POSITIONS DIRECTLY?
# ind1 += 1
# ind2 += 1
# elif start1 <= start2:
# if end1 < start2:
# unbalancedRegions += [(start1,end1)]
# ind1 += 1
# elif start2 <= start1:
# if end2 < start1:
# unbalancedRegions += [(start2,end2)]
# ind2 += 1
# elif end2 < end1:
# unbalancedRegions += []
# # Deal with no inversions present on the chromosome
# if len(invHom1) == 0:
# if (len(invHom2) == 0) or (recPos >= invHom2[ind2][1]):
# return unbalancedRegions
# else:
# return invHom2[ind2][1]
# elif len(invHom2) == 0:
# if recPos >= invHom1[ind1][1]:
# return -1
# else:
# return invHom1[ind1][1]
# else:
# # print(invHom1[ind1][:2])
# # print(invHom2[ind2][:2])
# # print(invHom1[ind1] == invHom2[ind2])
# if invHom1[ind1][:2] == invHom2[ind2][:2]:
# return -1
# end1 = invHom1[ind1][1]
# end2 = invHom2[ind2][1]
# # Currently, inversions are counted as [1,2), so crossovers are inside or not following such
# if recPos < end1:
# if recPos < end2:
# return min(end1,end2)
# if (ind2 < len(invHom2)-1) and invHom2[ind2+1][0] < end1:
# return invHom2[ind2+1][0]
# return end1
# elif recPos < end2:
# if (ind1 < len(invHom1)-1) and invHom1[ind1+1][0] < end2:
# return invHom1[ind1+1][0]
# return end2
# else:
# return -1
# For returning recombination points that are balanced, with correct resampling
def __getBalancedRecomb(self):
return
# For efficiently resampling recombination breakpoints
# when they would otherwise generate unbalanced gametes
def genGameteResampleCrossovers(self):
gamGenome = []
for parChrom in self.genome:
(numRecomb, recombPositions) = self.__getBalancedRecomb()
# print('Recombinations: '+str(numRecomb))
currHom1 = bool(np.random.randint(2))
# This first copy step is necessary independent of conversion/recombination activity,
# to prevent changes to shared-referent chromosomes
chrom = [[list(parChrom[0][0]),list(parChrom[0][1])],[list(parChrom[1][0]),list(parChrom[1][1])]]
# Perform fly-specific non-recombination non-conversion check for males
if self.willConvert and (self.sex == 'F' or (not self.maleAchiasmy)):
chrom = self.__convertChrom(chrom)
if (not self.willRecombine) or numRecomb == 0 or (self.maleAchiasmy and self.sex == 'M'): # WARNING - poorly defined numRecomb
if currHom1:
gamGenome += [chrom[0]]
else:
gamGenome += [chrom[1]]
else:
# NEED to allow for the span of positions in the chromosome if given positions outside [0,1)
recombPositions = np.random.ranf(numRecomb)*self.lenChrom
# recombPositions = np.random.ranf(numRecomb)
recombPositions.sort()
# print('Positions: '+str(recombPositions))
# Construct a recombinant gamete from the recombination positions
gamMutations = []
gamInversions = []
recIndex = 0
invInd1 = 0
invInd2 = 0
invHom1 = chrom[0][1]
invHom2 = chrom[1][1]
mutInd1 = 0
mutInd2 = 0
prevInvInd1 = 0
prevInvInd2 = 0
prevMutInd1 = 0
prevMutInd2 = 0
while recIndex < numRecomb:
recPos = recombPositions[recIndex]
while (mutInd1 < len(chrom[0][0])) and (chrom[0][0][mutInd1][0] <= recPos):
mutInd1 += 1
while (mutInd2 < len(chrom[1][0])) and (chrom[1][0][mutInd2][0] <= recPos):
mutInd2 += 1
while (invInd1 < len(chrom[0][1])) and (chrom[0][1][invInd1][0] <= recPos):
invInd1 += 1
while (invInd2 < len(chrom[1][1])) and (chrom[1][1][invInd2][0] <= recPos):
invInd2 += 1
# Add the mutations and inversions to the gamete chromosome
if currHom1:
gamMutations += chrom[0][0][prevMutInd1:mutInd1]
gamInversions += chrom[0][1][prevInvInd1:invInd1]
else:
gamMutations += chrom[1][0][prevMutInd2:mutInd2]
gamInversions += chrom[1][1][prevInvInd2:invInd2]
# Update the mutation/inversion indexes of the previous breakpoint
prevInvInd1 = invInd1
prevInvInd2 = invInd2
prevMutInd1 = mutInd1
prevMutInd2 = mutInd2
# Deal with crossovers in regions potentially generating aneuploidy
aneupRegEnd = self.__getAneupRegion(invHom1,invHom2,invInd1-1,invInd2-1,recPos)
if aneupRegEnd == -1:
currHom1 = not currHom1
recIndex += 1
else:
otherRecInReg = []
recIndex += 1
while (recIndex < numRecomb) and (recombPositions[recIndex] < aneupRegEnd):
otherRecInReg += [recombPositions[recIndex]]
recIndex += 1
# If there's an even number of recombinations in the region in total:
if len(otherRecInReg)%2:
currHom1 = not currHom1
for recPos in otherRecInReg:
while (mutInd1 < len(chrom[0][0])) and (chrom[0][0][mutInd1][0] <= recPos):
mutInd1 += 1
while (mutInd2 < len(chrom[1][0])) and (chrom[1][0][mutInd2][0] <= recPos):
mutInd2 += 1
# Add the mutations to the gamete chromosome (no inversion change in region)
if currHom1:
gamMutations += chrom[0][0][prevMutInd1:mutInd1]
else:
gamMutations += chrom[1][0][prevMutInd2:mutInd2]
# Update the mutation indexes of the previous breakpoint
prevMutInd1 = mutInd1
prevMutInd2 = mutInd2
# Switch the current chromosome from the crossover event
currHom1 = not currHom1
# Add the last mutations and inversions to the gamete chromosome
if currHom1:
gamMutations += chrom[0][0][prevMutInd1:len(chrom[0][0])]
gamInversions += chrom[0][1][prevInvInd1:len(chrom[0][1])]
else:
gamMutations += chrom[1][0][prevMutInd2:len(chrom[1][0])]
gamInversions += chrom[1][1][prevInvInd2:len(chrom[1][1])]
gamGenome += [[gamMutations,gamInversions]]
return gamGenome
# Takes two inversion lists for homologous chromosomes,
# indexes of the closest inversions to start > the position of interest,
# and the position of interest
# Returns the position following the position of interest such that an odd # of crossovers
# between the two would generate aneuploid gametes, returns -1 if it isn't in such a region
def __getAneupRegion(self,invHom1,invHom2,nextInd1,nextInd2,recPos):
# switch to the closest inversions to start <= the position of interest
precIndex1 = nextInd1 - 1
precIndex2 = nextInd2 - 1
# Deal with non-aneuploid region cases, overlapping inversion on only one chromosome:
# no inversions present on the chromosome, (should be covered by indexes == -1)
# inversions end or aren't encountered before the crossover
if precIndex1 == -1 or recPos >= invHom1[precIndex1][1]:
if precIndex2 == -1 or recPos >= invHom2[precIndex2][1]:
return -1
else:
end = invHom2[precIndex2][1]
if nextInd1 < len(invHom1):
end = min(end, invHom1[nextInd1][0])
return end
elif precIndex2 == -1 or recPos >= invHom2[precIndex2][1]:
# if recPos >= invHom1[precIndex1][1]:
# return -1
# else:
# return invHom1[precIndex1][1]
end = invHom1[precIndex1][1]
if nextInd2 < len(invHom2):
end = min(end, invHom2[nextInd2][0])
return end
elif invHom1[precIndex1][:2] == invHom2[precIndex2][:2]:
return -1
else:
# Expect to KNOW here that recPos < both inversion ends
assert(recPos < invHom1[precIndex1][1] and recPos < invHom2[precIndex2][1]), "Conditional tree should guarantee this"
# print(invHom1[precIndex1][:2])
# print(invHom2[precIndex2][:2])
# print(invHom1[precIndex1] == invHom2[precIndex2])
# end1 = invHom1[precIndex1][1]
# end2 = invHom2[precIndex2][1]
return min(invHom1[precIndex1][1],invHom2[precIndex2][1])
# if (precIndex2 < len(invHom2)-1) and invHom2[precIndex2+1][0] < end1:
# return invHom2[precIndex2+1][0]
# return end1
# elif recPos < end2:
# if (precIndex1 < len(invHom1)-1) and invHom1[precIndex1+1][0] < end2:
# return invHom1[precIndex1+1][0]
# return end2
# else:
# return -1
# Same as __getAneupRegion, but considers regions between inversions of opposite strands as aneuploidy generating,
# to remove recombinants that have multiple inversions
# ASSUMES only 1 inv/chrom, don't need to account for others on each homolog
def __getAneupRegionOneInvPerChrom(self,invHom1,invHom2,nextInd1,nextInd2,recPos):
if len(invHom1) > 1 or len(invHom2) > 1:
raise self.SimulationStateError((invHom1,invHom2),"When oneInvPerChrom is set, "+\
"the simulation should never have chromosomes with more than one inversion.")
# switch to the closest inversions to start <= the position of interest
precIndex1 = nextInd1 - 1
precIndex2 = nextInd2 - 1
if precIndex1 == -1:
if precIndex2 == -1:
return -1
elif recPos >= invHom2[precIndex2][1]:
if nextInd1 < len(invHom1):
return invHom1[nextInd1][0]
else:
return -1
else:
end = invHom2[precIndex2][1]
if nextInd1 < len(invHom1):
end = min(end, invHom1[nextInd1][0])
return end
elif recPos >= invHom1[precIndex1][1]:
if precIndex2 == -1:
if nextInd2 < len(invHom2):
return invHom2[nextInd2][0]
else:
return -1
elif recPos >= invHom2[precIndex2][1]:
# ASSUMES only 1 inv/chrom, don't need to account for others on either
return -1
else:
# ASSUMES only 1 inv/chrom, don't need to account for others on hom1
return invHom2[precIndex2][1]
else:
if precIndex2 == -1:
end = invHom1[precIndex1][1]
if nextInd2 < len(invHom2):
end = min(end, invHom2[nextInd2][0])
return end
elif recPos >= invHom2[precIndex2][1]:
# ASSUMES only 1 inv/chrom, don't need to account for others on hom2
return invHom1[precIndex1][1]
else:
# ASSUMES only 1 inv/chrom, don't need to account for others on either
if invHom1[precIndex1][:2] == invHom2[precIndex2][:2]:
return -1
else:
return min(invHom1[precIndex1][1],invHom2[precIndex2][1])
# Model independently per chromosome, currently doesn't redraw if recombination events fail,
# just throws out all recombination events in an aneuploidy-causing region if they are odd in number
def genGameteDropUnbCrossovers(self):
gamGenome = []
for parChrom in self.genome:
numRecomb = np.random.poisson(self.recombRate)
# print('Recombinations: '+str(numRecomb))
currHom1 = bool(np.random.randint(2))
# This first copy step is necessary independent of conversion/recombination activity,
# to prevent changes to shared-referent chromosomes
chrom = [[list(parChrom[0][0]),list(parChrom[0][1])],[list(parChrom[1][0]),list(parChrom[1][1])]]
# Perform fly-specific non-recombination non-conversion check for males
if self.willConvert and (self.sex == 'F' or (not self.maleAchiasmy)):
chrom = self.__convertChrom(chrom)
if (not self.willRecombine) or numRecomb == 0 or (self.maleAchiasmy and self.sex == 'M'):
if currHom1:
gamGenome += [chrom[0]]
else:
gamGenome += [chrom[1]]
else:
# NEED to allow for the span of positions in the chromosome if given positions outside [0,1)
recombPositions = np.random.ranf(numRecomb)*self.lenChrom
# recombPositions = np.random.ranf(numRecomb)
recombPositions = np.sort(recombPositions)
# print('Positions: '+str(recombPositions))
# Construct a recombinant gamete from the recombination positions
gamMutations = []
gamInversions = []
recIndex = 0
invInd1 = 0
invInd2 = 0
invHom1 = chrom[0][1]
invHom2 = chrom[1][1]
mutInd1 = 0
mutInd2 = 0
prevInvInd1 = 0
prevInvInd2 = 0
prevMutInd1 = 0
prevMutInd2 = 0
while recIndex < numRecomb:
recPos = recombPositions[recIndex]
while (mutInd1 < len(chrom[0][0])) and (chrom[0][0][mutInd1][0] <= recPos):
mutInd1 += 1
while (mutInd2 < len(chrom[1][0])) and (chrom[1][0][mutInd2][0] <= recPos):
mutInd2 += 1
while (invInd1 < len(chrom[0][1])) and (chrom[0][1][invInd1][0] <= recPos):
invInd1 += 1
while (invInd2 < len(chrom[1][1])) and (chrom[1][1][invInd2][0] <= recPos):
invInd2 += 1
# Add the mutations and inversions to the gamete chromosome
if currHom1:
gamMutations += chrom[0][0][prevMutInd1:mutInd1]
gamInversions += chrom[0][1][prevInvInd1:invInd1]
else:
gamMutations += chrom[1][0][prevMutInd2:mutInd2]
gamInversions += chrom[1][1][prevInvInd2:invInd2]
# Update the mutation/inversion indexes of the previous crossover
prevInvInd1 = invInd1
prevInvInd2 = invInd2
prevMutInd1 = mutInd1
prevMutInd2 = mutInd2
# Deal with crossovers in regions potentially generating aneuploidy
if self.oneInvPerChrom:
aneupRegEnd = self.__getAneupRegionOneInvPerChrom(invHom1,invHom2,invInd1,invInd2,recPos)
else:
aneupRegEnd = self.__getAneupRegion(invHom1,invHom2,invInd1,invInd2,recPos)
if aneupRegEnd == -1:
currHom1 = not currHom1
recIndex += 1
else:
otherRecInReg = []
recIndex += 1
while (recIndex < numRecomb) and (recombPositions[recIndex] < aneupRegEnd):
otherRecInReg += [recombPositions[recIndex]]
recIndex += 1
# If there's an even number of recombinations in the region in total:
if len(otherRecInReg)%2:
currHom1 = not currHom1
for recPos in otherRecInReg:
while (mutInd1 < len(chrom[0][0])) and (chrom[0][0][mutInd1][0] <= recPos):
mutInd1 += 1
while (mutInd2 < len(chrom[1][0])) and (chrom[1][0][mutInd2][0] <= recPos):
mutInd2 += 1
# Add the mutations to the gamete chromosome (no inversion change in region)
if currHom1:
gamMutations += chrom[0][0][prevMutInd1:mutInd1]
else:
gamMutations += chrom[1][0][prevMutInd2:mutInd2]
# Update the mutation indexes of the previous breakpoint
prevMutInd1 = mutInd1
prevMutInd2 = mutInd2
# Switch the current chromosome from the crossover event
currHom1 = not currHom1
# Add the last mutations and inversions to the gamete chromosome
if currHom1:
gamMutations += chrom[0][0][prevMutInd1:len(chrom[0][0])]
gamInversions += chrom[0][1][prevInvInd1:len(chrom[0][1])]
else:
gamMutations += chrom[1][0][prevMutInd2:len(chrom[1][0])]
gamInversions += chrom[1][1][prevInvInd2:len(chrom[1][1])]
gamGenome += [[gamMutations,gamInversions]]
return gamGenome
# For deciding which recombination breakpoint sampling to use
def genGamete(self):
resampleUnbalanced = False
if resampleUnbalanced:
return self.genGameteResampleCrossovers()
else:
return self.genGameteDropUnbCrossovers()
# For printing a (potentially) command-line friendly version of the genome
def printGenome(self, i, printMut = True, printInv = True):
indStr = 'Ind {:6d} '.format(i)
for c in range(len(self.genome)):
for h in range(2):
homStr = indStr + 'Chrom '+str(c)+' Hom '+str(h)
if printMut:
mutStr = homStr + ' Mut: ' + str(self.genome[c][h][0])
print(mutStr)
if printInv:
invStr = homStr + ' Inv: ' + str(self.genome[c][h][1])
print(invStr)
return
# Module methods for preparing populations (genomes/sexes) from mutation/haplotype data
# Could be defined as Static methods inside the population class
# For testing the inputs for correct size parameters
# MAYY WANT TO TEST lenChrom
def __inputSizeCheck(size, numChrom, genomes, sexes):
numGenomes = len(genomes)
if numGenomes > 0:
# Ignore numChrom if genomes pre-specified, peg it to the number of chormosomes in genomes[0]
numChrom = len(genomes[0])
if numGenomes > size:
raise SAIpop.InputError(genomes,'More genomes provided than population size')
# Either require equal length sexes and genomes or just that sexes is smaller than population size
# and allows for one of each sex?
if (len(sexes) != 0) and (len(sexes) != numGenomes):
raise SAIpop.InputError(sexes,'Sexes must be of equal length to genomes')
return (numGenomes,numChrom)
# For generating the sexes list from a current sexes list
def __genSexes(size, sexes, randomSex, minNumPerSex):
# Account the provided sexes
numFemales = 0
numMales = 0
for sex in sexes:
if sex == 'M':
numMales += 1
elif sex == 'F':
numFemales += 1
else:
raise SAIpop.InputError(sexes,'Sexes must only contain \'F\' and \'M\' elements')
newSexes = []
# Needs at least one of each sex to be a viable population
while numMales < minNumPerSex:
newSexes += ['M']
numMales += 1
while numFemales < minNumPerSex:
newSexes += ['F']
numFemales += 1
numRemaining = size - numFemales - numMales
if numRemaining < 0:
raise SAIpop.InputError(sexes,'Sexes must allow at least one \'F\' and \'M\' in the population')
# Reuse numMales for the number of males to be added
if randomSex:
numMales = np.random.binomial(numRemaining,0.5)
else:
numMales = int(numRemaining/2)
newSexes += ['M' for i in range(numMales)]
newSexes += ['F' for i in range(numRemaining-numMales)]
np.random.shuffle(newSexes)
popSexes = sexes + newSexes
# Mutates the sexes list but will be returned anyway
return popSexes
# For generating a set of genomes, sexes, and a record from specified mutations and inversions,
# along with partial genomes and sexes lists to specify specific genomes,
# input inversion and mutation lists formatted as described in self.record but with count instead of initial generation:
# mutList: a list of all mutations, indexed by ID, with each entry as
# [position,survival effect,reproductive effect,chromosome,initial count]
# invList: a list of all inversions, indexed by ID, with each entry as
# [start position,end position,chromosome,initial count]
# populates the remaining genome slots with genomes to which mutations are randomly assigned from the count pools
# Currently doesn't allow description of prior record
# How to model starting with mutations specific to sexes?
# Allow limiting the number of further genomes to generate? How will this interact with having at least 1 'M'/'F'?
# @staticmethod
def genGenomesSexes(size, mutList, invList, randomSex = True, numChrom = 1,
lenChrom = 1.0, genomes = [], sexes = [], minNumPerSex = 1, verbose = False):
# Handling input size checking
if verbose: print('Num Chromosomes provided: '+str(numChrom))
# print(genomes)
# print(sexes)
(numGenomes,numChrom) = __inputSizeCheck(size, numChrom, genomes, sexes) # UPDATE FOR NUMCHROM FROM MUT/INV LIST
if verbose: print('Num Genomes already provided: '+str(numGenomes))
if verbose: print('Num Chromosomes after checking if present in genomes provided: '+str(numChrom))
# Generate the remaining sexes list
popSexes = __genSexes(size, sexes, randomSex, minNumPerSex)
# Generate the remaining genomes
if verbose: print('Pop Size to be filled: '+str(size))
numNewGenomes = size-numGenomes
# print('Num Genomes not already provided: '+str(numNewGenomes))
newGenomes = [[[[[],[]],[[],[]]] for i in range(numChrom)] for j in range(numNewGenomes)]
# Will need to have separate lists per chromosome within these
posOrderedMut = [[] for i in range(numChrom)]
posOrderedInv = [[] for i in range(numChrom)]
# Record should be returned with only [1,3] actually populated, [2,4...] with empty lists
# for 0th generation update
# record = [[],[],[],[],[],[],[],[],[],[],[]]
# record = [[] for x in range(10)]
record = [[],[],{},[],{},[],[],[],[],[],[],[],{},[],[],[],[]]
numMut = len(mutList)
for m in range(numMut):
if verbose: print('Accounting mutation: '+str(mutList[m]))
count = mutList[m][4]
if count > 2*numNewGenomes:
raise SAIpop.InputError(mutList,'Mutation counts must be less than the remaining population size')
mutation = mutList[m][0:3]+[m]
chrom = mutList[m][3]
record[1] += [mutList[m][0:4]+[0,-1]]
# record[2] += [[]]
# record[2][m] = []
# Insert the mutation and count to the ordered list for addition to the genomes
i = 0
while (i < len(posOrderedMut[chrom])) and (posOrderedMut[chrom][i][0][0] < mutation[0]):
i += 1
posOrderedMut[chrom][i:i] = [(mutation,count)]
if verbose: print('Position-ordered mutations: '+str(posOrderedMut))
numInv = len(invList)
for i in range(numInv):
if verbose: print('Accounting inversion: '+str(invList[i]))
count = invList[i][3]
if count > 2*numNewGenomes:
raise SAIpop.InputError(invList,'Inversion counts must be less than the remaining population size')
inversion = invList[i][0:2]+[i]
chrom = invList[i][2]
record[3] += [invList[i][0:3]+[0,-1]]
# record[4] += [[]]
# record[5] += [[]]
# record[6] += [[]]
# record[7] += [[]]
# record[8] += [[]]
# record[9] += [[]]
# record[10] += [[]]
# record[4][i] = [[],[],[],[],[],[],[],[],[],[]]
# Insert the inversion and count to the ordered list for addition to the genomes
i = 0
while (i < len(posOrderedInv[chrom])) and (posOrderedInv[chrom][i][0][1] <= inversion[0]):
i += 1
if i < len(posOrderedInv[chrom]) and posOrderedInv[chrom][i+1][0][0] <= inversion[1]:
raise SAIpop.InputError(invList,'Inversions cannot overlap')
posOrderedInv[chrom][i:i] = [(inversion,count)]
if verbose: print('Position-ordered inversions: '+str(posOrderedInv))