-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathabsolute_functions.c
1198 lines (1010 loc) · 56.2 KB
/
absolute_functions.c
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
#include <stdio.h>
#include <float.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_fit.h>
#include <err.h>
#include "dependencies/pcg_basic.h"
#include "absolute_functions.h"
#include "sharedfunc_flag.h"
#include "main.h"
#include <tskit.h>
#include <tskit/tables.h>
#include <kastore.h>
#include <tskit/core.h>
#include <tskit/trees.h>
double RunSimulationAbs(bool issnapshot, char *prevsnapshotfilename, bool isredinmaxpopsize, char *redinmaxpopsizename, double redinmaxpopsize, char* mubname, char* Sbname, int tskitstatus, bool ismodular, int elementsperlb, bool isabsolute, int maxTime, int initialPopSize, int K, int chromosomesize, int numberofchromosomes, double deleteriousmutationrate, double Sd, int deleteriousdistribution, double beneficialmutationrate, double Sb, int beneficialdistribution, double r, int i_init, double s, gsl_rng* randomnumbergeneratorforgamma, FILE *miscfilepointer, FILE *veryverbosefilepointer, int rawdatafilesize, bool iscalcfixation)
{
if(!isabsolute){
fprintf(miscfilepointer, "\n Trying to use RunSimulationAbs within a relative fitness program. \n");
exit(0);
}
FILE *rawdatafilepointer;
FILE *summarydatafilepointer;
//tree sequence data files
FILE *nodefilepointer;
FILE *edgefilepointer;
FILE *sitefilepointer;
FILE *mutationfilepointer;
FILE *tskitdatafilepointer;
int i, j, k, w;
char* rawdatafilename = MakeRawDataFileName(mubname, Sbname, isredinmaxpopsize, redinmaxpopsizename);
char* summarydatafilename = MakeSummaryDataFileName(mubname, Sbname);
summarydatafilepointer = fopen(summarydatafilename, "w"); //opens the file to which to print summary data.
nodefilepointer = fopen("nodetable.txt", "w");
edgefilepointer = fopen("edgetable.txt", "w");
sitefilepointer = fopen("sitetable.txt", "w");
mutationfilepointer = fopen("mutationtable.txt", "w");
if (iscalcfixation)
{
tskitdatafilepointer = fopen("tskitdata.txt", "w"); //opens the file to which to print fixed mutaiton data.
fprintf(tskitdatafilepointer, "Mutation\tTime_app\tTime_fix\n");
}
int kappa;
if(r == 1.0){
kappa = K/(s*i_init);
}
else{
if(deleteriousdistribution == 0){
kappa = (1-r)*K/(s);
}
else if(deleteriousdistribution == 1){
kappa = -(log(r)*K)/(s);
}
}
int maxPopSize = kappa;
//variables used to define birth rate
double const b_0 = 1.0;
double birthrate;
double *arrayofbirthrates;
arrayofbirthrates = malloc(sizeof(double)*maxPopSize);
calcRateofBirths(arrayofbirthrates, maxPopSize, kappa, b_0);
int simplifyat = 0;
int genafterburnin = 50000;
int simplifyeach = 2000;
int printeach = maxTime/rawdatafilesize;
int printtime = 0;
double redtime = 55000;
double redtimeeach = redinmaxpopsize;
if (tskitstatus == 2)
{
printtime = genafterburnin;
if (iscalcfixation)
{
simplifyat = genafterburnin + 3000;
simplifyeach = 3000;
}else{
simplifyat = genafterburnin;
}
}
int updatesumofdeathrateseach = 1000;
int updatesumtime = 0;
int totaltimesteps = maxTime;
int popsize = initialPopSize;
int *pPopSize;
pPopSize = &popsize;
double t = 0.0;
double *pCurrenttime = &t;
double *wholepopulationgenomes;
int totalpopulationgenomelength;
int totalindividualgenomelength;
double *parent1gamete, *parent2gamete;
if(!ismodular){
totalpopulationgenomelength = maxPopSize * numberofchromosomes * 2 * chromosomesize;
totalindividualgenomelength = numberofchromosomes * 2 * chromosomesize;
wholepopulationgenomes = malloc(sizeof(double) * totalpopulationgenomelength);
parent1gamete = malloc(sizeof(double) * numberofchromosomes*chromosomesize);
parent2gamete = malloc(sizeof(double) * numberofchromosomes*chromosomesize);
}
else{
//in modular runs the length of chromosome increases by a factor of elementsperlb (elements per linkage block)
totalpopulationgenomelength = maxPopSize * numberofchromosomes * 2 * chromosomesize * elementsperlb;
totalindividualgenomelength = numberofchromosomes * 2 * chromosomesize * elementsperlb;
wholepopulationgenomes = malloc(sizeof(double) * totalpopulationgenomelength);
parent1gamete = malloc(sizeof(double) * numberofchromosomes*chromosomesize*elementsperlb);
parent2gamete = malloc(sizeof(double) * numberofchromosomes*chromosomesize*elementsperlb);
}
long double sumofdeathrates;
long double sumofdeathratessquared;
long double sumofload;
long double sumofloadsquared;
long double *psumofdeathrates;
psumofdeathrates = &sumofdeathrates;
long double *psumofdeathratessquared;
psumofdeathratessquared = &sumofdeathratessquared;
long double *psumofload;
psumofload = &sumofload;
long double *psumofloadsquared;
psumofloadsquared = &sumofloadsquared;
long double *wholepopulationselectiontree;
wholepopulationselectiontree = malloc(sizeof(long double) * maxPopSize);
//Following lines are from the tskit library.
//Initializes the tables that make up the tree sequence recording.
tsk_table_collection_t treesequencetablecollection;
tsk_table_collection_t * tablepointer = &treesequencetablecollection;
int returnvaluefortskfunctions = tsk_table_collection_init(&treesequencetablecollection, 0);
check_tsk_error(returnvaluefortskfunctions);
tsk_id_t *wholepopulationnodesarray;
if (tskitstatus != 0){
wholepopulationnodesarray = malloc(sizeof(tsk_id_t) * 2 * maxPopSize);
}
//The extant nodes need to have explicit identification in order to add edges between parents and children nodes.
//Each node is only a single set of chromosomes, so the 2 here assumes diploidy.
tsk_id_t wholepopulationsitesarray[totalindividualgenomelength / 2];
//The number of sites is the number of linkage blocks in a single set of chromosomes (haploid), and won't change over the course of the simulation.
long double *wholepopulationdeathratesarray;
wholepopulationdeathratesarray = malloc(sizeof(long double) * maxPopSize);
//The Fenwick tree does not store each individual's wi, but rather a collection of partial sums.
//For debugging purposes and data that requires summarizing wis, storing the wis in an array is necessary.
long double *sortedwisarray;
sortedwisarray = malloc(sizeof(long double) * maxPopSize);
//In order to visualize the distribution of fitness in the population,
//the individual fitnesses need to be sorted, which requires a separate array.
bool *wholepopulationisfree;
wholepopulationisfree = malloc(sizeof(bool) * maxPopSize);
int *wholepopulationindex;
wholepopulationindex = malloc(sizeof(int) * maxPopSize);
if (VERYVERBOSE == 1) {
fprintf(veryverbosefilepointer, "Entered simulation run.\n");
}
//assignment of data to popArray for index, wis, and deathrate
if(!issnapshot){
rawdatafilepointer = fopen(rawdatafilename, "w"); //opens the file to which to print data to be plotted.
fprintf(rawdatafilepointer, "Time\tPop_size\tMean_death_rate\tVar_death_rate\tMean_birth_rate\tMean_load\tVar_load\n");
summarydatafilepointer = fopen(summarydatafilename, "w"); //opens the file to which to print summary data.
popsize = initialPopSize;
t = 0.0;
//assignment of data to popArray for index, wis, and deathrate
InitializePopulationAbs(tskitstatus, &treesequencetablecollection, wholepopulationnodesarray, wholepopulationsitesarray, wholepopulationselectiontree, wholepopulationdeathratesarray, wholepopulationindex, wholepopulationisfree, initialPopSize, maxPopSize, totaltimesteps, deleteriousdistribution, wholepopulationgenomes, totalpopulationgenomelength, psumofdeathrates, psumofdeathratessquared, psumofload, psumofloadsquared, b_0, r, i_init, s);//sets up all data within the population for a run. As this initializes data I think it should be a separate function.
}else{
rawdatafilepointer = fopen(rawdatafilename, "a");
summarydatafilepointer = fopen(summarydatafilename, "a"); //opens the file to which to print summary data.
FILE *prevsnapshotfilepointer;
prevsnapshotfilepointer = fopen(prevsnapshotfilename, "r");
if(prevsnapshotfilepointer == NULL){
fprintf(miscfilepointer, "\nError: There was an error oppening the snapshot file");
exit(0);
}
InitializeWithSnapshotAbs(wholepopulationselectiontree, wholepopulationdeathratesarray, wholepopulationindex, wholepopulationisfree, maxPopSize, wholepopulationgenomes, totalpopulationgenomelength, psumofdeathrates, psumofdeathratessquared, psumofload, psumofloadsquared, pPopSize, pCurrenttime, prevsnapshotfilepointer, miscfilepointer);
if (VERYVERBOSE == 1) {
fprintf(veryverbosefilepointer, "Started population with snapshot file.\n");
}
//the previous simulation time had to be added to the max time of the simulation
maxTime += t;
printtime += t + printeach;
updatesumtime += t + updatesumofdeathrateseach;
redtime += t + redinmaxpopsize;
fclose(prevsnapshotfilepointer);
}
if (VERYVERBOSE == 1) {
fprintf(veryverbosefilepointer, "Population initialized.\n");
fflush(veryverbosefilepointer);
}
double *logaveragefitnesseachNtimesteps;
logaveragefitnesseachNtimesteps = malloc(sizeof(double) * maxTime);
//In order to calculate the slope of degradation of fitness,
//I need to store the average fitness each generation.
long double currentfittestindividualswi;
//Following array is to store the variance in log(fitness) for twenty generations at a time for estimating the end of the burn-in phase.
//The choice of twenty is completely arbitrary and could eventually be an input if it seems worth it.
size_t step = 1;
double *last200Ntimestepsvariance;
double *literallyjustlast200Ntimesteps;
literallyjustlast200Ntimesteps = malloc(sizeof(double) * 200);
last200Ntimestepsvariance = malloc(sizeof(double) * 200);
for (k = 0; k < 200; k++) {
literallyjustlast200Ntimesteps[k] = 0.0;
last200Ntimestepsvariance[k] = 0.0;
}
double slopeofvariance;
int isburninphaseover = 0;
if (tskitstatus == 1){
isburninphaseover = 1;
}
int didpopulationcrash = 0;
int endofburninphase;
int endofdelay = maxTime-1;
int endofsimulation = maxTime-1;
int Nxtimestepsafterburnin = 0;
double arbitrarynumber = (-1.0 * 0.007 / maxPopSize); //using a number somewhere close to the mean of the DFE for deleterious mutations.
double slopeoflogfitness;
double variancesum;
bool birthhappens;
//variables used for limiting printing of popsize based on lines
int N = 0;
int linesize = 200;
int index = 0;
int upperlimit = 0;
int lowerlimit = maxPopSize;
int *arrayofpopsizes;
arrayofpopsizes = malloc(sizeof(int)*maxPopSize);
for(i = 0; i < maxPopSize; i++){
arrayofpopsizes[i] = N;
N += linesize;
}
if (VERYVERBOSE == 1) {
fprintf(veryverbosefilepointer, "Variables initialized, preparing to begin simulation.\n");
fflush(veryverbosefilepointer);
}
//BEGIN THE SIMULATION FOR LOOP
while (t < maxTime) {
if(popsize < 3){
fprintf(summarydatafilepointer, "Population died during run at time %f", t);
birthrate = arrayofbirthrates[popsize];
fprintf(rawdatafilepointer, "%f\t%d\t%Lf\t%Lf\t%f\n", t, popsize, (sumofdeathrates/(double)popsize), ((sumofdeathratessquared/(double)popsize) - (long double) pow((sumofdeathrates/(double)popsize),2)), (birthrate/(double)popsize), (sumofload/(double)popsize), ((sumofloadsquared/(double)popsize) - (long double) pow((sumofloadsquared/(double)popsize),2)));
break;
}
if(popsize >= (maxPopSize-1)){
fprintf(summarydatafilepointer, "Population achieved its maximum population size at time %f", t);
birthrate = arrayofbirthrates[popsize];
fprintf(rawdatafilepointer, "%f\t%d\t%Lf\t%Lf\t%f\n", t, popsize, (sumofdeathrates/(double)popsize), ((sumofdeathratessquared/(double)popsize) - (long double) pow((sumofdeathrates/(double)popsize),2)), (birthrate/(double)popsize), (sumofload/(double)popsize), ((sumofloadsquared/(double)popsize) - (long double) pow((sumofloadsquared/(double)popsize),2)));
break;
}
if(tskitstatus == 2 && t >= genafterburnin){
isburninphaseover = 1;
}
if (isredinmaxpopsize && t >= redtime){
K = --K;
if(r == 1.0){
kappa = K/(s*i_init);
} else{
if(deleteriousdistribution == 0){
kappa = (1-r)*K/(s);
} else if(deleteriousdistribution == 1){
kappa = -(log(r)*K)/(s);
}
}
calcRateofBirths(arrayofbirthrates, maxPopSize, kappa, b_0);
redtime += redinmaxpopsize;
}
birthhappens = monteCarloStep(arrayofbirthrates, popsize, pCurrenttime, sumofdeathrates);//This is the monte carlo step. This decides if a birth or a death event takes place by returning a 0 or 1
PerformOneEventAbs(tskitstatus, isburninphaseover, ismodular, elementsperlb, &treesequencetablecollection, wholepopulationnodesarray, wholepopulationsitesarray, pPopSize, pCurrenttime, wholepopulationgenomes, wholepopulationselectiontree, wholepopulationdeathratesarray, wholepopulationisfree, wholepopulationindex, psumofdeathrates, psumofdeathratessquared, psumofload, psumofloadsquared, parent1gamete, parent2gamete, totaltimesteps, isabsolute, birthhappens, maxPopSize, chromosomesize, numberofchromosomes, totalindividualgenomelength, deleteriousmutationrate, Sd, deleteriousdistribution, beneficialmutationrate, Sb, beneficialdistribution, b_0, r, i_init, s, randomnumbergeneratorforgamma, miscfilepointer);
if (tskitstatus == 2){
if (isburninphaseover != 0){
//This SECTION covers the search for fixed mutations and their time of fixation
if (iscalcfixation)
{
if (t > simplifyat)
{
//sort the table
returnvaluefortskfunctions = tsk_table_collection_sort(&treesequencetablecollection, NULL, 0);
check_tsk_error(returnvaluefortskfunctions);
fprintf(miscfilepointer, "\n tree sequence table collection sorted. \n");
fflush(miscfilepointer);
//reindex the table
returnvaluefortskfunctions = tsk_table_collection_build_index(&treesequencetablecollection, 0);
check_tsk_error(returnvaluefortskfunctions);
fprintf(miscfilepointer, "\n tree sequence table collection index built. \n");
fflush(miscfilepointer);
tsk_table_collection_print_state(&treesequencetablecollection, miscfilepointer);
//change sample status of nodes alive in the population
for (k = 0; k < (2*maxPopSize); k++) {
tablepointer->nodes.flags[wholepopulationnodesarray[k]] = TSK_NODE_IS_SAMPLE;
}
//create tree sequence object
tsk_treeseq_t treesequence;
returnvaluefortskfunctions = tsk_treeseq_init(&treesequence, &treesequencetablecollection, 0);
check_tsk_error(returnvaluefortskfunctions);
fprintf(miscfilepointer, "\n tree sequence object initialized. \n");
fflush(miscfilepointer);
fprintf(miscfilepointer, "\n sample number %lld. \n", (long long) tsk_treeseq_get_num_samples(&treesequence));
//create tree object
tsk_tree_t tree;
int ret;
//initialize a tree object
ret = tsk_tree_init(&tree, &treesequence, 0);
check_tsk_error(ret);
fprintf(miscfilepointer, "\n tree object initialized. \n");
fflush(miscfilepointer);
for (ret= tsk_tree_first(&tree); ret == TSK_TREE_OK; ret = tsk_tree_next(&tree))
{
fprintf(miscfilepointer, "\n analyzing tree \n");
fflush(miscfilepointer);
fprintf(miscfilepointer, "\n (within tree) number of roots of tree %lld is %lld. \n", (long long) tree.index, (long long) tsk_tree_get_num_roots(&tree));
fflush(miscfilepointer);
//operation on a tree is to find the MRCA of the sample and then all the nodes between the MRCA and the root
FindFixedMutations(&tree, tskitdatafilepointer, miscfilepointer);
fprintf(miscfilepointer, "\n analyzing next tree \n");
fflush(miscfilepointer);
}
check_tsk_error(ret);
fprintf(miscfilepointer, "\n tree sequence analysis completed. \n");
fflush(miscfilepointer);
tsk_tree_free(&tree);
tsk_treeseq_free(&treesequence);
//sort the table
returnvaluefortskfunctions = tsk_table_collection_sort(&treesequencetablecollection, NULL, 0);
check_tsk_error(returnvaluefortskfunctions);
//simplify after finishing the fixation part
returnvaluefortskfunctions = tsk_table_collection_simplify(&treesequencetablecollection, wholepopulationnodesarray, (2*maxPopSize), 0, NULL);
check_tsk_error(returnvaluefortskfunctions);
for (k = 0; k < (2*maxPopSize); k++) {
wholepopulationnodesarray[k] = k;
}
simplifyat += simplifyeach;
}
}
//printing section
if (t > printtime){
birthrate = arrayofbirthrates[popsize];
if (t > updatesumtime){
sumofdeathrates = Fen_sum(wholepopulationselectiontree, maxPopSize);
updatesumtime += updatesumofdeathrateseach;
}
if (popsize > upperlimit || popsize < lowerlimit){
index = SearchforPopsize(arrayofpopsizes, maxPopSize, popsize);
upperlimit = arrayofpopsizes[index];
lowerlimit = arrayofpopsizes[index-1];
fprintf(rawdatafilepointer, "%f\t%d\t%Lf\t%Lf\t%f\t%Lf\t%Lf\n", t, (upperlimit+lowerlimit)/2, (sumofdeathrates/(double)popsize), ((sumofdeathratessquared/(double)popsize) - (long double) pow((sumofdeathrates/(double)popsize),2)), (birthrate/(double)popsize), (sumofload/(double)popsize));
}
if((int)t % 1000 == 0){
fflush(rawdatafilepointer);
}
}
}
} else if (tskitstatus == 1){
if (isburninphaseover != 0){
//This SECTION covers the search for fixed mutations and their time of fixation
if (iscalcfixation)
{
if (t > simplifyat)
{
//sort the table
returnvaluefortskfunctions = tsk_table_collection_sort(&treesequencetablecollection, NULL, 0);
check_tsk_error(returnvaluefortskfunctions);
fprintf(miscfilepointer, "\n tree sequence table collection sorted. \n");
fflush(miscfilepointer);
//reindex the table
returnvaluefortskfunctions = tsk_table_collection_build_index(&treesequencetablecollection, 0);
check_tsk_error(returnvaluefortskfunctions);
fprintf(miscfilepointer, "\n tree sequence table collection index built. \n");
fflush(miscfilepointer);
tsk_table_collection_print_state(&treesequencetablecollection, miscfilepointer);
//change sample status of nodes alive in the population
for (k = 0; k < (2*maxPopSize); k++) {
tablepointer->nodes.flags[wholepopulationnodesarray[k]] = TSK_NODE_IS_SAMPLE;
}
//create tree sequence object
tsk_treeseq_t treesequence;
returnvaluefortskfunctions = tsk_treeseq_init(&treesequence, &treesequencetablecollection, 0);
check_tsk_error(returnvaluefortskfunctions);
fprintf(miscfilepointer, "\n tree sequence object initialized. \n");
fflush(miscfilepointer);
fprintf(miscfilepointer, "\n sample number %lld. \n", (long long) tsk_treeseq_get_num_samples(&treesequence));
//create tree object
tsk_tree_t tree;
int ret;
//initialize a tree object
ret = tsk_tree_init(&tree, &treesequence, 0);
check_tsk_error(ret);
fprintf(miscfilepointer, "\n tree object initialized. \n");
fflush(miscfilepointer);
for (ret= tsk_tree_first(&tree); ret == TSK_TREE_OK; ret = tsk_tree_next(&tree))
{
fprintf(miscfilepointer, "\n analyzing tree \n");
fflush(miscfilepointer);
fprintf(miscfilepointer, "\n (within tree) number of roots of tree %lld is %lld. \n", (long long) tree.index, (long long) tsk_tree_get_num_roots(&tree));
fflush(miscfilepointer);
//operation on a tree is to find the MRCA of the sample and then all the nodes between the MRCA and the root
FindFixedMutations(&tree, tskitdatafilepointer, miscfilepointer);
fprintf(miscfilepointer, "\n moving to next tree \n");
fflush(miscfilepointer);
}
fprintf(miscfilepointer, "\n tree sequence analysis completed. \n");
fflush(miscfilepointer);
tsk_tree_free(&tree);
tsk_treeseq_free(&treesequence);
//sort the table
returnvaluefortskfunctions = tsk_table_collection_sort(&treesequencetablecollection, NULL, 0);
check_tsk_error(returnvaluefortskfunctions);
//simplify after finishing the fixation part
returnvaluefortskfunctions = tsk_table_collection_simplify(&treesequencetablecollection, wholepopulationnodesarray, (2*maxPopSize), 0, NULL);
check_tsk_error(returnvaluefortskfunctions);
for (k = 0; k < (2*maxPopSize); k++) {
wholepopulationnodesarray[k] = k;
}
simplifyat += simplifyeach;
}
} else{
if (t > simplifyat) {
returnvaluefortskfunctions = tsk_table_collection_sort(&treesequencetablecollection, NULL, 0);
check_tsk_error(returnvaluefortskfunctions);
returnvaluefortskfunctions = tsk_table_collection_simplify(&treesequencetablecollection, wholepopulationnodesarray, (2*maxPopSize), 0, NULL);
check_tsk_error(returnvaluefortskfunctions);
for (k = 0; k < (2*maxPopSize); k++) {
wholepopulationnodesarray[k] = k;
}
simplifyat += simplifyeach;
}
}
}
//printing section
if(t > printtime){
birthrate = arrayofbirthrates[popsize];
if (t > updatesumtime){
sumofdeathrates = Fen_sum(wholepopulationselectiontree, maxPopSize);
updatesumtime += updatesumofdeathrateseach;
}
fprintf(rawdatafilepointer, "%f\t%d\t%Lf\t%Lf\t%f\t%Lf\t%Lf\n", t, popsize, (sumofdeathrates/(double)popsize), ((sumofdeathratessquared/(double)popsize) - (long double) pow((sumofdeathrates/(double)popsize),2)), (birthrate/(double)popsize), (sumofload/(double)popsize));
if((int)t % 1000 == 0){
fflush(rawdatafilepointer);
}
printtime += printeach;
}
} else{
if(t > printtime){
birthrate = arrayofbirthrates[popsize];
if (t > updatesumtime){
sumofdeathrates = Fen_sum(wholepopulationselectiontree, maxPopSize);
updatesumtime += updatesumofdeathrateseach;
}
fprintf(rawdatafilepointer, "%f\t%d\t%Lf\t%Lf\t%f\t%Lf\t%Lf\n", t, popsize, (sumofdeathrates/(double)popsize), ((sumofdeathratessquared/(double)popsize) - (long double) pow((sumofdeathrates/(double)popsize),2)), (birthrate/(double)popsize), (sumofload/(double)popsize));
if((int)t % 1000 == 0){
fflush(rawdatafilepointer);
}
printtime += printeach;
}
}
}
//END OF SIMULATION FOR LOOP
//Tree sequence recording requires that tables are sorted on the back end,
//so I sort once again here at the end to ensure that all tables are sorted before they're read to file.
//This might be inefficient, I'm not sure.
if(tskitstatus != 0){
printf("Sort at final generation %lld: (%lld nodes %lld edges)",
(long long) t,
(long long) tablepointer->nodes.num_rows,
(long long) tablepointer->edges.num_rows);
returnvaluefortskfunctions = tsk_table_collection_sort(&treesequencetablecollection, NULL, 0);
check_tsk_error(returnvaluefortskfunctions);
returnvaluefortskfunctions = tsk_table_collection_simplify(&treesequencetablecollection, wholepopulationnodesarray, (2*maxPopSize), 0, NULL);
check_tsk_error(returnvaluefortskfunctions);
printf(" -> (%lld nodes %lld edges)\n",
(long long) tablepointer->nodes.num_rows,
(long long) tablepointer->edges.num_rows);
for (k = 0; k < (2*maxPopSize); k++) {
wholepopulationnodesarray[k] = k;
}
//Printing out the node table in a way readable by python on the back end.
fprintf(nodefilepointer, "is_sample time\n");
for (k = 0; k < tablepointer->nodes.num_rows; k++) {
if (k < (2*popsize)) {
fprintf(nodefilepointer, "1 %f\n", tablepointer->nodes.time[k]);
fflush(nodefilepointer);
} else {
fprintf(nodefilepointer, "0 %f\n", tablepointer->nodes.time[k]);
fflush(nodefilepointer);
}
}
//Printing out the edge table in a way readable by python on the back end.
fprintf(edgefilepointer, "left right parent child\n");
for (k = 0; k < tablepointer->edges.num_rows; k++) {
fprintf(edgefilepointer, "%f %f %d %d\n", tablepointer->edges.left[k], tablepointer->edges.right[k], tablepointer->edges.parent[k], tablepointer->edges.child[k]);
fflush(edgefilepointer);
}
//Printing out the site table in a way readable by python.
fprintf(sitefilepointer, "position ancestral_state\n");
for (k = 0; k < tablepointer->sites.num_rows; k++) {
fprintf(sitefilepointer, "%f 0.0\n", tablepointer->sites.position[k]);
fflush(sitefilepointer);
}
//Printing out the mutation table in a way readable by python.
fprintf(mutationfilepointer, "site node time derived_state\n");
for (k = 0; k < tablepointer->mutations.num_rows; k++) {
fprintf(mutationfilepointer, "%d %d %f %.12s\n", tablepointer->mutations.site[k], tablepointer->mutations.node[k], tablepointer->mutations.time[k], (tablepointer->mutations.derived_state + k*12));
fflush(mutationfilepointer);
}
}
if (VERYVERBOSE == 1) {
fprintf(veryverbosefilepointer, "Finished simulation with mean sb %f \n", Sb);
fprintf(veryverbosefilepointer, "Time elapsed: %f\n", t);
fprintf(veryverbosefilepointer, "Final population size was: %d\n", popsize);
}
FILE *popsnapshotfilepointer;
char* popsnapshotfilename = MakePopSnapshotFileName(mubname, Sbname);
popsnapshotfilepointer = fopen(popsnapshotfilename, "w"); //opens the file to which to print summary data.
WritePopSnapshot(wholepopulationgenomes, totalpopulationgenomelength, sumofdeathrates, sumofdeathratessquared, sumofload, sumofloadsquared, wholepopulationselectiontree, wholepopulationdeathratesarray, wholepopulationisfree, wholepopulationindex, maxPopSize, popsize, t, popsnapshotfilepointer);
fclose(rawdatafilepointer);
fclose(summarydatafilepointer);
fclose(nodefilepointer);
fclose(edgefilepointer);
fclose(sitefilepointer);
fclose(mutationfilepointer);
fclose(popsnapshotfilepointer);
if (iscalcfixation)
{
fclose(tskitdatafilepointer);
}
free(popsnapshotfilename);
free(rawdatafilename);
free(summarydatafilename);
free(arrayofbirthrates);
free(arrayofpopsizes);
free(logaveragefitnesseachNtimesteps);
free(literallyjustlast200Ntimesteps);
free(last200Ntimestepsvariance);
free(wholepopulationgenomes);
free(parent1gamete);
free(parent2gamete);
free(wholepopulationselectiontree);
free(wholepopulationdeathratesarray);
free(sortedwisarray);
free(wholepopulationisfree);
free(wholepopulationindex);
if (tskitstatus != 0){
free(wholepopulationnodesarray);
}
tsk_table_collection_free(&treesequencetablecollection);
return 0;
}
//calculates every possible birth rate for every possible value of population size within range [0-MaxPopSize]
void calcRateofBirths(double *arrayofbirthrates, int maxPopSize, int kappa, double b_0) {
int i;
for(i = 0; i < maxPopSize; i++){
arrayofbirthrates[i] = (b_0) * (double)i * (1 - ((double)i/(double)kappa));
}
}
//searches for where the current popsize is an array of offset lines to determine upper and lower limit. This function serves the module of limiting excessive printing.
int SearchforPopsize(int *a, int n, int popsize) {
int i = 0;
while (i < n && a[i] < popsize) i++;
return i;
}
//returns output of either birth or death
bool monteCarloStep(double *arrayofbirthrates, int popsize, double *pCurrentTime, double sumofdeathrates) {
double deathRate;
double birthRate;
double timestep;
deathRate = sumofdeathrates;
//rate of births is calculated using equation used in lab write up
birthRate = arrayofbirthrates[popsize];
timestep = 1/(deathRate + birthRate);//To make time steps dynamical, we directly use the inverse of the sum of the rates as value for a time step.
*pCurrentTime += timestep;
//This is the actual monte carlo step
return discoverEvent(deathRate, birthRate);
}
bool discoverEvent(double deathRate, double birthRate) {
bool boolBirth;
double cutOffPoint, randomNumber;
randomNumber = ldexp(pcg32_random(), -32);
//if lands on the cutoff point death occurs, technically skewing towards death but is very minor.
cutOffPoint = deathRate/(deathRate + birthRate);
if (randomNumber > cutOffPoint)
boolBirth = 1;
else
boolBirth = 0;
return boolBirth;
}
bool PerformOneEventAbs(int tskitstatus, int isburninphaseover, bool ismodular, int elementsperlb, tsk_table_collection_t *treesequencetablecollection, tsk_id_t * wholepopulationnodesarray, tsk_id_t * wholepopulationsitesarray, int *pPopSize, double * pCurrenttime, double *wholepopulationgenomes, long double *wholepopulationselectiontree, long double *wholepopulationdeathratesarray, bool *wholepopulationisfree, int *wholepopulationindex, long double *psumofdeathrates, long double *psumofdeathratessquared, long double *psumofload, long double *psumofloadsquared, double* parent1gamete, double* parent2gamete, int totaltimesteps, bool isabsolute, bool birthhappens, int maxPopSize, int chromosomesize, int numberofchromosomes, int totalindividualgenomelength, double deleteriousmutationrate, double Sd, int deleteriousdistribution, double beneficialmutationrate, double Sb, int beneficialdistribution, double b_0, double r, int i_init, double s, gsl_rng* randomnumbergeneratorforgamma, FILE *miscfilepointer)
{
if(isabsolute == 0){
fprintf(miscfilepointer, "\n Trying to use PerformOneEventAbs within a non absolute fitness simulation. \n");
exit(0);
}
int randparent1, randparent2, currentparent1, currentparent2, currentvictim;
int i;
bool nolethalmut = true;
int victim, birthplace;
if(*pPopSize < 2){
fprintf(miscfilepointer, "\n Trying to use PerformOneEventAbs with a population size lower than 2. \n");
exit(0);
}
if(*pPopSize >= maxPopSize && birthhappens){
fprintf(miscfilepointer, "\n Trying to use PerformOneEventAbs with a population size greater than maxPopSize. \n");
exit(0);
}
//next pointers are only used in relative fitness scenarios. Here, they are just initialized
long double *psumofloads, *wholepopulationwisarray;
if (birthhappens){
randparent1 = ChooseParent(*pPopSize);
currentparent1 = wholepopulationindex[randparent1];
do{
randparent2 = ChooseParent(*pPopSize);
} while(randparent2 == randparent1);
currentparent2 = wholepopulationindex[randparent2];
if(wholepopulationisfree[currentparent1] || wholepopulationisfree[currentparent2]){
fprintf(miscfilepointer, "\n Trying to give birth to a new individual using a parent that is not present in PerformOneEventAbs. \n");
exit(0);
}
tsk_id_t childnode1, childnode2;
double currenttime;
RecombineChromosomesIntoGamete(isabsolute, tskitstatus, ismodular, elementsperlb, isburninphaseover, treesequencetablecollection, wholepopulationnodesarray, &childnode1, totaltimesteps, currenttime, currentparent1, chromosomesize, numberofchromosomes, parent1gamete, wholepopulationgenomes, totalindividualgenomelength);
nolethalmut = ProduceMutatedGamete(tskitstatus, isburninphaseover, treesequencetablecollection, wholepopulationnodesarray, wholepopulationsitesarray, &childnode1, totaltimesteps, currenttime, currentparent1, isabsolute, totalindividualgenomelength, deleteriousmutationrate, beneficialmutationrate, Sb, beneficialdistribution, Sd, deleteriousdistribution, parent1gamete, randomnumbergeneratorforgamma, miscfilepointer);
if(!nolethalmut)
return false;
RecombineChromosomesIntoGamete(isabsolute, tskitstatus, ismodular, elementsperlb, isburninphaseover, treesequencetablecollection, wholepopulationnodesarray, &childnode2, totaltimesteps, currenttime, currentparent2, chromosomesize, numberofchromosomes, parent2gamete, wholepopulationgenomes, totalindividualgenomelength);
nolethalmut = ProduceMutatedGamete(tskitstatus, isburninphaseover, treesequencetablecollection, wholepopulationnodesarray, wholepopulationsitesarray, &childnode2, totaltimesteps, currenttime, currentparent2, isabsolute, totalindividualgenomelength, deleteriousmutationrate, beneficialmutationrate, Sb, beneficialdistribution, Sd, deleteriousdistribution, parent2gamete, randomnumbergeneratorforgamma, miscfilepointer);
if(!nolethalmut)
return false;
PerformBirth(tskitstatus, isburninphaseover, ismodular, elementsperlb, treesequencetablecollection, wholepopulationnodesarray, childnode1, childnode2, isabsolute, parent1gamete, parent2gamete, maxPopSize, pPopSize, birthplace, wholepopulationgenomes, totalindividualgenomelength, deleteriousdistribution, wholepopulationselectiontree, wholepopulationwisarray, wholepopulationdeathratesarray, wholepopulationindex, wholepopulationisfree, psumofloads, psumofdeathrates, psumofdeathratessquared, b_0, r, i_init, s, psumofload, psumofloadsquared, miscfilepointer);
}
else{
// use of the fennwick tree to find the victim in the population, note that since fenwick tree stores all the population (non occupied spaces have a fitness of 0) there is not need to use the wholepopulationindex, fenwick search already gives you the space that the selected individual occupies.
victim = ChooseVictimWithTree(wholepopulationselectiontree, *pPopSize, maxPopSize, *psumofdeathrates, miscfilepointer);
// printf("%d\n", victim);
//
// for(i = 0; i < maxPopSize; i++)
// printf("%2d ", wholepopulationisfree[i]);
// printf("\n");
PerformDeath(isabsolute, tskitstatus, isburninphaseover, maxPopSize, pPopSize, victim, deleteriousdistribution, wholepopulationselectiontree, wholepopulationwisarray, wholepopulationdeathratesarray, wholepopulationindex, wholepopulationisfree, psumofloads, psumofdeathrates,psumofdeathratessquared, b_0, r, i_init, s, psumofload, psumofloadsquared, wholepopulationnodesarray, miscfilepointer);
}
return true;
}
void InitializePopulationAbs(int tskitstatus, tsk_table_collection_t * treesequencetablecollection, tsk_id_t * wholepopulationnodesarray, tsk_id_t * wholepopulationsitesarray, long double *wholepopulationselectiontree, long double *wholepopulationdeathratesarray, int *wholepopulationindex, bool *wholepopulationisfree, int initialPopSize, int maxPopSize, int totaltimesteps, int deleteriousdistribution, double *wholepopulationgenomes, int totalpopulationgenomelength, long double *psumofdeathrates, long double *psumofdeathratessquared, long double *psumofload, long double *psumofloadsquared, double b_0, double r, int i_init, double s)
{
int i, j;
double haploidgenomelength = (double) ((totalpopulationgenomelength / maxPopSize) / 2);
double starting_load;
if(r == 1.0){
starting_load = b_0 - s*i_init;
}
else{
if(deleteriousdistribution == 0){
starting_load = b_0 - s*(1 - pow(r, i_init))/(1-r);
}
else if(deleteriousdistribution == 1){
starting_load = b_0 - s*(pow(r, (i_init -1)) -1)/(log(r));
}
}
for (i = 0; i < initialPopSize; i++) {
wholepopulationselectiontree[i] = starting_load; //all individuals start with death rate d_0. Currently d_0 is set through the input parameters
wholepopulationdeathratesarray[i] = starting_load;
wholepopulationindex[i] = i;
wholepopulationisfree[i] = false;
}
for (i = initialPopSize; i < maxPopSize; i++) {
wholepopulationselectiontree[i] = 0.0;
wholepopulationdeathratesarray[i] = 0.0;
wholepopulationindex[i] = i;
wholepopulationisfree[i] = true;
}
//this for loop taken from the Fen_init function in sample implementation from 'Fenwick tree' Wikipedia page. Absolute trees needs to contemplate all popSize, including non occupied spaces.
for (i = 0; i < maxPopSize; i++) {
j = i + LSB(i+1);
if (j < maxPopSize) {
wholepopulationselectiontree[j] += wholepopulationselectiontree[i];
}
}
*psumofload = (long double) initialPopSize * i_init;
*psumofloadsquared = (long double) initialPopSize * pow(i_init, 2);
*psumofdeathrates = (long double) initialPopSize * starting_load;
*psumofdeathratessquared = (long double) initialPopSize * pow(starting_load, 2);
for (i = 0; i < totalpopulationgenomelength; i++){
wholepopulationgenomes[i] = 0.0;
}
if (tskitstatus != 0){
treesequencetablecollection->sequence_length = haploidgenomelength;
//The following lines initialize the node table for tree sequence recording.
//Note that nodes here are single sets of chromosomes, so the 2x popsize here assumes diploidy.
for (i = 0; i < (2 * maxPopSize); i++) {
wholepopulationnodesarray[i] = tsk_node_table_add_row(&treesequencetablecollection->nodes, 0, totaltimesteps, TSK_NULL, TSK_NULL, NULL, 0);
check_tsk_error(wholepopulationnodesarray[i]);
}
//The following lines add a site to the tree sequence recording site table corresponding to each linkage block, with ancestral state of 0.
for (i = 0; i < haploidgenomelength; i++) {
wholepopulationsitesarray[i] = tsk_site_table_add_row(&treesequencetablecollection->sites, i, "0.0000000000", 12, NULL, 0);
check_tsk_error(wholepopulationsitesarray[i]);
}
}
}
//used to initialize a population using a file that stores all the important variables
void InitializeWithSnapshotAbs(long double *wholepopulationselectiontree, long double *wholepopulationdeathratesarray, int *wholepopulationindex, bool *wholepopulationisfree, int maxPopSize, double *wholepopulationgenomes, int totalpopulationgenomelength, long double *psumofdeathrates, long double *psumofdeathratessquared, long double *psumofload, long double *psumofloadsquared, int *pPopSize, double *pCurrenttime, FILE *prevsnapshotfilepointer, FILE *miscfilepointer)
{
int i, j;
char strtemp[200];
//gets the genomes of the whole population from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
if(strcmp(strtemp, "Genomes:")){
fprintf(miscfilepointer, "\nError: Corrupted snapshot file, headers do not include Genomes: check that the snapshot file is in the correct parameters folder");
exit(0);
}
for (i = 0; i < totalpopulationgenomelength; i++){
fscanf(prevsnapshotfilepointer, "%lf", &wholepopulationgenomes[i]);
}
//gets the sum of death rates from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
if(strcmp(strtemp, "Sum_of_death_rates:")){
fprintf(miscfilepointer, "\nError: Corrupted snapshot file, headers do not include Sum_of_death_rates: check that the snapshot file is in the correct parameters folder or that there are no errors in the file");
exit(0);
}
fscanf(prevsnapshotfilepointer, "%Lf", psumofdeathrates);
//gets the sum of death rates squared from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
fscanf(prevsnapshotfilepointer, "%Lf", psumofdeathratessquared);
//gets the sum of load from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
fscanf(prevsnapshotfilepointer, "%Lf", psumofload);
//gets the sum of load sqaured from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
fscanf(prevsnapshotfilepointer, "%Lf", psumofloadsquared);
//gets the selection tree from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
for (i = 0; i < maxPopSize; i++){
fscanf(prevsnapshotfilepointer, "%Lf", &wholepopulationselectiontree[i]);
}
//gets the selection tree from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
for (i = 0; i < maxPopSize; i++){
fscanf(prevsnapshotfilepointer, "%Lf", &wholepopulationdeathratesarray[i]);
}
//since fscanf does not read bools, first store the value in an int
int tempspace;
//gets the free spaces in the population from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
for (i = 0; i < maxPopSize; i++){
fscanf(prevsnapshotfilepointer, "%d", &tempspace);
wholepopulationisfree[i] = tempspace;
}
//gets the index array from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
for (i = 0; i < maxPopSize; i++){
fscanf(prevsnapshotfilepointer, "%d", &wholepopulationindex[i]);
}
//gets the popsize from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
fscanf(prevsnapshotfilepointer, "%d", pPopSize);
//gets the time from the snapshot file
fscanf(prevsnapshotfilepointer, "%s" , strtemp);
if(strcmp(strtemp, "Time:")){
fprintf(miscfilepointer, "\nError: Corrupted snapshot file, headers do not include Time: check that the snapshot file is in the correct parameters folder or that there are no errors in the file");
exit(0);
}
fscanf(prevsnapshotfilepointer, "%lf", pCurrenttime);
}
int ChooseParent(int populationsize)
{
return pcg32_boundedrand(populationsize);
}
int ChooseVictimWithTree(long double* wholepopulationselectiontree, int popsize, int maxPopSize, long double inversesumofloads, FILE *miscfilepointer)
{
long double randomnumberofdeath;
int newVictim = 0;
randomnumberofdeath = (long double)ldexp(pcg32_random(), -32) * (inversesumofloads);
//Above line generates a random integer between 0 and 2^32, then multiplies by 2^-32
//to generate a float between 0 and 1 and then multiplies by the sum of wis
//to get a number between 0 and the sum of wis.
int leftbound, rightbound;
leftbound = 0;
rightbound = maxPopSize;
if (leftbound >= rightbound) {
return -1;
fprintf(miscfilepointer, "\nError: population size is %d.", popsize);
}
newVictim = SearchTree(leftbound, rightbound, randomnumberofdeath, wholepopulationselectiontree);
return newVictim;
}
int findinindex(int *wholepopulationindex, int which, int tam, FILE *miscfilepointer){
int i;
bool placefound = false;
for(i = 0; i < tam; i++){
if(wholepopulationindex[i] == which){
placefound = true;
return i;
}
}
if(!placefound){
fprintf(miscfilepointer, "\n Array of indexes is corrupted in findinindex. \n");
exit(0);
}
}
void indexArrayFlipDeath(int *wholepopulationindex, int placeinindex, int popsize){
/*
This function flips the integer value from the last in the array of wholepopulationindex to the place where an individual died. This way wholepopulationindex is mantained without unoccupied spaces
*/
int indexlast = wholepopulationindex[(popsize-1)];
int indexvictim = wholepopulationindex[placeinindex];
wholepopulationindex[placeinindex] = indexlast;
wholepopulationindex[(popsize-1)] = indexvictim;
}
double CalculateDeathRate(bool ismodular, int elementsperlb, double *parent1gamete, double *parent2gamete, int totalindividualgenomelength, int deleteriousdistribution,double b_0, double r, int i_init, double s)
{
double inddeathrate = 0.0;
double currentlinkageblocksload = 0.0;
double currentlinkageblocksloadmod[elementsperlb];
double sumofloadmod = 0;
int totallinkageblocks;
int i, m;
if (!ismodular){
//since the load is calculated per gamete, the total number of linkages blocks is half the total genome length of an ind
totallinkageblocks = totalindividualgenomelength/2;
for (i = 0; i < totallinkageblocks; i++) {
currentlinkageblocksload += parent1gamete[i];
currentlinkageblocksload += parent2gamete[i];
}
//load is calculated as the number of mutations per individual. An heterozygous should have 1/2 mutation, and an homozygous 1 mutation. Thus we divide the sum of the load of the two sister chromosomes by 2
currentlinkageblocksload = currentlinkageblocksload/2;
if(r == 1.0){
inddeathrate = b_0 - s*(i_init - currentlinkageblocksload);
}
else{
if(deleteriousdistribution == 0){
inddeathrate = b_0 - s*(1 - pow(r, (i_init -currentlinkageblocksload)))/(1-r);
}
else if(deleteriousdistribution == 1)
inddeathrate = b_0 - s*(pow(r, (i_init -currentlinkageblocksload -1)) -1)/(log(r));
}
}
else{
printf("Error no code for CalculateDeathRate function with modularity yet");
exit(0);
}