-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSim.cpp
executable file
·1882 lines (1471 loc) · 60 KB
/
Sim.cpp
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 "time.h"
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <stdio.h>
#include <chrono>
#include <algorithm>
#include "Sim.hpp"
#include "mersenne.h"
#include <omp.h>
#include <climits>
#define PI 3.14159265358979323846
#define xi1 0.099194
#define xi2 -0.16346
#define rs 1.791044776
#define EMPTY -1
#define xi1Wall -0.58202813
#define xi2Wall -1.38057246
using namespace NESI;
using namespace std;
/****************************** SIMULATION RUN CONTROL ********************************/
// system preparation and initialization
Sim::Sim() {
read_input(); // get input paramters
if (box.checkpoint) read_configuration();
else init_configuration(); // get starting configuration
wrap_atoms();
generate_matrices(); // set up interactions
initialize_grid(); // build cell lists
initialize_data(); // get ready to store data
if (box.giveNewVel) set_velocities(); // set velocities
if (!box.continuation) openFiles(); // prepare to write output
}
// perform simulation
void Sim::MDSim() {
// start with a force calculation
calcVirials = calcEnergy = true;
calc_forces(calcVirials,calcEnergy);
box.upperAccept = box.lowerAccept = 0;
// start the timer
auto start = std::chrono::high_resolution_clock::now();
//equilibration - slab data is not calculated here, only coordinates are output
for (box.step=0;box.step<box.numEqSteps;box.step++) {
// do a half-step of velocity update
update_vel_half(vs,fs,box.dt);
// do a full step of position update
update_pos(xs,vs,box.dt);
// rebuild the lists and calculate forces
build_bead_lists();
calcVirials = false;
if (box.swapEvery > 0) calcEnergy = ((box.step+1)%box.swapEvery == 0);
calc_forces(calcVirials,calcEnergy);
// final half-step velocity update
update_vel_half(vs,fs,box.dt);
// thermostat the portion near the lower wall
if (box.hasWallZ) scale_wall_velocities();
else scale_velocities();
// write coordinates
if ((box.step+1)%box.writeCoords == 0) {
printf("Turn: %d\n",box.step+1);
printXYZ();
}
// particle swaps to maintain chemical potential differences
if ((box.swapEvery > 0) && ((box.step+1)%box.swapEvery == 0)) swap_particles();
// zero out the liquid momentum if necessary
if (box.zeroLiqMomentum > 0 && (box.step+1)%box.zeroLiqMomentum == 0) zero_wall_momentum();
}
// production
for (box.step=box.numEqSteps;box.step<box.numSteps+box.numEqSteps;box.step++) {
// do a half-step of velocity update
update_vel_half(vs,fs,box.dt);
// do a full step of position update
update_pos(xs,vs,box.dt);
// rebuild the lists and calculate forces
calcVirials = ((box.step+1)%box.calcInterval == 0);
calcEnergy = (((box.step+1)%box.calcInterval == 0) || ((box.step+1)%box.swapEvery == 0));
build_bead_lists();
calc_forces(calcVirials,calcEnergy);
// final half-step velocity update
update_vel_half(vs,fs,box.dt);
// apply thermostat at walls
if (box.hasWallZ) scale_wall_velocities();
else scale_velocities();
// calculate slab data
if ((box.step+1)%box.calcInterval == 0) calc_slab_data_omp();
// write slab data
if ((box.step+1)%box.writeInterval == 0) {
write_slab_data();
}
// write coordinates
if ((box.step+1)%box.writeCoords == 0) {
printf("Turn: %d\n",box.step+1);
printXYZ();
}
// write checkpoint file and widom histograms
if ((box.step+1)%box.checkInterval == 0) {
print_configuration();
}
// particle swaps to maintain chemical potential differences
// this messes with the per-particle energies, so must be done AFTER the slab calculations
if ((box.swapEvery > 0) && ((box.step+1)%box.swapEvery == 0)) swap_particles();
// zero out the liquid momentum if necessary
if (box.zeroLiqMomentum > 0 && (box.step+1)%box.zeroLiqMomentum == 0) zero_wall_momentum();
}
cout << "Swaps accepted at upper bath: " << box.upperAccept << endl;
cout << "Swaps accepted at lower bath: " << box.lowerAccept << endl;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
double tsps = (box.numSteps + box.numEqSteps) / (duration.count());
printf("runtime %f\n%e timesteps per second\n",duration.count(), tsps);
//write_slab_data();
dumpData();
//printXYZ();
}
/******************************************************************************/
/********************** SYSTEM PREPARATION AND INPUT *********************************/
// prepare the files we're going to write to
void Sim::openFiles() {
FILE *dump;
dump = fopen("config.xyz","w");
fclose(dump);
dump = fopen("data.txt","w");
fclose(dump);
int i;
for (i=0;i<box.numTypes;i++) {
char filename[32];
sprintf(filename,"slab_dens_%d.txt",i);
dump=fopen(filename,"w");
fclose(dump);
}
for (i=0;i<box.numTypes;i++) {
char filename[32];
sprintf(filename,"slab_mtms_%d.txt",i);
dump=fopen(filename,"w");
fclose(dump);
}
dump=fopen("slab_kins.txt","w");
fclose(dump);
dump=fopen("slab_pots.txt","w");
fclose(dump);
dump=fopen("slab_virs.txt","w");
fclose(dump);
dump=fopen("slab_surf.txt","w");
fclose(dump);
dump=fopen("slab_heat_fluxes.txt","w");
fclose(dump);
for (i=0;i<box.numTypes;i++) {
char filename[32];
sprintf(filename,"slab_widom_hist_%d.txt",i);
dump=fopen(filename,"w");
fclose(dump);
}
}
void Sim::read_input() {
FILE *input;
char tt[2001];
int ret;
input=fopen("input", "r");
if (input!=NULL)
{ /****** Reading Input File ********/
ret=fscanf(input,"%d", &box.seed); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.checkpoint); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.continuation); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.giveNewVel); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.numSteps); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.numEqSteps); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.calcInterval); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.writeInterval); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.writeCoords); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.checkInterval); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.x); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.y); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.z); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.numBeads); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.numTypes); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.cellMult); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.tempSet); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.tempSetTop); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.thermoHeight); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.thermoHeightTop); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.dt); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.hasWallZ); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.slabWidth); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.numInsertionsPerStep); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &minEnergy); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &maxEnergy); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &binWidth); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.rescaleTime); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.rescaleTimeTop); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.pinningForce); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.pinHeight); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.wallEps); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.wallCut); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.zeroLiqMomentum); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.deltaMuTop); fgets(tt,2000,input);
ret=fscanf(input,"%lf", &box.deltaMuBottom); fgets(tt,2000,input);
ret=fscanf(input,"%d", &box.swapEvery); fgets(tt,2000,input);
fgets(tt,2000,input);fgets(tt,2000,input);
box.velVar = sqrtl(box.tempSet);
box.velVarTop = sqrtl(box.tempSetTop);
box.numSlabs = (int) floor(box.z/box.slabWidth);
box.slabWidth = box.z/box.numSlabs;
box.targetK = 1.5*box.numBeads*box.tempSet;
box.collisionProb = box.dt/box.rescaleTimeTop;
// set histogram parameters
quitEnergy = maxEnergy-minEnergy;
numBins = (int) ceil(quitEnergy/binWidth); // number of actual bins is one larger to handle all high-energy values
binWidth = quitEnergy/numBins;
fclose(input);
}
else
{
fprintf(stdout,"\n Input File Not Found\n");
exit(EXIT_FAILURE);
}
// get openMP parameters
#if defined(_OPENMP)
#pragma omp parallel
{
if (omp_get_thread_num() == 0) {
nThreads = omp_get_num_threads();
cout << "Number of threads: " << nThreads << endl;
}
}
#else
nThreads = 1;
#endif
}
// read configuration from initial state (provided as input)
void Sim::read_configuration() {
int i,start,end,anchor,rigid,issite,hassites;
char tt[2001];
double total_volume = 0.0;
// xyz-input file with velocities
FILE *atom_file = fopen("init.xyz","r"); //Location of all atom files
//fgets(tt,2000,atom_file); //Section title
fscanf(atom_file, "%d",&box.numBeads);
fscanf(atom_file, "%lf%lf%lf", &box.x, &box.y, &box.z); // comment line is xyz dimensions
xs = new NESI::vector[box.numBeads];
vs = new NESI::vector[box.numBeads];
fs = new NESI::vector[box.numBeads*nThreads];
types = new int[box.numBeads];
virials = new shape[box.numBeads*nThreads];
potentials = new double[box.numBeads*nThreads];
// read init config file
for (i=0;i<box.numBeads;i++) {
fscanf(atom_file,"%d%lf%lf%lf%lf%lf%lf", &types[i], &xs[i][0], &xs[i][1], &xs[i][2], &vs[i][0], &vs[i][1], &vs[i][2]);
}
fclose(atom_file);
wrap_atoms();
double volume = box.x*box.y*box.z;
box.dens = box.numBeads/volume;
}
// initialize configuration by placing atoms on a lattice
void Sim::init_configuration() {
int i,j,k,dim,idx,factor,dimZ;
double dx,dy,dz;
double spacing = 1.2;
char tt[2001];
// initialize the data structures
types = new int[box.numBeads];
xs = new NESI::vector[box.numBeads];
vs = new NESI::vector[box.numBeads];
fs = new NESI::vector[box.numBeads*nThreads];
virials = new shape[box.numBeads*nThreads];
potentials = new double[box.numBeads*nThreads];
// find lattice spacing needed
factor = (int) box.z/box.x;
dim = (int) ceil(cbrt(box.numBeads/factor)); // now many beads in the x and y directions
dx = box.x/dim;
dy = box.y/dim;
dz = box.z/(dim*factor);
// loop through atoms, placing them on the lattice
for (i=0;i<dim;i++) {
for (j=0;j<dim;j++) {
for (k=0;k<factor*dim;k++) {
// exit if we have enough atoms
idx = i*dim*dim*factor + j*dim*factor + k;
if (idx >= box.numBeads) continue;
// place the bead at the center of the lattice
types[idx] = 0;
xs[idx][0] = ((double)i+0.5)*dx;
xs[idx][1] = ((double)j+0.5)*dy;
xs[idx][2] = ((double)k+0.5)*dz;
}
}
}
wrap_atoms();
double volume = box.x*box.y*box.z;
box.dens = box.numBeads/volume;
}
// draw velocities at random from boltzmann dist.
void Sim::set_velocities() {
int i,j;
double var = sqrtl(box.tempSet);
double kinetic = 0.0;
double temp,scale;
NESI::vector p,pTot;
// generate random velocities and keep track of total momentum - assumes particles of identical mass
for (i=0;i<box.numBeads;i++) {
for (j=0;j<3;j++) {
vs[i][j] = calc_random_gaussian(0.0,var*sqrtInvMasses[types[i]]);
}
vec_scalar_mult(p,vs[i],masses[types[i]]);
vec_add(pTot,p);
}
vec_scalar_mult(pTot,1.0/((double) box.numBeads));
// subtract off the total momentum and keep track of kinetic energy
for (i=0;i<box.numBeads;i++){
vec_scalar_mult(p,pTot,invMasses[types[i]]);
vec_subtr(vs[i],p);
kinetic += 0.5*masses[types[i]]*vec_dot(vs[i],vs[i]);
}
// rescale velocities to get correct temp
scale = sqrtl(box.targetK/kinetic);
for (i=0;i<box.numBeads;i++){
vec_scalar_mult(vs[i],scale);
}
}
// read in the interaction data and create parameter matrices
void Sim::generate_matrices() {
int ret,i,j,type1,type2;
double epsVal,sigVal,rcutVal,massVal;
const char* chr;
// set up the data structures
eps = new double *[box.numTypes];
sigs = new double *[box.numTypes];
rcuts = new double *[box.numTypes];
masses = new double[box.numTypes];
invMasses = new double[box.numTypes];
sqrtInvMasses = new double[box.numTypes];
for (i=0;i<box.numTypes;i++) {
eps[i] = new double [box.numTypes];
sigs[i] = new double [box.numTypes];
rcuts[i] = new double [box.numTypes];
}
// set everything to zero initially
for (i=0;i<box.numTypes;i++) {
for (j=0;j<box.numTypes;j++) {
eps[i][j] = 0.0;
sigs[i][j] = 0.0;
rcuts[i][j] = 0.0;
}
masses[i] = invMasses[i] = sqrtInvMasses[i] = 1.0; // just in case, since we divide by this pretty often
}
// read in the mass data line-by-line
std::ifstream typeData("types.dat");
for (std::string line; getline(typeData,line);) {
// convert string to char*
chr = line.c_str();
// read in the LJ types the parameters apply to
ret=sscanf(chr,"%d%lf", &type1,&massVal);
masses[type1] = massVal;
invMasses[type1] = 1.0/massVal;
sqrtInvMasses[type1] = sqrtl(invMasses[type1]);
}
// read in the interaction data line-by-line
std::ifstream data("interactions.dat");
for (std::string line; getline(data,line);) {
// convert string to char*
chr = line.c_str();
// read in the LJ types the parameters apply to
ret=sscanf(chr,"%d%d%lf%lf%lf", &type1,&type2,&epsVal,&sigVal,&rcutVal);
eps[type1][type2] = eps[type2][type1] = epsVal;
sigs[type1][type2] = sigs[type2][type1] = sigVal;
rcuts[type1][type2] = rcuts[type2][type1] = rcutVal;
}
data.close();
// use appropriate combination rules for any missing elements
for (i=0;i<box.numTypes;i++) {
for(j=i+1;j<box.numTypes;j++) {
if (eps[i][j] == 0.0) eps[i][j] = eps[j][i] = sqrtl(eps[i][i]*eps[j][j]);
if (sigs[i][j] == 0.0 && sigs[i][i] != 0.0 && sigs[j][j] != 0.0) sigs[i][j] = sigs[j][i] = 0.5*(sigs[i][i]+sigs[j][j]);
if (rcuts[i][j] == 0.0 && rcuts[i][i] != 0.0 && rcuts[j][j] != 0.0) rcuts[i][j] = rcuts[j][i] = max(rcuts[i][i],rcuts[j][j]);
}
}
// find the minimum value of epsilon (used in exit criteria for widom insertion)
minEps = 9999999999.9;
for (i=0;i<box.numTypes;i++) {
for (j=0;j<box.numTypes;j++) {
if (eps[i][j] < minEps) minEps = eps[i][j];
}
}
}
// set up random num. generators and slab data structures
void Sim::initialize_data() {
if (box.seed < 0) {
box.seed = time(NULL);
}
RanGen = new CRandomMersenne(box.seed);
threadRanGen = (CRandomMersenne*) malloc(nThreads*sizeof(CRandomMersenne));
int i,j;
for (i=0;i<nThreads;i++) {
threadRanGen[i] = *new CRandomMersenne(box.seed+i+1); // make sure each RNG has a different seed
}
// initialize slab data
slab_counts = new int *[box.numTypes];
for (i=0;i<box.numTypes;i++) {
slab_counts[i] = new int [box.numSlabs*nThreads];
}
slab_mtms = new NESI::vector *[box.numTypes];
for (i=0;i<box.numTypes;i++) {
slab_mtms[i] = new NESI::vector [box.numSlabs*nThreads];
}
slab_kins = new shape[box.numSlabs*nThreads];
slab_pots = new double[box.numSlabs*nThreads];
slab_heat_fluxes = new NESI::vector[box.numSlabs*nThreads];
slab_virs = new shape[box.numSlabs*nThreads];
typeEnergies = new double[box.numTypes*nThreads];
slab_widom_hist = new long int **[box.numSlabs];
for (i=0;i<box.numTypes;i++) {
slab_widom_hist[i] = new long int *[box.numSlabs];
for (j=0;j<box.numSlabs;j++) {
slab_widom_hist[i][j] = new long int [numBins+1]; // extra bin to handle super-high energy results that essentially just contribute zeros in the boltzmann factor
} // note that each thread has its own chunk of slabs for insertions, so no write conflicts
}
// just to be safe, initialize all of these to zeros
for (i=0;i<box.numTypes;i++) {
memset(slab_counts[i], 0, box.numSlabs*nThreads*sizeof(*slab_counts[i]));
memset(slab_mtms[i], 0, box.numSlabs*nThreads*sizeof(*slab_mtms[i]));
for (j=0;j<box.numSlabs;j++) {
memset(slab_widom_hist[i][j], 0, (numBins+1)*sizeof(*slab_widom_hist[i][j]));
}
}
memset(slab_kins, 0, box.numSlabs*nThreads*sizeof(*slab_kins));
memset(slab_pots, 0, box.numSlabs*nThreads*sizeof(*slab_pots));
memset(slab_virs, 0, box.numSlabs*nThreads*sizeof(*slab_virs));
memset(slab_heat_fluxes, 0, box.numSlabs*nThreads*sizeof(*slab_heat_fluxes));
}
/*********************************************************************************/
/********************* CELL LIST METHODS ******************************************/
// maps a position (vector) to a given cell
int Sim::mapToGrid(NESI::vector r) {
double x,y,z,x1,y1,z1;
int a,b,c,m;
x = r[0];
y = r[1];
z = r[2];
a = floor(x/box.cell_width_x);
b = floor(y/box.cell_width_y);
c = floor(z/box.cell_width_z);
m = c*box.cell_num_x*box.cell_num_y + b*box.cell_num_x + a;
return m;
}
// maps a position (x,y,z) to a given cell
int Sim::mapToGrid(double x, double y, double z) {
int a,b,c,m;
a = floor(x/box.cell_width_x);
b = floor(y/box.cell_width_y);
c = floor(z/box.cell_width_z);
m = c*box.cell_num_x*box.cell_num_y + b*box.cell_num_x + a;
return m;
}
// converts cell coordinates into position in cell data list
int Sim::calc_cell_placement(int a, int b, int c) {
a = a%box.cell_num_x;
if (a<0) a += box.cell_num_x;
b = b%box.cell_num_y;
if (b<0) b += box.cell_num_y;
c = c%box.cell_num_z;
if (c<0) c += box.cell_num_z;
return c*box.cell_num_y*box.cell_num_x + b*box.cell_num_x + a;
}
// converts position in cell data list into cell coordinates
void Sim::calc_cell_index(NESI::lvector &index, int m) {
int a,b,c;
c = m/(box.cell_num_x*box.cell_num_y);
m -= c*box.cell_num_x*box.cell_num_y;
b = m/box.cell_num_x;
a = m - b*box.cell_num_x;
index[0] = a;
index[1] = b;
index[2] = c;
}
// create the cell list data structures
void Sim::initialize_grid() {
int i,j,k,m1,m2;
lvector idx1,idx2;
// first get longest cut off distance
box.rcut = 0.0;
for (i=0;i<box.numTypes;i++) {
for (j=i;j<box.numTypes;j++) {
if (rcuts[i][j] >= box.rcut) box.rcut = rcuts[i][j];
}
}
// figure out how many cells we have, how big they need to be, and how
// many neighbors are needed in force calculations
box.cell_num_x = int(floor(box.x * box.cellMult / box.rcut));
box.cell_num_y = int(floor(box.y * box.cellMult / box.rcut));
box.cell_num_z = int(floor(box.z * box.cellMult / box.rcut));
box.cell_width_x = box.x / double(box.cell_num_x);
box.cell_width_y = box.y / double(box.cell_num_y);
box.cell_width_z = box.z / double(box.cell_num_z);
box.numCell = box.cell_num_x*box.cell_num_y*box.cell_num_z;
box.cell_lim_x = int(ceil(box.rcut / box.cell_width_x));
box.cell_lim_y = int(ceil(box.rcut / box.cell_width_y));
box.cell_lim_z = int(ceil(box.rcut / box.cell_width_z));
// construct the list of cell neighbors
box.maxNeighbors = (2*box.cell_lim_x+1)*(2*box.cell_lim_y+1)*(2*box.cell_lim_z+1) - 1;
box.cell_neighbors = new int *[box.numCell];
box.cell_num_neighbors = new int[box.numCell];
box.do_force_calc = new bool *[box.numCell];
box.cellVec = new lvector[box.numCell];
for (m1=0;m1<box.numCell;m1++) {
// initialize list of neighbors
box.cell_neighbors[m1] = new int[box.maxNeighbors];
box.do_force_calc[m1] = new bool[box.maxNeighbors];
box.cell_num_neighbors[m1] = 0;
// get cell index
calc_cell_index(idx1,m1);
box.cellVec[m1][0] = idx1[0];
box.cellVec[m1][1] = idx1[1];
box.cellVec[m1][2] = idx1[2];
// loop through nearby cells to find neighbors
for (i=idx1[0]-box.cell_lim_x;i<=idx1[0]+box.cell_lim_x;i++) {
for (j=idx1[1]-box.cell_lim_y;j<=idx1[1]+box.cell_lim_y;j++) {
for (k=idx1[2]-box.cell_lim_z;k<=idx1[2]+box.cell_lim_z;k++) {
// if we have walls in the z-direction, ignore this cell and move on
if (box.hasWallZ && (k < 0 || k >= box.cell_num_z)) continue;
if (k == idx1[2] && j == idx1[1] && i == idx1[0]) continue; // don't include ourselves in the list
// get list placement of the neighboring cell
m2 = calc_cell_placement(i,j,k);
calc_cell_index(idx2,m2);
// add to list of cell neighbors
box.cell_neighbors[m1][box.cell_num_neighbors[m1]] = m2;
box.do_force_calc[m1][box.cell_num_neighbors[m1]] = box.doNeighborCalc(idx1,idx2);
box.cell_num_neighbors[m1]++;
}
}
}
}
// now construct the array of list heads and the linked list
box.head = new int[box.numCell];
box.bead_list = new int[box.numBeads];
// and finally, build the lsits
build_bead_lists();
}
void Sim::build_bead_lists() {
int i,m;
for (i=0;i<box.numCell;i++) {
box.head[i] = EMPTY;
}
for (i=0;i<box.numBeads;i++) {
box.bead_list[i] = EMPTY;
}
for (i=0;i<box.numBeads;i++) {
m = mapToGrid(xs[i]);
box.bead_list[i] = box.head[m];
box.head[m] = i;
}
}
/******************************************************************************************/
/*********************************INTEGRATOR FUNCTIONS*************************************/
void Sim::update_vel_half(NESI::vector *vs, NESI::vector *fs, double dt) {
int i,j;
double dtHalf = 0.5*dt;
for (i=0;i<box.numBeads;i++) {
for (j=0;j<3;j++) {
vs[i][j] += dtHalf*fs[i][j]*invMasses[types[i]];
}
}
}
void Sim::update_pos(NESI::vector *xs, NESI::vector *vs, double dt) {
int i;
double randVel;
// loop through atoms and update velocities
for (i=0;i<box.numBeads;i++) {
// update positions
xs[i][0] += box.dt*vs[i][0];
xs[i][1] += box.dt*vs[i][1];
xs[i][2] += box.dt*vs[i][2];
// handle PBCs
xs[i][0] = fmod(xs[i][0],box.x);
if (xs[i][0] < 0.0) xs[i][0] += box.x;
xs[i][1] = fmod(xs[i][1],box.y);
if (xs[i][1] < 0.0) xs[i][1] += box.y;
// handle walls if necessary
if (box.hasWallZ) {
// if a particle has left the box
if (xs[i][2] >= box.z) {
// specular reflection
xs[i][2] = 2.0*box.z - xs[i][2];
vs[i][2] *= -1.0;
// draw new velocity parallel to wall, i.e. diffuse reflection
vs[i][0] = calc_random_gaussian(0.0,box.velVarTop*sqrtInvMasses[types[i]]);
vs[i][1] = calc_random_gaussian(0.0,box.velVarTop*sqrtInvMasses[types[i]]);
}
if (xs[i][2] < 0.0) {
// specular reflection
xs[i][2] *= -1.0;
vs[i][2] *= -1.0;
// draw new velocity
vs[i][0] = calc_random_gaussian(0.0,box.velVar*sqrtInvMasses[types[i]]);
vs[i][1] = calc_random_gaussian(0.0,box.velVar*sqrtInvMasses[types[i]]);
}
}
else {
xs[i][2] = fmod(xs[i][2],box.z);
if (xs[i][2] < 0.0) xs[i][2] += box.z;
}
}
}
// apply canonical sampling velocity rescaling (CSVR) thermostat near the lower wall
// and Andersen thermostat near top wall
void Sim::scale_wall_velocities() {
int i,j,count;
double var,kinetic,dK,newK,targetK,scale,height;
// get kinetic energy and find out how we need to scale
//#pragma omp parallel for reduction(+:kinetic)
kinetic = 0;
count = 0;
for (i=0;i<box.numBeads;i++){
// if near lower wall, add to count/kinetic totals for CSVR thermostat
if (xs[i][2] <= box.thermoHeight) {
kinetic += masses[types[i]]*vec_dot(vs[i],vs[i]);
count++;
}
// Andersen thermostat at upper wall (nothing to do after this step for upper wall)
else if (xs[i][2] >= (box.z-box.thermoHeightTop)) {
if (RanGen->Random() <= box.collisionProb) {
var = box.velVarTop*sqrtInvMasses[types[i]];
vs[i][0] = calc_random_gaussian(0.0,var);
vs[i][1] = calc_random_gaussian(0.0,var);
vs[i][2] = calc_random_gaussian(0.0,var);
}
}
}
kinetic *= 0.5;
// get the target kinetic energy for the given number of particles
targetK = 1.5*count*box.tempSet;
// take a step in the stochastic process
dK = (targetK-kinetic)*(box.dt/box.rescaleTime) + 2.0*sqrtl(targetK*kinetic*box.dt/(3.0*count*box.rescaleTime))*calc_random_gaussian(0.0,1.0);
newK = kinetic + dK;
// find the scaling parameter
scale = sqrtl(newK/kinetic);
// scale the velocities
for (i=0;i<box.numBeads;i++) {
if (xs[i][2] <= box.thermoHeight) {
for (j=0;j<3;j++) {
vs[i][j] *= scale;
}
}
}
}
// apply canonical sampling velocity rescaling (CSVR) thermostat
// currently unused
void Sim::scale_velocities() {
int i,j;
double kinetic,dK,newK,scale;
// get kinetic energy and find out how we need to scale
//#pragma omp parallel for reduction(+:kinetic)
kinetic = 0;
for (i=0;i<box.numBeads;i++){
kinetic += masses[types[i]]*vec_dot(vs[i],vs[i]);
}
kinetic *= 0.5;
// take a step in the stochastic process
dK = (box.targetK-kinetic)*(box.dt/box.rescaleTime) + 2.0*sqrtl(box.targetK*kinetic*box.dt/(3.0*box.numBeads*box.rescaleTime))*calc_random_gaussian(0.0,1.0);
newK = kinetic + dK;
// find the scaling parameter
scale = sqrtl(newK/kinetic);
// scale the velocities
for (i=0;i<box.numBeads;i++) {
for (j=0;j<3;j++) {
vs[i][j] *= scale;
}
}
}
// zero out the momentum near the wall - plays nice with the CSVR thermostat being used
void Sim::zero_wall_momentum() {
int i,j,count;
double kin,newKin,scale;
NESI::vector pTot;
// get momentum, keeping track of the kinetic energy
count = 0;
kin = 0.0;
pTot[0] = pTot[1] = pTot[2] = 0.0;
for (i=0;i<box.numBeads;i++){
if (xs[i][2] < box.pinHeight) {
pTot[0] += masses[types[i]]*vs[i][0];
pTot[1] += masses[types[i]]*vs[i][1];
pTot[1] += masses[types[i]]*vs[i][2];
kin += masses[types[i]]*vec_dot(vs[i],vs[i]);
count++;
}
}
// calculate kinetic energy and average momentm
pTot[0] /= count;
pTot[1] /= count;
pTot[2] /= count;
newKin = 0.0;
// shift the velocities, keeping track of the new kinetic energy
for (i=0;i<box.numBeads;i++) {
if (xs[i][2] < box.pinHeight) {
vs[i][0] -= invMasses[types[i]]*pTot[0];
vs[i][1] -= invMasses[types[i]]*pTot[1];
vs[i][2] -= invMasses[types[i]]*pTot[2];
newKin += masses[types[i]]*vec_dot(vs[i],vs[i]);
}
}
// scale the velocities back to the same kinetic energy we had before
scale = sqrtl(kin/newKin);
for (i=0;i<box.numBeads;i++) {
if (xs[i][2] < box.pinHeight) {
vs[i][0] *= scale;
vs[i][1] *= scale;
vs[i][2] *= scale;
}
}
}
// function to swap particle identities near the walls in order to maintain chemical potential difference at top/bottom
// note that this assumes only two particle types
void Sim::swap_particles() {
// build vector of atom ids for upper and lower baths
std::vector<int> upperIds;
std::vector<int> lowerIds;
int i,j,k,newType,factor,m1,m2;
double newPotential,deltaU,boltz;
// get the particles that are in the upper/lower baths
for (i=0;i<box.numBeads;i++) {
if (xs[i][2] <= box.thermoHeight) {
lowerIds.push_back(i);
}
else if (xs[i][2] >= (box.z-box.thermoHeightTop)) {
upperIds.push_back(i);
}
}
// first do the upper bath
// choose a particle at random and figure out what the new type should be
i = upperIds.at((int) floor(RanGen->Random()*upperIds.size()));
newPotential = 0.0;
newType = (types[i]+1)%2;
factor = types[i]-newType;
// now calculate the new energy using the cell list structure
// get the grid cell the atom is in
m1 = mapToGrid(xs[i]);
j = box.head[m1];
// interactions within the current cell
while (j != EMPTY) {
newPotential += calc_position_energy(i,j,newType);
j = box.bead_list[j];
}
for (k=0;k<box.cell_num_neighbors[m1];k++) {
// get this cell's placement
m2 = box.cell_neighbors[m1][k];
// loop through the atoms in this cell
j = box.head[m2];
while (j != EMPTY) {
newPotential += calc_position_energy(i,j,newType);
j = box.bead_list[j];
}
}
// get the boltzmann factor
deltaU = newPotential - 2.0*potentials[i];
boltz = exp((-1.0*deltaU + box.deltaMuTop*factor)/box.tempSetTop);
// determine if the move is accepted
if (boltz >= 1.0 || RanGen->Random() < boltz) {
types[i] = newType;
box.upperAccept += 1;
}
// now do the lower bath
// choose a particle at random and figure out what the new type is
i = lowerIds.at((int) floor(RanGen->Random()*lowerIds.size()));
newPotential = 0.0;
newType = (types[i]+1)%2;
factor = types[i]-newType;
// now calculate the new energy using the cell list structure
// get the grid cell the atom is in
m1 = mapToGrid(xs[i]);
j = box.head[m1];
// interactions within the current cell
while (j != EMPTY) {
newPotential += calc_position_energy(i,j,newType);
j = box.bead_list[j];
}
for (k=0;k<box.cell_num_neighbors[m1];k++) {
// get this cell's placement
m2 = box.cell_neighbors[m1][k];
// loop through the atoms in this cell
j = box.head[m2];
while (j != EMPTY) {
newPotential += calc_position_energy(i,j,newType);
j = box.bead_list[j];