-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlenski_sim.cc
1231 lines (1029 loc) · 41.1 KB
/
lenski_sim.cc
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 "lenski_sim.hh"
#include <algorithm>
#include <numeric>
#include <errno.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cmath>
#include <time.h>
#include <sstream>
#include <fstream>
#include <string>
#include <cassert>
#include <gsl/gsl_randist.h>
#include <boost/math/distributions/hypergeometric.hpp>
using std::normal_distribution;
using std::set_difference;
/* Class constructor. Initializes the simulation and sets
* the simulation parameters. */
lenski_sim::lenski_sim(
const int _L,
const int _N_0,
const int _N_f,
const double _p,
const double _rho,
const double _sigh,
const double _muJ,
const double _sigJ,
string _base_folder,
bool _interact,
int _output_interval,
int _init_rank,
int _rank_interval,
const int _nbins,
const double _min_select,
const double _max_select,
uint32_t _seed,
const bool _hoc,
const int _replicate_number,
bool _output_sim_info,
const int _reset_fac) :
/* Initialize the simulation parameters. */
L(_L), N_0(_N_0), N_f(_N_f), p(_p*_L),
rho(_rho), sigh(_sigh), sigJ(_sigJ), Foff(0), base_folder(_base_folder),
nbac_tot(_N_0), n_strains(1), interact(_interact),
output_interval(_output_interval), init_rank(_init_rank),
rank_interval(_rank_interval), bin_edges(new double[_nbins+1]),
bin_counters(new int[_nbins+2]), nbins(_nbins),
min_select(_min_select), max_select(_max_select), hoc(_hoc),
replicate_number(_replicate_number),
reset_index(1), reset_fac(_reset_fac)
{
// setup simulation space
output_folder = base_folder +
"/replicate" + std::to_string(replicate_number);
allocate_space(_seed, _output_sim_info);
// draw random interactions and initializations
setup_disorder();
// set the initial rank
if (init_rank >= 0) {
printf("About to update rank of the initial strain to %d.\n",
init_rank);
update_rank();
}
// output quenched disorder information to replicate folders
if (_output_sim_info) {
output_bin_edges();
output_his_bin();
if (interact) { output_Jijs_bin(); output_Jalpha_bin(); }
output_alpha0s();
}
}
/* Scale what is needed to vary the strength of epistasis. */
void lenski_sim::scale_disorder(
vector<double> unit_his,
vector<double> unit_Jijs) {
// update the disorder values
for (int ii = 0; ii < L; ii++) { his[ii] = sigh*unit_his[ii]; }
int key(0);
for (int ii = 0; ii < L; ii++) {
for (int jj = ii+1; jj < L; jj++) {
key = jj + ii*L;
Jijs[key] = sigJ*unit_Jijs[key];
}
}
// after re-scaling h and J, the initialization cannot be the same,
// because the rescaling will have
// changed the rank. hence, we need to re-compute the rank.
// moreover, we need to update the values of J*alpha0 and Foff.
// this happens inside update_rank().
if (init_rank >= 0) {
printf("About to update rank of the initial strain to %d.\n",
init_rank);
update_rank();
}
else {
update_Jalpha0();
Foff = 0;
Foff = 1 - (hoc? compute_fitness_slow_hoc(0)
: compute_fitness_slow(0));
}
}
/* Copy the quenched disorder. */
void lenski_sim::copy_disorder(
vector<double> _his,
vector<double> _Jijs,
vector<double> _alpha0s,
vector<double> _Jalpha0) {
his = _his;
Jijs = _Jijs;
// different initialization for each replicate.
if (init_rank >= 0) {
// for the new J matrix, draw a new uniform initialization,
// re-compute Jalpha0, and update to the correct rank.
for (int ii = 0; ii < L; ii++) {
alpha0s[ii] = (gsl_rng_uniform(gsl_gen) < 0.5)? 1 : -1;
}
update_Jalpha0();
printf("About to update rank of the initial strain to %d.\n",
init_rank);
update_rank();
}
// same initialization for each replicate.
else {
Jalpha0 = _Jalpha0;
alpha0s = _alpha0s;
Foff = 0;
Foff = 1 - (hoc? compute_fitness_slow_hoc(0)
: compute_fitness_slow(0));
}
mkdir(output_folder.c_str(), 0700);
output_bin_edges();
output_his_bin();
if (interact) { output_Jijs_bin(); output_Jalpha_bin(); }
output_alpha0s();
}
void lenski_sim::allocate_space(
uint32_t seed,
bool output_sim_info) {
// Declare the GSL random number generator
// empirically, taus2 seems to be the fastest option.
gsl_gen = gsl_rng_alloc(gsl_rng_taus2);
gsl_rng_set(gsl_gen, seed);
// No mutations on the initial strain by definition.
if (hoc) { mutations_hoc.emplace_back(); }
else { mutations.emplace_back(); }
mut_order.emplace_back();
fit_effects.emplace_back();
// We start with N_0 bacteria of the first strain by definition.
n_bac.push_back(N_0);
// the fitness of the first strain is one at the start by definition
// (choice of F_{offset}).
fits.push_back(1);
// And create the output folder.
if (output_sim_info) { mkdir(output_folder.c_str(), 0700); }
// Set up the bins and output information.
setup_bins();
// Preallocate space for the disorder.
his.resize(L); alpha0s.resize(L);
Jalpha0.resize(L, 0);
Jijs.resize(L*L, 0);
}
/* Draw the quenched disorder. */
void lenski_sim::setup_disorder() {
double curr_J_val(0);
int key;
for (int ii = 0; ii < L; ii++) {
his[ii] = gsl_ran_gaussian(gsl_gen, sigh);
alpha0s[ii] = (gsl_rng_uniform(gsl_gen) < 0.5)? 1 : -1;
}
if (interact) {
for (int ii = 0; ii < L; ii++) {
for (int jj = ii+1; jj < L; jj++) {
key = jj + ii*L;
curr_J_val = (gsl_rng_uniform(gsl_gen) < rho)?
gsl_ran_gaussian(gsl_gen, sigJ) : 0;
if (curr_J_val != 0) {
Jijs[key] = curr_J_val;
Jalpha0[ii] += curr_J_val*alpha0s[jj];
Jalpha0[jj] += curr_J_val*alpha0s[ii];
}
}
}
}
check_Jalpha0();
Foff = 1 - (hoc? compute_fitness_slow_hoc(0) : compute_fitness_slow(0));
}
/* Draws a Poisson random number via inversion by sequential search.
* Fast for small values of $\mu$. */
int lenski_sim::draw_poisson(double lambda) {
int x = 0;
double p = exp(-lambda);
double s = p;
double u = gsl_rng_uniform(gsl_gen);
while (u > s) { x++; p *= lambda/x; s += p; }
return x;
}
/* Step the simulation forward by dt seconds. */
void lenski_sim::step_forward(double dt) {
// Change in number of bacteria for the current (looped over) strain.
double dN(0);
// Number of mutations for the current (looped over) strain in the time dt.
int n_mutants(0),
new_strains(0), // Number of new strains after mutations have occurred.
mutant_ind(0); // Current index of the (looped over) mutation.
double new_fit(0), new_effect(0);
double alphak_p(0);
double poisson_mu(0);
// Compute the change in the number of cells for each strain,
// as well as the mutations that stem from each strain.
for (int curr_strain = 0; curr_strain < n_strains; curr_strain++) {
// figure out the number of mutant strains
dN = n_bac[curr_strain]*(exp(fits[curr_strain]*dt) - 1);
poisson_mu = dN*p;
n_mutants = poisson_mu < 1.0? draw_poisson(poisson_mu)
: gsl_ran_poisson(gsl_gen, poisson_mu); // slightly speedier hack
// ensure we don't draw more than the total population
n_mutants = (n_mutants > dN)? dN : n_mutants;
n_mutants_so_far += n_mutants;
// adjust the current and the overall population
n_bac[curr_strain] += (dN - n_mutants);
nbac_tot += dN;
// for each mutant, flip the spin and join or define new strains.
for (int curr_mutant = 0; curr_mutant < n_mutants; curr_mutant++) {
// draw the random spin to flip
mutant_ind = gsl_rng_uniform_int(gsl_gen, L);
// check if this strain already exists.
auto curr_mut_order = mut_order[curr_strain];
curr_mut_order.push_back(mutant_ind);
auto mut_exists_it = current_strains.find(curr_mut_order);
if (mut_exists_it != current_strains.cend()) {
n_bac[mut_exists_it->second]++;
}
// otherwise, create a new strain
else {
// grab the parent set of mutations
unordered_set<int> curr_muts = mutations[curr_strain];
auto mut_iterator = curr_muts.find(mutant_ind);
// update the set of mutations of the child
if (mut_iterator == curr_muts.cend()) {
curr_muts.insert(mutant_ind);
alphak_p = alpha0s[mutant_ind];
}
else {
curr_muts.erase(mut_iterator);
alphak_p = -alpha0s[mutant_ind];
}
// compute the fitness using the parent set of mutations
// note that curr_muts is fine to pass, because any
// additional term in compute_fitness will just be zero.
new_fit = compute_fitness(curr_strain, mutant_ind,
curr_muts, alphak_p);
fits.push_back(new_fit);
// update mutation information.
// avoid excessive copying with std::move
mut_order.push_back(std::move(curr_mut_order));
mutations.push_back(std::move(curr_muts));
current_strains[curr_mut_order] = n_strains + new_strains;
// store the fitness effect information
auto curr_fit_effects = fit_effects[curr_strain];
new_effect = new_fit - fits[curr_strain];
curr_fit_effects.push_back(new_effect);
fit_effects.push_back(std::move(curr_fit_effects));
bin_counters[find_bin_ind(new_effect/fits[curr_strain])]++;
// update strain counter and total number of bacteria
new_strains++;
n_bac.push_back(1.0);
}
}
}
n_strains += new_strains;
}
/* Step the simulation forward by dt seconds,
* with an uncorrelated house of cards landscape at each gene. */
void lenski_sim::step_forward_hoc(double dt) {
// Change in number of bacteria for the current (looped over) strain.
double dN(0);
// Number of mutations for the current (looped over) strain in the time dt.
int n_mutants(0),
new_strains(0), // Number of new strains after mutations have occurred.
mutant_ind(0); // Current index of the (looped over) mutation.
time_t ts_t(0), te_t(0);
double new_fit(0), new_effect(0);
double alpha_ck(0), Delta_ck(0);
// Compute the change in the number of cells for each strain,
// as well as the mutations that stem from each strain.
for (int curr_strain = 0; curr_strain < n_strains; curr_strain++) {
// draw the mutants
dN = n_bac[curr_strain]*(exp(fits[curr_strain]*dt) - 1);
// don't do the random draw if we have less
// than a single bacterium to save time
n_mutants = (dN < 1)? 0 : gsl_ran_poisson(gsl_gen, dN*p*L);
// the poisson rng can sometimes draw more mutants than
// there were in the original population; stop this.
n_mutants = (n_mutants <= dN)? n_mutants : dN;
n_bac[curr_strain] += (dN - n_mutants);
nbac_tot += dN;
time(&ts_t);
for (int curr_mutant = 0; curr_mutant < n_mutants; curr_mutant++) {
// draw where the mutant occurred
mutant_ind = gsl_rng_uniform_int(gsl_gen, L);
// store the sequence of mutations (used for testing fixed
// mutations in post-processing)
auto curr_mut_order = mut_order[curr_strain];
curr_mut_order.push_back(mutant_ind);
// draw the new spin value and update the mutation increments.
alpha_ck = 2*gsl_rng_uniform(gsl_gen) - 1;
unordered_map<int, double> curr_muts = mutations_hoc[curr_strain];
auto mut_iterator = curr_muts.find(mutant_ind);
// Delta_ck = \alpha_k^c - \alpha_k^p
Delta_ck = alpha_ck - alpha0s[mutant_ind]
- ((mut_iterator == curr_muts.cend())? 0
: curr_muts[mutant_ind]);
// curr_muts[k] = \alpha_k^P - \alpha_k^m
curr_muts[mutant_ind] = alpha_ck - alpha0s[mutant_ind];
// update mutation information
mut_order.push_back(curr_mut_order);
mutations_hoc.push_back(curr_muts);
// compute and save the fitness for the new strain
new_fit = compute_fitness_hoc(curr_strain, mutant_ind,
Delta_ck,
mutations_hoc[curr_strain]);
fits.push_back(new_fit);
// store the fitness effect information
auto curr_fit_effects = fit_effects[curr_strain];
new_effect = new_fit - fits[curr_strain];
curr_fit_effects.push_back(new_effect);
fit_effects.push_back(curr_fit_effects);
bin_counters[find_bin_ind(new_effect/fits[curr_strain])]++;
// update strain counter and total number of bacteria
new_strains++;
n_bac.push_back(1);
}
}
time(&te_t);
n_strains += new_strains;
}
/* Checks for strains with zero bacteria. */
void lenski_sim::check_nbac_wtf() {
for (int ii = 0; ii < n_strains; ii++) {
int curr_nbac = n_bac[ii];
if (curr_nbac <= 0) { printf("WTF on strain: %d\n", ii); }
}
}
/* Computes the fitness using the full definition, for testing other
* fitness computation methods.
* Used for +-1-valued spins. */
double lenski_sim::compute_fitness_slow(int strain_index) {
double fit(0);
double alpha_i, alpha_j;
int key;
for (int ii = 0; ii < L; ii++) {
auto mut_it = mutations[strain_index].find(ii);
alpha_i = (mut_it == mutations[strain_index].cend())?
alpha0s[ii] : -alpha0s[ii];
fit += alpha_i*his[ii];
if (interact) {
for (int jj = ii+1; jj < L; jj++) {
mut_it = mutations[strain_index].find(jj);
alpha_j = (mut_it == mutations[strain_index].cend())?
alpha0s[jj] : -alpha0s[jj];
key = jj + L*ii;
fit += 2*Jijs[key]*alpha_i*alpha_j;
}
}
}
return Foff + fit;
}
/* Compute the fitness using the local field approach. */
double lenski_sim::compute_fitness_lf(int parent_index,
int mutation_index) {
// find the value of alpha_kp
auto parent_muts = mutations[parent_index];
auto mut_it = parent_muts.find(mutation_index);
double alpha_kp = (mut_it == parent_muts.cend())?
alpha0s[mutation_index] : -alpha0s[mutation_index];
// compute the instantaneous contribution to the fitness
double fit = fits[parent_index];
fit -= 2*alpha_kp*his[mutation_index];
// compute the Jalpha contribution to the fitness
int key, row, col;
double alpha_j(0), Jalpha(0);
for (int jj = 0; jj < L; jj++) {
// get alpha_jp
mut_it = parent_muts.find(jj);
alpha_j = (mut_it == parent_muts.cend())?
alpha0s[jj] : -alpha0s[jj];
// get Jkj
row = mutation_index <= jj? mutation_index : jj;
col = mutation_index <= jj? jj : mutation_index;
key = col + row*L;
// compute the dot product
Jalpha += Jijs[key]*alpha_j;
}
Jalpha *= -4*alpha_kp;
return fit + Jalpha;
}
/* Computes the fitness using the full definition, for
* testing other fitness computation methods.
* Used for real-valued spins. */
double lenski_sim::compute_fitness_slow_hoc(int strain_index) {
double fit(0);
double alpha_i, alpha_j;
int key;
for (int ii = 0; ii < L; ii++) {
auto mut_it = mutations_hoc[strain_index].find(ii);
alpha_i = alpha0s[ii]
+ ((mut_it == mutations_hoc[strain_index].cend())?
0 : mut_it->second);
fit += alpha_i*his[ii];
if (interact) {
for (int jj = ii+1; jj < L; jj++) {
mut_it = mutations_hoc[strain_index].find(jj);
alpha_j = alpha0s[jj]
+ ((mut_it == mutations_hoc[strain_index].cend())?
0 : mut_it->second);
key = jj + L*ii;
fit += 2*Jijs[key]*alpha_i*alpha_j;
}
}
}
return Foff + fit;
}
/* Computes the fitness value for a new bacterial strain, given the parent.
* and the identification index for the mutation. Does so for +-1-valued spins.
* Does not require the initial strain to be all ones. */
double lenski_sim::compute_fitness(
int parent_index,
int mutation_index,
unordered_set<int> &parent_muts,
double alphak_p) {
double J_cross_muts(0);
int first_mut, second_mut, key;
if (interact) {
for (const int &other_mut : parent_muts) {
first_mut = (other_mut < mutation_index)?
other_mut : mutation_index;
second_mut = (other_mut <= mutation_index)?
mutation_index : other_mut;
key = second_mut + L*first_mut;
J_cross_muts += Jijs[key]*alpha0s[other_mut];
}
}
else { J_cross_muts = 0; }
return fits[parent_index] - alphak_p*(2*his[mutation_index]
+ 4*Jalpha0[mutation_index] - 8*J_cross_muts);
}
/* Computes the fitness value for a new bacterial strain, given the parent.
* and the identification index for the mutation.
* Does so for real-valued spins.
* Does not require the initial strain to be all ones. */
double lenski_sim::compute_fitness_hoc(
int parent_index,
int mutation_index,
double Delta_ck,
unordered_map<int, double> &parent_muts) {
double J_cross_muts(0);
int first_mut, second_mut, key;
if (interact) {
for (const auto & [other_mut, Delta_pj]: parent_muts) {
first_mut = (other_mut < mutation_index)?
other_mut : mutation_index;
second_mut = (other_mut <= mutation_index)?
mutation_index: other_mut;
key = second_mut + L*first_mut;
J_cross_muts += Jijs[key]*Delta_pj;
}
}
else { J_cross_muts = 0; }
return fits[parent_index] + Delta_ck*(his[mutation_index]
+ 2*(Jalpha0[mutation_index] + J_cross_muts));
}
/* Compute rank of a given strain, and store all the beneficial mutations. */
int lenski_sim::compute_rank(
int strain_ind,
vector<int> &beneficial_muts,
double &avg_fit_inc,
bool store_incs) {
// Stores the rank of this strain.
int curr_rank(0);
// Computes the hypothetical fitness of a mutant
// strain, used to determine rank.
double curr_new_fit(0);
// declare both of these guys and switch on simulation type.
unordered_set<int> muts; unordered_map<int, double> muts_hoc;
if (hoc) { muts_hoc = mutations_hoc[strain_ind]; }
else { muts = mutations[strain_ind]; }
// declare variables for fitness computation.
double Delta_ck(0), Delta_pk(0), fit_inc(0), alphak_p(0);
avg_fit_inc = 0;
if (store_incs) { beneficial_incs.clear(); }
// Loop over all the genes and check the fitness
// if a mutation were to occur there.
for (int curr_gene = 0; curr_gene < L; curr_gene++) {
// swap the fitness computation depending on the kind of simulation.
if (hoc) {
auto mut_iterator = muts_hoc.find(curr_gene);
Delta_pk = ((mut_iterator == muts_hoc.cend())?
0 : mut_iterator->second);
Delta_ck = -2*(alpha0s[curr_gene] + Delta_pk);
curr_new_fit = compute_fitness_hoc(strain_ind, curr_gene,
Delta_ck, muts_hoc);
}
else {
auto mut_iterator = muts.find(curr_gene);
alphak_p = (mut_iterator == muts.cend())?
alpha0s[curr_gene] : -alpha0s[curr_gene];
curr_new_fit = compute_fitness(strain_ind, curr_gene,
muts, alphak_p);
}
// compute the fitness and store info if its a beneficial mutation.
fit_inc = curr_new_fit - fits[strain_ind];
if (fit_inc >= 0) {
curr_rank += 1;
avg_fit_inc += fit_inc;
beneficial_muts.push_back(curr_gene);
if (store_incs) { beneficial_incs.push_back(fit_inc); }
}
}
avg_fit_inc /= (curr_rank > 0)? curr_rank : 1.;
return curr_rank;
}
/* Update rank of the initial strain. */
void lenski_sim::update_rank() {
// declare variables needed for the computation
vector<int> beneficial_muts;
double avg_fit_inc(0);
int mut_ind(0);
// compute the initial rank and keep trying to reduce the rank.
// compute the distribution of fitness increments each time so that
// we will have it when we hit the desired rank.
int final_rank = compute_rank(0, beneficial_muts, avg_fit_inc, true);
int row(0), col(0);
while (final_rank > init_rank) {
// draw mutation index randomly and flip the spin
mut_ind = beneficial_muts[gsl_rng_uniform_int(gsl_gen, beneficial_muts.size())];
alpha0s[mut_ind] *= -1;
// apply corrections to Jalpha
for (int i = 0; i < L; i++) {
row = (i <= mut_ind)? i : mut_ind;
col = (i <= mut_ind)? mut_ind : i;
Jalpha0[i] += 2*Jijs[col + row*L]*alpha0s[mut_ind];
}
// recompute the rank to see where we are at.
beneficial_muts.clear();
final_rank = compute_rank(0, beneficial_muts, avg_fit_inc, true);
}
// save initial strain information.
ranks[0] = final_rank;
avg_incs[0] = avg_fit_inc;
// re-compute Jalpha0 and Foff for this init.
Foff = 0;
Foff = 1 - (hoc? compute_fitness_slow_hoc(0) : compute_fitness_slow(0));
}
/* Run the whole simulation for n_days days with timestep dt. */
void lenski_sim::simulate_experiment(int n_days, double dt) {
// Time the results.
time_t dilute_start(0), dilute_end(0);
time_t step_start(0), step_end(0);
time_t frame_start(0), frame_end(0);
// time values.
double dilute_time(0),
step_time(0),
total_time(0),
rank_time(0);
int n_frames = n_days/output_interval;
// simulate for a fixed number of generations/days.
for (curr_day = 0; curr_day < n_days; curr_day++) {
// keep stepping forward until we have reached the correct size.
time(&step_start);
while (nbac_tot < N_f) {
hoc? step_forward_hoc(dt) : step_forward(dt);
}
time(&step_end);
step_time += difftime(step_end, step_start)/60.;
// perform and time the dilution.
time(&dilute_start);
dilute_gsl();
time(&dilute_end);
dilute_time += difftime(dilute_end, dilute_start)/60.;
if (!hoc) { update_reference_strain(); }
// measurement occurs after dilution.
if (curr_day % output_interval == 0) {
output_frame_info(total_time, frame_start, frame_end, rank_time,
dilute_time, step_time, curr_day/output_interval,
n_frames);
}
}
// Final dump of simulation data.
output_bac_data_bin("bac_data");
output_mut_data_bin("mut_data");
output_bin_counts();
// Output total time information.
string time_str = output_folder + "/time_info.dat";
FILE *outf = fopen(time_str.c_str(), "w");
fprintf(outf, "Total simulation time: %f hours.", total_time);
fclose(outf);
}
/* Re-compute the reference strain for faster fitness computation. */
void lenski_sim::update_reference_strain() {
// check if we actually have enough mutations that it will be
// beneficial to re-define the reference strain
auto max_nbac_it = std::max_element(n_bac.cbegin(), n_bac.cend());
int dominant_index = std::distance(n_bac.cbegin(), max_nbac_it);
unordered_set<int> dominant_mutations = mutations[dominant_index];
int n_dominant_mutations = dominant_mutations.size();
if (n_dominant_mutations >= reset_index * reset_fac) {
printf("Updating reference strain.\n");
time_t update_start(0), update_end(0);
time(&update_start);
printf("n_dominant_mutations: %d, reset_index: %d, reset_fac: %d\n",
n_dominant_mutations, reset_index, reset_fac);
// update Jalpha0
int key, row, col;
for (int ii = 0; ii < L; ii++) {
for (int jj : dominant_mutations) {
row = (ii < jj)? ii : jj;
col = (ii <= jj)? jj : ii;
key = col + row*L;
Jalpha0[ii] -= 2*Jijs[key]*alpha0s[jj];
}
}
// update alpha0
for (int ii : dominant_mutations) { alpha0s[ii] *= -1; }
// update each mutation set
vector<unordered_set<int>> new_mutations;
int strain_count = 0;
for (auto mutation_set : mutations) {
if (strain_count != dominant_index) {
unordered_set<int> new_mutation_set;
set_symmetric_difference(dominant_mutations.cbegin(),
dominant_mutations.cend(),
mutation_set.cbegin(),
mutation_set.cend(),
std::inserter(new_mutation_set,
new_mutation_set.begin()));
new_mutations.push_back(new_mutation_set);
}
else { new_mutations.emplace_back(); }
strain_count++;
}
mutations.swap(new_mutations);
// change the next amount of mutations we need before resetting
reset_index++;
time(&update_end);
printf("Finished updating reference strain. Time: %g\n",
difftime(update_end, update_start));
}
}
void lenski_sim::output_frame_info(
double &total_time,
time_t &frame_start,
time_t &frame_end,
double &rank_time,
double dilute_time,
double step_time,
int curr_frame,
int n_frames) {
// last frame ends now.
if (curr_frame > 0) { time(&frame_end); }
// output bacteria and mutation information.
output_bac_data_bin("bac_data");
time_t rank_start(0), rank_end(0);
time(&rank_start); output_mut_data_bin("mut_data"); time(&rank_end);
// update time information.
double frame_time = curr_frame > 0?
difftime(frame_end, frame_start)/60. : 0;
total_time += frame_time/60.;
rank_time += difftime(rank_end, rank_start)/60.;
// print diagnostic information.
printf("Finished frame %d/%d. Total time: %0.3fh. \
Frame time: %0.6fm.\nDilute time: %0.6fm. \
Step time: %0.6fm. Rank compute time: %0.6fm.\n",
curr_frame, n_frames, total_time, frame_time, dilute_time,
step_time, rank_time);
// output selection coefficient bin counters.
output_bin_counts();
// next frame starts now.
time(&frame_start);
}
// Taken from https://stackoverflow.com/questions/1577475/c-
// sorting-and-keeping-track-of-indexes
template <typename T>
vector<size_t> sort_indices(const vector<T> &v) {
vector<size_t> idx(v.size());
iota(idx.begin(), idx.end(), 0);
stable_sort(idx.begin(), idx.end(),
[&v](size_t i1, size_t i2) { return v[i1] > v[i2]; });
return idx;
}
/* Perform the dilution step using the gsl
* random number generation library. */
void lenski_sim::dilute_gsl() {
vector<double> new_nbac;
vector<unordered_map<int, double>> new_mutations_hoc;
vector<unordered_set<int>> new_mutations;
vector<vector<int>> new_mut_order;
vector<vector<double>> new_fit_effects;
vector<double> new_fits;
unordered_map<int, int> new_ranks;
unordered_map<int, double> new_avg_incs;
unordered_map<vector<int>, int, vector_hash> new_curr_strains;
int n_choices(0), new_n_strains(0);
double nbac_other(nbac_tot), nbac_curr(0);
int nsamps(N_0);
int strain(0);
int strain_ind(0);
// sort in descending order to minimize number of samples
vector<size_t> sorted_indices = sort_indices(n_bac);
while (nsamps > 0) {
strain_ind = sorted_indices[strain];
nbac_curr = n_bac[strain_ind];
nbac_other -= n_bac[strain_ind];
if (strain == n_strains-1) {
n_choices = std::min((int) round(nbac_curr), nsamps);
nsamps = 0;
}
else {
// sample from hypergeometric. slower, but exact.
//n_choices = gsl_ran_hypergeometric(gsl_gen,
// (int) round(nbac_curr),
// (int) round(nbac_other),
// nsamps);
// sample from binomial as an approximation.
n_choices = gsl_ran_binomial_tpe(
gsl_gen,
nbac_curr/(nbac_curr + nbac_other),
nsamps);
n_choices = n_choices < nbac_curr? n_choices : nbac_curr;
}
if (n_choices > 0) {
nsamps -= n_choices;
new_nbac.push_back(n_choices);
auto rank_it = ranks.find(strain_ind);
if (rank_it != ranks.cend()) {
new_ranks[new_n_strains] = ranks[strain_ind];
new_avg_incs[new_n_strains] = avg_incs[strain_ind];
}
vector<int> mut_seq = mut_order[strain_ind];
if (mut_seq.size() > 0) {
new_curr_strains[mut_seq] = new_n_strains;
}
if (hoc) { new_mutations_hoc.push_back(mutations_hoc[strain_ind]); }
else { new_mutations.push_back(mutations[strain_ind]); }
new_mut_order.push_back(mut_order[strain_ind]);
new_fit_effects.push_back(fit_effects[strain_ind]);
new_fits.push_back(fits[strain_ind]);
new_n_strains++;
}
strain++;
}
// Now that we've done the loop, update the class data structures.
nbac_tot = N_0;
n_strains = new_n_strains;
ranks.swap(new_ranks);
avg_incs.swap(new_avg_incs);
mutations.swap(new_mutations);
mutations_hoc.swap(new_mutations_hoc);
mut_order.swap(new_mut_order);
fit_effects.swap(new_fit_effects);
n_bac.swap(new_nbac);
fits.swap(new_fits);
current_strains.swap(new_curr_strains);
}
/* Outputs the number of bacteria and fitness values in binary. */
void lenski_sim::output_bac_data_bin(string file_name) {
// dump the bacteria and fitness info
char *bufc = new char[256];
string output_str = output_folder + "/" + file_name + ".%d.bin";
sprintf(bufc, output_str.c_str(), curr_day);
FILE *outf = fopen(bufc, "wb");
if (outf == NULL) {
fprintf(stderr, "Error opening file %s, errno %d, errstr (%s).\n",
bufc, errno, strerror(errno));
}
delete [] bufc;
float *buf = new float[2*n_strains];
float *bp = buf;
for (int ii = 0; ii < n_strains; ii++) {
*(bp++) = n_bac[ii]; *(bp++) = fits[ii];
}
fwrite(buf, sizeof(float), 2*n_strains, outf);
delete [] buf;
fclose(outf);
// dump the total number of mutations up to this point
output_str = output_folder + "/nmuts.bin";
outf = fopen(output_str.c_str(), "ab");
if (outf == NULL) {
fprintf(stderr, "Error opening nmuts file, errno %d, errstr (%s).\n",
errno, strerror(errno));
}
fwrite(&n_mutants_so_far, sizeof(int), 1, outf);
fclose(outf);
}
/* Outputs mutation order, fitness increments, rank, and mean
* fitness effect of remaining beneficial mutations in binary. */
void lenski_sim::output_mut_data_bin(string file_name) {
// construct the mutation data output file.
char *bufc = new char[256];
string output_str = output_folder + "/" + file_name + ".%d.bin";
sprintf(bufc, output_str.c_str(), curr_day);
FILE *outf = fopen(bufc, "wb");
if (outf == NULL) {
fprintf(stderr, "Error opening file %s, errno %d, errstr (%s).\n",
bufc, errno, strerror(errno));
}
delete [] bufc;
// declare some containers for the mutation data calculations.
vector<int> curr_muts;
vector<int> tmp;
vector<double> curr_fit_effs;
vector<float> dat;
int curr_rank(0);
double avg_fit_inc(0);
// find the maximum bacteria count to get the distribution of
// beneficial fitness effects for the dominant strain.
int max_nbac = *std::max_element(n_bac.cbegin(), n_bac.cend());
// compute mutation data for each strain
for (int ii = 0; ii < n_strains; ii++) {
// add a separator between strains
dat.push_back(10*L + ii + 1);
// check if we should compute the distribution
bool on_dominant_strain = n_bac[ii] == max_nbac;
// add mutation locations and fitness effect data
curr_muts = mut_order[ii];
curr_fit_effs = fit_effects[ii];
for (long unsigned int jj = 0; jj < curr_muts.size(); jj++) {
dat.push_back(curr_muts[jj]);
dat.push_back(curr_fit_effs[jj]);
}
// if it's time, compute the rank
if (curr_day % rank_interval == 0) {