-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp.gilps
executable file
·1490 lines (1342 loc) · 49.3 KB
/
main.cpp.gilps
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
/*
* main.cpp
* Population_Dynamics
*
* Created by Greg Hart on May 2015
* Copyright 2015 ALF. All rights reserved.
*
*/
/*
* IN
* resIdx.dat - ordered list of residue types - as integer codes - present at each site from most to least probable
* h.dat - h parameters
* J.dat - J parameters
* init_seq.dat - (optional) a starting sequence, if file is not found then the WT is used.
*
* OUT
* P1_model_traj.dat - running trajectory of P1 values of the population
* P2_model_traj.dat - running trajectory of P2 values of the population
* P1_model.dat - terminal P1 values computed by the population path
* P2_model.dat - terminal P2 values computed by the population path
* MC_seqs.dat - sequences sampled from population trajectory
* pop_stats.dat - data on the population at different time points
* Tcell_traj.dat - Number of Tcells and targets at different time points
*/
#include "main.h"
#include "functions.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#include <vector>
#include <limits>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
//#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <trng/yarn2.hpp>
#include <trng/uniform01_dist.hpp>
#include <trng/poisson_dist.hpp>
#include <boost/numeric/odeint.hpp>
#define PARTPARALLEL 3
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
using std::vector;
using std::sort;
using namespace boost::numeric::odeint;
typedef std::vector<double> state_type;
// main function preforming Fisher-wright dynamics on the viral side and intergrating ODEs for the Tcell side
int main (int argc, char *argv[]) {
cout.setf(std::ios_base::scientific);
cout.precision(3);
#ifdef UNIT_TESTING
#endif // #ifdef UNIT_TESTING
// start timer
double wall_start = get_wall_time();
double cpu_start = get_cpu_time();
// inputs with default values
long n_inputs=15;
long seed = -240164;
long m=3;
long N=10000;
double rate=0.0001;
long progeny = 10;
long n_cycles = 20000;
long burnin = 2000;
long sample_mod = 10000;
double T = 1;
long print_mod = 1;
long write_mod = 5;
long n_epitope = 1;
double n_T = 1000;
int rep_lim = 9;
double T_penalty = 1;
double a = 1e-7;
double ap = 1e-6;
double b = 1e-4;
double d = 0.2;//0.5;
double dp = 3;
double re = 6;//4;
double e = 3*1e-4;
double g = 0.03;
double hr = 0.03;
double w = .1;//7.5;
std::ifstream fin_inputs;
fin_inputs.open("./inputs.dat");
if (!fin_inputs) {
cerr << "Cannot open input file inputs.dat in the current directory; aborting." << endl;
exit(-1);
}
long input_cntr=0;
while (!fin_inputs.eof()) {
std::string input_name, tmp_str;
fin_inputs >> input_name;
if (strcmp(input_name.c_str(),"seed")==0) {
fin_inputs >> seed;
input_cntr++;
} else if (strcmp(input_name.c_str(),"m")==0) {
fin_inputs >> m;
input_cntr++;
} else if (strcmp(input_name.c_str(),"N")==0) {
fin_inputs >> N;
input_cntr++;
} else if (strcmp(input_name.c_str(),"rate")==0) {
fin_inputs >> rate;
input_cntr++;
} else if (strcmp(input_name.c_str(),"progeny")==0) {
fin_inputs >> progeny;
input_cntr++;
} else if (strcmp(input_name.c_str(),"n_cycles")==0) {
fin_inputs >> n_cycles;
input_cntr++;
} else if (strcmp(input_name.c_str(),"burnin")==0) {
fin_inputs >> burnin;
input_cntr++;
} else if (strcmp(input_name.c_str(),"sample_mod")==0) {
fin_inputs >> sample_mod;
input_cntr++;
} else if (strcmp(input_name.c_str(),"T")==0) {
fin_inputs >> T;
input_cntr++;
} else if (strcmp(input_name.c_str(),"print_mod")==0) {
fin_inputs >> print_mod;
input_cntr++;
} else if (strcmp(input_name.c_str(),"write_mod")==0) {
fin_inputs >> write_mod;
input_cntr++;
} else if (strcmp(input_name.c_str(),"n_epitope")==0) {
fin_inputs >> n_epitope;
input_cntr++;
} else if (strcmp(input_name.c_str(),"n_T")==0) {
fin_inputs >> n_T;
input_cntr++;
} else if (strcmp(input_name.c_str(),"rep_lim")==0) {
fin_inputs >> rep_lim;
input_cntr++;
} else if (strcmp(input_name.c_str(),"T_penalty")==0) {
fin_inputs >> T_penalty;
input_cntr++;
}
getline(fin_inputs,tmp_str);
}
if (input_cntr!=n_inputs) {
cerr << "ERROR - did not read expected number of inputs from inputs.dat; aborting." << endl;
exit(-1);
}
fin_inputs.close();
// loading parameters
//- loading ordered residue indices at each site (resIdx.dat), computing total number of h and J parameters,
// and candidateSites list of sites containing more than one residue type as only sites at which we attempt mutations
std::vector<long> nRes(m,-1);
std::vector< std::vector<long> > resIdx(m);
load_resIdx("./resIdx.dat",nRes,resIdx,m);
long n_h=0;
long n_J=0;
for(long i=0; i<m; i++) {
n_h += nRes[i];
for(long j=i+1; j<m; j++) {
n_J += nRes[i]*nRes[j];
}
}
// 6 hours to replicate, 7 day half life, 40 replication complexes per cell.
// long progeny = 4*7*40*(n_h-m)/(19*m);
cout << "progeny = " << progeny << endl;
std::vector<long> epi_start(n_epitope,-1);
std::vector<long> epi_end(n_epitope,-1);
std::vector< std::vector<double> > chi(n_epitope);
//setup T cell populations
std::vector<state_type> Tcells(n_epitope, state_type(rep_lim+2));
double chiI[n_epitope];
std::vector< std::vector<int> > place_value(n_epitope);
std::vector< std::vector<int> > n_WTepitopes(n_epitope);
if(n_epitope > 0){
load_epitopes("./epitopes.dat", epi_start, epi_end, chi, n_epitope, resIdx, nRes, Tcells, rep_lim);
}
for (long i=0; i<n_epitope; i++){
(n_WTepitopes[i]).resize((chi[i]).size(), 0);
// create a way to index all mutations in an epitope
(place_value[i]).resize(epi_end[i]-epi_start[i], 0);
int size = 1;
int count = 0;
for(int j=epi_start[i]; j<epi_end[i]; j++){
place_value[i][count] = size;
size *= nRes[j];
count++;
}
}
cout << "\n";
cout << "$$ # parameters: $$" << endl;
cout << " # h parameters = " << n_h << endl;
cout << " # J parameters = " << n_J << endl;
cout << " # epitopes = " << n_epitope << endl;
cout << endl;
std::vector <long> candidateSites(0);
for(long i=0; i<m; i++) {
if (nRes[i]>1) {
candidateSites.push_back(i);
}
}
long n_candidateSites = candidateSites.size();
//- loading h parameters
std::vector< std::vector<double> > h(m);
for(long i=0; i<m; i++) {
(h[i]).resize(nRes[i],(double)0);
}
load_X1("./h.dat",nRes,h,m);
//- loading J parameters
// \-> loading only upper triangle
// \-> loading residuewise elements in column major order (i.e., over i residues first)
std::vector< std::vector< std::vector< std::vector<double> > > > J(m);
for(long i=0; i<m; i++) {
(J[i]).resize(m);
for(long j=i+1; j<m; j++) {
(J[i][j]).resize(nRes[i]);
for(long p=0; p<nRes[i]; p++) {
(J[i][j][p]).resize(nRes[j],(double)0);
}
}
}
load_X2("./J.dat",nRes,J,m);
// initializing trajectory files
FILE* fout_P1_traj;
{
std::string fstr_P1_traj="./P1_model_traj.dat";
fout_P1_traj = fopen(fstr_P1_traj.c_str(),"wb");
if (fout_P1_traj==NULL) {
cerr << "Cannot open output file " << fstr_P1_traj << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [2];
sizes[0] = sizeof(long);
sizes[1] = sizeof(double);
fwrite(sizes,4,2,fout_P1_traj);
}
FILE* fout_P2_traj;
{
std::string fstr_P2_traj="./P2_model_traj.dat";
fout_P2_traj = fopen(fstr_P2_traj.c_str(),"wb");
if (fout_P2_traj==NULL) {
cerr << "Cannot open output file " << fstr_P2_traj << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [2];
sizes[0] = sizeof(long);
sizes[1] = sizeof(double);
fwrite(sizes,4,2,fout_P2_traj);
}
FILE* fout_MC_seqs;
{
std::string fstr_MC_seqs="./MC_seqs.dat";
fout_MC_seqs = fopen(fstr_MC_seqs.c_str(),"wb");
if (fout_MC_seqs==NULL) {
cerr << "Cannot open output file " << fstr_MC_seqs << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [2];
sizes[0] = sizeof(long);
sizes[1] = sizeof(int8_t);
fwrite(sizes,4,2,fout_MC_seqs);
fwrite(&N,sizeof(long),1,fout_MC_seqs);
}
FILE* fout_pop_stats;
{
std::string fstr_pop_stats="./pop_stats.dat";
fout_pop_stats = fopen(fstr_pop_stats.c_str(),"wb");
if (fout_pop_stats==NULL) {
cerr << "Cannot open output file " << fstr_pop_stats << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [2];
sizes[0] = sizeof(long);
sizes[1] = sizeof(double);
fwrite(sizes,4,2,fout_pop_stats);
}
FILE* fout_fitness;
{
std::string fstr_fitness="./fitness.dat";
fout_fitness = fopen(fstr_fitness.c_str(),"wb");
if (fout_fitness==NULL) {
cerr << "Cannot open output file " << fstr_fitness << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [2];
sizes[0] = sizeof(long);
sizes[1] = sizeof(double);
fwrite(sizes,4,2,fout_fitness);
fwrite(&N,sizeof(long),1,fout_fitness);
}
FILE* fout_Tcell_traj;
{
std::string fstr_Tcell_traj="./Tcell_traj.dat";
fout_Tcell_traj = fopen(fstr_Tcell_traj.c_str(),"wb");
if (fout_Tcell_traj==NULL) {
cerr << "Cannot open output file " << fstr_Tcell_traj << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [3];
sizes[0] = sizeof(long);
sizes[1] = sizeof(double);
sizes[2] = n_epitope;
fwrite(sizes,4,3,fout_Tcell_traj);
}
// Out put files for epitope seqs
FILE* fout_epi_traj[n_epitope];
if(n_epitope > 0){
std::string fstr = "./epitopes.dat";
std::ifstream fin;
fin.open(fstr.c_str());
if (!fin) {
std::cerr << "Cannot open input file " << fstr << "; aborting." << std::endl;
exit(-1);
}
std::string epi_file;
for(long i=0; i<n_epitope; i++) {
if (fin.eof()) {
std::cerr << "Prematurely encountered eof in " << fstr << "; aborting." << std::endl;
exit(-1);
}
std::getline(fin, epi_file);
std::stringstream readStrStrm(epi_file);
readStrStrm >> epi_file;
size_t pos = 0;
pos = epi_file.find_last_of('/');
epi_file = epi_file.substr(pos+1);
std::string token;
pos = epi_file.find('_');
epi_file.erase(0, pos + 1);
pos = epi_file.find('_');
token = epi_file.substr(0, pos);
pos = token.find('-');
{
fout_epi_traj[i] = fopen(epi_file.c_str(),"wb");
if (fout_epi_traj==NULL) {
cerr << "Cannot open output file " << epi_file << " in the current directory; aborting." << endl;
exit(-1);
}
int32_t sizes [2];
sizes[0] = sizeof(long);
sizes[1] = sizeof(int8_t);
fwrite(sizes,4,2,fout_epi_traj[i]);
fwrite(&N,sizeof(long),1,fout_epi_traj[i]);
}
}
while(!fin.eof()) {
std::getline(fin,epi_file);
if(!epi_file.empty()){
std::cerr << "Elements remain in " << fstr << " after populating array; aborting." << std::endl;
exit(-1);
}
}
}
// initializing model probability arrays
std::vector< std::vector<double> > n1(h);
std::vector< std::vector< std::vector< std::vector<double> > > > n2(J);
for(long i=0; i<m; i++) {
for(long p=0; p<nRes[i]; p++) {
n1[i][p] = 0;
for(long j=i+1; j<m; j++) {
for(long q=0; q<nRes[j]; q++) {
n2[i][j][p][q] = 0;
}
}
}
}
printf("PARTPARALLEL = %d\n", PARTPARALLEL);
// Population dynamics over empirical fitness landscape
cout << "Commencing evolutionary dynamics on the Potts model..." << endl;
// initialize population arrays
std::vector< std::vector<int8_t> > population(N, std::vector<int8_t>(m));
std::vector< std::vector<int8_t> > temp_pop(progeny*N, std::vector<int8_t>(m));
double* boltzfac = new double[N];
double* temp_boltz = new double[N*progeny];
double* part_sum = new double[N*progeny];
bool* part_sum_used = new bool[N*progeny];
double Z = 1.0;
double Ztemp = 1.0;
double* boltzfac_eff = new double[N];
double Z_eff = 1.0;
double* E = new double[N];
double* E_eff = new double[N];
double E_ave = 0.0;
double E_eff_ave = 0.0;
int* pop_init = new int[m];
bool* occupied = new bool[N*progeny];
int* idx = new int[N*progeny];
// Initialize every sequence in the population to the sequence found in the file or the WT if no file.
load_seq("init_seq.dat", pop_init, nRes, resIdx, m);
for(long i=0; i<N; i++){
for(long j=0; j<m; j++){
population[i][j]=pop_init[j];
}
}
delete[] pop_init;
// initialize occupied arrays
for(long i = 0; i < N*progeny; i++){
occupied[i] = false;
}
double temp = 0;
for(long i=0; i<m; i++) {
for(long p=0; p<nRes[i]; p++) {
temp += h[i][p];
}
}
T_penalty = T_penalty*temp/n_h;
cout << "T penalty: " << T_penalty << endl;
// Calulate the boltzmann factor for each sequence and the partition function as if only the sequences in the population are possible.
E[0] = energy(population[0],m,h,J);
E_eff[0] = E[0];
E_ave = E[0];
E_eff_ave = E[0];
boltzfac[0] = exp(-E[0]/T);
boltzfac_eff[0] = boltzfac[0];
for(long i=1; i<N; i++){
E[i] = E[0];
E_eff[i] = E[0];
boltzfac[i]=boltzfac[0];
boltzfac_eff[i] = boltzfac[0];
}
Z = boltzfac[0];
Ztemp = Z;
Z_eff = boltzfac_eff[0];
// calculate initial refrencies of amino acids
for(long k=0; k<N; k++){
for(long i=0; i<m; i++) {
n1[i][population[k][i]] += 1.0;
for(long j=i+1; j<m; j++) {
n2[i][j][population[k][i]][population[k][j]] += 1.0;
}
}
}
// write initial state to file
long zero = 0;
fwrite(&zero, sizeof(long), 1, fout_pop_stats);
fwrite(&N, sizeof(long), 1, fout_pop_stats);
fwrite(&Ztemp, sizeof(double), 1, fout_pop_stats);
fwrite(&Z, sizeof(double), 1, fout_pop_stats);
fwrite(&Z_eff, sizeof(double), 1, fout_pop_stats);
fwrite(&E_ave, sizeof(double), 1, fout_pop_stats);
fwrite(&E_eff_ave, sizeof(double), 1, fout_pop_stats);
fwrite(&zero, sizeof(long), 1, fout_P1_traj);
for(long i=0; i<m; i++) {
for(long p=0; p<nRes[i]; p++) {
n1[i][p] = n1[i][p]/N;
fwrite(&n1[i][p], sizeof(double), 1, fout_P1_traj);
n1[i][p] = n1[i][p]*N;
}
}
fwrite(&zero, sizeof(long), 1, fout_P2_traj);
for(long i=0; i<m; i++) {
for(long j=i+1; j<m; j++) {
for(long q=0; q<nRes[j]; q++) {
for(long p=0; p<nRes[i]; p++) {
n2[i][j][p][q] = n2[i][j][p][q]/N;
fwrite(&n2[i][j][p][q], sizeof(double), 1, fout_P2_traj);
n2[i][j][p][q] = n2[i][j][p][q]*N;
}
}
}
}
// reset amino acid frequencies
for(long i=0; i<m; i++) {
for(long p=0; p<nRes[i]; p++) {
n1[i][p] = 0.0;
for(long j=i+1; j<m; j++) {
for(long q=0; q<nRes[j]; q++) {
n2[i][j][p][q] = 0.0;
}
}
}
}
fwrite(&zero, sizeof(long), 1, fout_Tcell_traj);
for(long i=0; i<n_epitope; i++){
double Etotal = 0.0;
fwrite(&Tcells[i][0], sizeof(double), 1, fout_Tcell_traj);
for(long j=1; j<=rep_lim; j++){
Etotal += Tcells[i][j];
}
fwrite(&Etotal, sizeof(double), 1, fout_Tcell_traj);
fwrite(&Tcells[i][rep_lim+1], sizeof(double), 1, fout_Tcell_traj);
int index = 0;
int count = 0;
for(long position=epi_start[i]; position<epi_end[i]; position++){
index += place_value[i][count]*population[0][position];
count++;
}
chi[i][index] = chi[i][index]*N;
fwrite(&chi[i][index], sizeof(double), 1, fout_Tcell_traj);
chi[i][index] = chi[i][index]/N;
}
fwrite(&zero, sizeof(long), 1, fout_MC_seqs);
for(long k=0; k<N; k++){
for(long i=0; i<m; i++) {
fwrite(&resIdx[i][population[k][i]], sizeof(int8_t), 1, fout_MC_seqs);
}
}
for(long j=0; j<n_epitope; j++){
fwrite(&zero, sizeof(long), 1, fout_epi_traj[j]);
for(long k=0; k<N; k++){
for(long i=epi_start[j]; i<epi_end[j]; i++) {
fwrite(&resIdx[i][population[k][i]], sizeof(int8_t), 1, fout_epi_traj[j]);
}
}
}
fwrite(&zero, sizeof(long), 1, fout_fitness);
fwrite(E, sizeof(double), N, fout_fitness);
fwrite(E_eff, sizeof(double), N, fout_fitness);
fwrite(boltzfac, sizeof(double), N, fout_fitness);
fwrite(boltzfac_eff, sizeof(double), N, fout_fitness);
// N.B. For execution acceleration, this subroutine operates under fake residue numbering scheme (fakeres) whereby
// most probable residue at site i is coded as 0, next most probable as 1, ..., least probable as nRes[i]-1
// to obviate frequent (slow) lookup of residue types in resIdx
//
// Under this scheme, the fakeres code is identical to its position in resIdx, facilitating rapid lookup of
// corresponding n1,n2,h,J matrix elements
//
long pos = 0;
long n_samples = 0;
double Etemp[rep_lim];
// \-> safeUnity guards against blue moon segmentation faults for ran2 returning precisely unity due to interaction with floor call (ran2 precisely zero is not problematic)
static double safeUnity = 1.0 - std::numeric_limits<double>::epsilon();
double Energy = 0.0;
double penalty_S;
int thread_num;
#pragma omp parallel shared(thread_num)
{
if(omp_get_thread_num()==0){
thread_num = omp_get_num_threads();
}
}
int seq_S;
#if PARTPARALLEL == 2 || PARTPARALLEL == 1 // unused in 1,0
int *seq_arr = new int[thread_num];
#elif PARTPARALLEL == 3 || PARTPARALLEL == 0
int *seq_arr = new int[N];
#endif
vector<vector <int>> energy_idx; // This matrix of index is for parallelizing
// the energy calculation in PART 2
init_energy_index(m, thread_num, energy_idx);
double *key = new double[N*progeny];
double *key_l = new double[N*progeny];
// If omp is in use parallelize all operations on the population for speed.
#pragma omp parallel default(shared) shared(stdout, part_sum_used, seq_arr, energy_idx, Energy, seq_S, penalty_S, nRes, resIdx, h, J, T, population, temp_pop, temp_boltz, m, N, boltzfac, boltzfac_eff, Z, Z_eff, Ztemp, fout_P1_traj, fout_P2_traj, fout_MC_seqs, fout_pop_stats, fout_Tcell_traj, fout_fitness, fout_epi_traj, write_mod, print_mod, sample_mod, n_samples, cout, cerr, n_cycles, n1, n2, burnin, progeny, rate, seed, safeUnity, pos, Tcells, Etemp, n_T, chi, chiI, T_penalty, n_WTepitopes, n_epitope, epi_start, epi_end, rep_lim, occupied, idx, part_sum, place_value, E, E_ave, E_eff, E_eff_ave)
{
// Parallel safe PRNG
trng::yarn2 r((long)fabs(seed)); // PRNG
trng::uniform01_dist<> u; // uniform distribution for probabilities
trng::poisson_dist IntGenerator(3*m*rate); // poisson distribution for number of mutants in a sequence
#ifdef _OPENMP
const int size=omp_get_num_threads(); // get total number of processes
const int rank=omp_get_thread_num(); // get rank of current process
r.split(size, rank); // split PRN sequences by leapfrog method - choose sub-stream no. rank out of size streams
#else
const int size = 1;
const int rank = 0;
#endif
if(rank == 0) {
printf("OPENMP: %d threads\n", size);
fflush(stdout);
}
// break up the population into a chunk for each processor.
const long len = N/size;
const long begin = rank*len;
const long end = rank + 1 == size ? N : begin+len;
// break up DNA in later computation
const long len_m = m/size;
const long begin_m = rank*len_m;
const long end_m = rank + 1 == size ? m : begin_m+len_m;
// start main loop
for (long cycle=1; cycle<=n_cycles; cycle++) {
// reset values used in every iteration of the loop
#pragma omp single
{
pos = 0;
Ztemp = 0.0;
E_ave = 0.0;
E_eff_ave = 0.0;
for(long i=0; i<n_epitope; i++){
for(long j=0; j<(n_WTepitopes[i]).size(); j++){
n_WTepitopes[i][j] = 0;
}
}
}
#pragma omp barrier
int ranInt1 = 0; // IntGenerator(r)=number of mution for the parent sequence;
double ranNum1 = 0; //=u(r)*safeUnity; // range [0,1)
long parent = 0;
long site = 0;
long res = 0;
double Z_local = 0;
double Ztemp_local = 0;
double Z_local_eff = 0;
// Have every sequence in the population produce offspring equal to the value of progeny. Mutating each offspring sequence as it is copied
for(long k=0; k<progeny; k++){ // loop over the number of progeny
for(long i=begin; i<end; i++){ // loop over the processor's part of the population
ranInt1 = IntGenerator(r); // number of mution for the parent sequence;
for(long j=0; j<m; j++){ // copy parent sequence
temp_pop[i+(N*k)][j] = population[i][j];
}
for(long j=0; j<ranInt1; j++){ // introduce mutations
ranNum1 = u(r)*safeUnity;
site = (long)floor((double)ranNum1 * (double)m);
ranNum1 = u(r)*safeUnity;
res = (long)floor((double)ranNum1 * (double)(nRes[site]-1));
if (temp_pop[i+(N*k)][site] <= res) {
res++;
}
temp_pop[i+(N*k)][site] = res;
}
idx[i+(N*k)] = i+(N*k);
double penalty = 0;
for(long j=0; j<n_epitope; j++){ // calculate T-cell susceptibility
int index = 0;
int count = 0;
for(long position=epi_start[j]; position<epi_end[j]; position++){
index += place_value[j][count]*temp_pop[i+(N*k)][position];
count++;
}
double num_Ecells = 0;
for(long t=1; t<=rep_lim; t++){
num_Ecells += Tcells[j][t];
}
penalty += T_penalty*chi[j][index]*num_Ecells;
}
// calculate boltzmann factor of daughter sequence and add it to the partition function
temp_boltz[i+(N*k)] = exp(-(energy(temp_pop[i+(N*k)],m,h,J))/T-penalty/T);
Ztemp_local += temp_boltz[i+(N*k)];
occupied[i+(N*k)] = true;
}
}
// combine partition function from each processor
#pragma omp atomic
Ztemp += Ztemp_local;
#pragma omp barrier
#if PARTPARALLEL == 0
#pragma omp single
{
sort(idx, idx+N*progeny, [&temp_boltz](size_t i1, size_t i2){return temp_boltz[i1] < temp_boltz[i2];});
part_sum[0] = temp_boltz[idx[0]];
for(long i=1; i<N*progeny; i++){
part_sum[i] = part_sum[i-1] + temp_boltz[idx[i]];
}
// pick sequences that survive to the final population based on their fitness
Z = 0.0;
Z_eff = 0.0;
E_ave = 0.0;
E_eff_ave = 0.0;
while(pos < N){
ranNum1 = u(r)*safeUnity*part_sum[N*progeny-1];
long seq = std::lower_bound(part_sum, part_sum + N*progeny,ranNum1) - part_sum;
seq_arr[pos] = seq;
if(seq >= N*progeny){
cout << "Error in find, seq = " << seq << ", ranNum1 = " << ranNum1 << ", Ztemp = " << Ztemp << endl;
}
for(long j=0; j<m; j++){
population[pos][j]=temp_pop[idx[seq]][j];
}
// prime T cells
double penalty = 0;
for(long j=0; j<n_epitope; j++){
int index = 0;
int count = 0;
for(long position=epi_start[j]; position<epi_end[j]; position++){
index += place_value[j][count]*population[pos][position];
count++;
}
double num_Ecells = 0;
for(long t=1; t<=rep_lim; t++){
num_Ecells += Tcells[j][t];
}
penalty += T_penalty*chi[j][index]*num_Ecells;
n_WTepitopes[j][index]+=1.0;
}
E[pos] = energy(population[pos],m,h,J);
boltzfac[pos] = exp(-(E[pos])/T);
E_eff[pos] = E[pos]+penalty;
boltzfac_eff[pos] = exp(-E_eff[pos]/T);
E_ave += E[pos];
E_eff_ave += E_eff[pos];
Z += boltzfac[pos];
Z_eff += boltzfac_eff[pos];
pos++;
occupied[idx[seq]] = false;
if(seq==0){
part_sum[seq] = 0;
seq++;
}
for(long i=seq; i<N*progeny; i++){
if(occupied[idx[i]]){
part_sum[i] = temp_boltz[idx[i]] + part_sum[i-1];
} else {
part_sum[i] = part_sum[i-1];
}
}
}
} // end #pragma omp single
#pragma omp barrier
#endif
#if PARTPARALLEL == 1
///////////////////////////////
// PART 2 Introducing Mutation
///////////////////////////////
#pragma omp single
{
// make sure smaller numbers don't get rounded off
sort(idx, idx+N*progeny, [&temp_boltz](size_t i1, size_t i2){return temp_boltz[i1] < temp_boltz[i2];});
part_sum[0] = temp_boltz[idx[0]];
for(long i=1; i<N*progeny; i++)
{
part_sum[i] = part_sum[i-1] + temp_boltz[idx[i]];
}
// pick sequences that survive to the final population based on their fitness
Z = 0.0;
Z_eff = 0.0;
E_ave = 0.0;
E_eff_ave = 0.0;
}
while(pos < N){
if(rank==0){ // only main thread start
double ranNum1 = u(r)*safeUnity*part_sum[N*progeny-1];
long seq = std::lower_bound(part_sum, part_sum + N*progeny,ranNum1) - part_sum;
seq_S = seq;
if(seq >= N*progeny){
cout << "Error in find, seq = " << seq << ", ranNum1 = " << ranNum1 << ", Ztemp = " << Ztemp << endl;
}
for(long j=0; j<m; j++){
population[pos][j]=temp_pop[idx[seq]][j];
}
// prime T cells
double penalty = 0;
for(long j=0; j<n_epitope; j++){
int index = 0;
int count = 0;
for(long position=epi_start[j]; position<epi_end[j]; position++){
index += place_value[j][count]*population[pos][position];
count++;
}
double num_Ecells = 0;
for(long t=1; t<=rep_lim; t++){
num_Ecells += Tcells[j][t];
}
penalty += T_penalty*chi[j][index]*num_Ecells;
n_WTepitopes[j][index]+=1.0;
}
penalty_S = penalty;
} // only mean thread end
#pragma omp barrier
double E_P = 0.0;
auto sequence = population[pos];
for(auto i=energy_idx[rank].begin(); i!=energy_idx[rank].end(); i++) {
E_P += h[*i][sequence[*i]];
for (long j=(*i)+1; j<m; j++){
E_P += J[*i][j][sequence[*i]][sequence[j]];
}
}
#pragma omp atomic
Energy += E_P;
#pragma omp barrier
if(rank==0) { // only main thread start
E[pos] = Energy;
boltzfac[pos] = exp(-(E[pos])/T);
E_eff[pos] = E[pos]+penalty_S;
boltzfac_eff[pos] = exp(-E_eff[pos]/T);
E_ave += E[pos];
E_eff_ave += E_eff[pos];
Z += boltzfac[pos];
Z_eff += boltzfac_eff[pos];
pos++;
occupied[idx[seq_S]] = false;
Energy = 0.0;
}// only main thread end
if(size == 1 || rank != 0){
#pragma omp for schedule(static)
for(long i=seq_S; i<N*progeny; i++){
part_sum[i] -= temp_boltz[idx[seq_S]];
}
}
#pragma omp barrier
}// end while
//////////////////////////////
// END Part 2
/////////////////////////////
#endif
#if PARTPARALLEL == 2
///////////////////////////////
// PART 2 Introducing Mutation
///////////////////////////////
#pragma omp single
{
// make sure smaller numbers don't get rounded off
sort(idx, idx+N*progeny, [&temp_boltz](size_t i1, size_t i2){return temp_boltz[i1] < temp_boltz[i2];});
part_sum[0] = temp_boltz[idx[0]];
for(long i=1; i<N*progeny; i++){
part_sum[i] = part_sum[i-1] + temp_boltz[idx[i]];
}
// pick sequences that survive to the final population based on their fitness
Z = 0.0;
Z_eff = 0.0;
E_ave = 0.0;
E_eff_ave = 0.0;
}
while(pos < N){
int pos_L = pos + rank;
double ranNum1 = u(r)*safeUnity*part_sum[N*progeny-1];
long seq = std::lower_bound(part_sum, part_sum + N*progeny,ranNum1) - part_sum;
int active_threads = N > pos + (size - 1) ? size : N - pos;
seq_arr[rank] = seq;
#pragma omp barrier
#pragma omp single
{
int dup_idx;
while( (dup_idx = check_duplicate(seq_arr, active_threads)) != 0){
ranNum1 = u(r)*safeUnity*part_sum[N*progeny-1];
seq_arr[dup_idx] = std::lower_bound(part_sum, part_sum + N*progeny,ranNum1) - part_sum;
}
}
seq = seq_arr[rank];
if(seq >= N*progeny){
cout << "Error in find, seq = " << seq << ", ranNum1 = " << ranNum1 << ", Ztemp = " << Ztemp << endl;
}
if(pos_L < N){
for(long j=0; j<m; j++){
population[pos_L][j]=temp_pop[idx[seq]][j];
}
// prime T cells
double penalty = 0;
for(long j=0; j<n_epitope; j++){
int index = 0;
int count = 0;
for(long position=epi_start[j]; position<epi_end[j]; position++){
index += place_value[j][count]*population[pos_L][position];
count++;
}
double num_Ecells = 0;
for(long t=1; t<=rep_lim; t++){
num_Ecells += Tcells[j][t];
}
penalty += T_penalty*chi[j][index]*num_Ecells;
#pragma omp atomic
n_WTepitopes[j][index]+=1.0;
}
E[pos_L] = energy(population[pos_L],m,h,J);
E_eff[pos_L] = E[pos_L] + penalty;
boltzfac[pos_L] = exp(-(E[pos_L])/T);
boltzfac_eff[pos_L] = exp(-E_eff[pos_L]/T);
#pragma omp critical
{
E_ave += E[pos_L];
E_eff_ave += E_eff[pos_L];
Z += boltzfac[pos_L];
Z_eff += boltzfac_eff[pos_L];
}
occupied[idx[seq]] = false;
}
for(int j = 0; j < active_threads; j++){
#pragma omp barrier
#pragma omp for schedule(static)
for(long i=seq_arr[j]; i<N*progeny; i++){
part_sum[i] -= temp_boltz[idx[seq_arr[j]]];
}
}
#pragma omp single
{
pos += size;
}
}
//////////////////////////////
// END Part 2
/////////////////////////////
#endif
#if PARTPARALLEL == 3
///////////////////////////////
// PART 2 Introducing Mutation
///////////////////////////////
#pragma omp single
{
// initialize
Z = 0.0;
Z_eff = 0.0;
E_ave = 0.0;
E_eff_ave = 0.0;
seq_S = 0;
}
// algorithm A, select numbers with largest keys
#pragma omp for schedule(static)