-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCConfiguration.cpp
executable file
·1798 lines (1523 loc) · 73.2 KB
/
CConfiguration.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 "headers/CConfiguration.h"
using namespace Eigen;
using namespace std;
const double _srqtPi = sqrt (M_PI);
CConfiguration::CConfiguration(){
}
CConfiguration::CConfiguration( double timestep, model_param_desc modelpar, sim_triggers triggers, file_desc files)
{
// seed = 0: use time, else any integer
// init random number generator
setRanNumberGen(0);
_triggers = triggers;
_files = files;
_modelpar = modelpar;
_potRange = modelpar.urange;
_potStrength = modelpar.ustrength;
_pradius = modelpar.particlesize/2; //_pradius is now the actual radius of the particle. hence, I need to change the definition of the LJ potential to include (_pradius +_polyrad) - or maybe leave LJ pot out
_polyrad = modelpar.polymersize / 2; //This is needed for testOverlap for steric and HI stuff !!
_polydiamSq = pow(modelpar.polymersize,2);
_Invpolyrad = 1./_polyrad;
_fitRPinv = triggers.fitRPinv;
_boxsize = modelpar.boxsize;
_n_cellsAlongb = modelpar.n_cells;
_resetpos = (_boxsize/_n_cellsAlongb)/2; // puts the particle in the center of the cell at the origin
_timestep = timestep;
_ranSpheres = triggers.ranSpheres;
_trueRan = triggers.trueRan;
_ranRod = triggers.ranRod;
_noLub = triggers.noLub;
_LJPot = (triggers.stericType == "LJ" || triggers.stericType == "LJ025" );
if ( triggers.stericType == "LJ025" ) _epsilonLJ = 0.25;
_ranU = triggers.ranPot;
_poly = CPolymers();
_upot = 0;
_f_mob = Vector3d::Zero();
_f_sto = Vector3d::Zero();
_tracerMM = Matrix3d::Identity();
_mu_sto = sqrt( 2 * _timestep ); //timestep for stochastic force
_hpi = triggers.hpi;
_HI2 = false;
_hpi_u = modelpar.hpi_u;
_hpi_k = modelpar.hpi_k;
_binv = 2./_boxsize;//this needs to be 2/b apparently
_Nrods = 3*pow((_n_cellsAlongb+3), 2);
_rSq_arr.resize(_Nrods), _ri_arr.resize(_Nrods), _rk_arr.resize(_Nrods);
for (int i = 0; i < 3; i++){
_ppos(i) = _resetpos;
_startpos(i) = _resetpos;
_entryside[i] = 0;
_wallcrossings[i] = 0;
_boxnumberXYZ[i] = 0;
_prevpos(i) = _resetpos;
_lastcheck[i] = _startpos(i);
}
//_ppos << 3.625, 4.375, 4.875;
cout << "Init HI parameters .." << endl;
//Ewald sum stuff
_nmax = modelpar.nmax; // This corresponds to the r_cutoff = _nmax * _boxsize
_alpha = 1 * sqrt(M_PI) / _boxsize; // This value for alpha corresponds to the suggestion in Beenakker1986
_k_cutoff = 2. * _alpha * _alpha * _nmax * _boxsize; /* This corresponds to suggestion by Jain2012 ( equation 15 and 16 ). */
_nkmax = (int) (_k_cutoff * _boxsize / (2. * M_PI) + 0.5); /* The last bit (+0.5) may be needed to ensure that the next higher integer
* k value is taken for kmax */
_r_cutoffsq = pow(_nmax * _boxsize, 2); // Like Jain2012, r_cutoff is chosen such that exp(-(r_cutoff * alpha)^2) is small
// lubrication stuff
initLubStuff(modelpar.particlesize,modelpar.polymersize);
double lubweight = 1. / (1 + abs(_polyrad - _pradius)/(_polyrad + _pradius)); //this is between 1 and 0.5
double bcell = _boxsize/_n_cellsAlongb;
//old version _cutofflubSq = pow(lubweight*modelpar.lubcutint*(_polyrad + _pradius),2);
_cutofflubSq = pow(_polyrad*2*lubweight + bcell, 2); //this version accounts for the symmetry of the system
if (_EwaldTest != 0 || _ranSpheres) _cutofflubSq = pow(lubweight*modelpar.lubcutint*(_polyrad + _pradius),2); // old version
_stericrSq = pow(_pradius + _polyrad, 2);
// init HI vectors matrices, etc
// Configurations
_EwaldTest = modelpar.EwaldTest; // Predefine _edgeParticles. Ewaldtest = 0 runs normal. Ewaldtest = 1 runs the program with only spheres in the corners of the cells, i.e. _edgeParticles = 1, EwaldTest = 2 with 2 edgeparticles, and so on
_noEwald = false; // noEwald to use normal Rotne Prager instead of Ewald summed one
_2DLattice = false; //This creates a 2D lattice like in Phillips1990. I will be able to compare my data to settle whether my HI is correct.
_Vinv = 1./pow( _boxsize, 3 );
_cutoffMMsq = pow(0.05*_boxsize/_n_cellsAlongb,2);
if (_ranSpheres && _boxsize > 10) _cutoffMMsq = pow(0.03*_boxsize/_n_cellsAlongb,2);
//if (_polyrad != 0) _HI = true;
if (_EwaldTest != 0) _edgeParticles = _EwaldTest;
else _edgeParticles = (int) ( ( _boxsize/_n_cellsAlongb )/modelpar.polymersize + 0.0001);// round down
_sphereoffset = (_boxsize/_n_cellsAlongb) / _edgeParticles;
if (_ranRod) initRodsVec();//Needs to be before initPolySpheres!
cout << "Init Polymer Spheres .." << endl;
initPolySpheres();
if (!_triggers.noHI) {
// TODO LJ
//_LJPot = false;
// THIS NEEDS TO COME LAST !!!!!!!
cout << "Init Mobility Matrix .." << endl;
initConstMobilityMatrix();
calcTracerMobilityMatrix(true);
//_pbc_corr = 1 - 1/(_N_polyspheres+1); // assign system size dependent value to pbc correction for tracer displacement in porous medium
}
// TEST CUE to modify the directory the output data is written to!!
_testcue = "";
//TODO newrods - Only create as many newrods as were deleted
if (_ranRod) cout << "NOTE: Fixed number of rods in plane as 9*nrods!" << endl;
if (_ranRod) _testcue += "/RPYOverlap/fixnrods1";
if ( _noEwald ) _testcue += "/noEwald";
if (_2DLattice) _testcue += "/2DLattice";
if ( _EwaldTest > 0 ) _testcue += "/EwaldTest" + toString(_EwaldTest);
if ( _n_cellsAlongb != 1 ){
_testcue += "/n" + toString(_n_cellsAlongb);
cout << "Set _edgeParticles = " << _edgeParticles << endl; //<< " --- and _mobilityMatrix.rows() = " <<_mobilityMatrix.rows() << endl;
}
if (!_testcue.empty()) cout << "***********************************\n**** WARNING: String '_testcue' is not empty ****\n***********************************" << endl;
if ( _boxsize/_n_cellsAlongb != 10 ) cout << "***********************************\n**** WARNING: boxsize b != 10 * n_cell !!! ****\n***********************************" << endl;
if (_noEwald) cout << "~~~~~~~~~~~~~~~~~~~~~~~~~!!!!!!!!!! Warning, noEwald is activated ! !!!!!!!!!~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
// for (int l=0;l<10;l++){
// Vector3d rn_vec = Vector3d::Zero();
// rn_vec(0) = 3 + 0.001 * l;
// cout << rn_vec(0) << " \n" << lub2p(rn_vec, rn_vec.squaredNorm(), 8) <<"\n -----" << endl ;
// }
iftestEwald(testRealSpcM(); testEwald(); )
iftestLub2p(testLub2p();)
if (_triggers.preEwald==true && !_triggers.noHI){
_nxbins = (int)(0.5/_frac + 0.00001);
cout << "precompute Resistance Matrix for nxbins = " << _nxbins << endl;
initTrafoMatrixes();
_files.ewaldTable = "ewaldTables/ewaldTable_a" + toString(_modelpar.polymersize) + "p" + toString(_modelpar.particlesize)
+ "b" + toString(_modelpar.boxsize) + "nc" + toString(_modelpar.n_cells) + "nmax" + toString(_modelpar.nmax) + "frac" + toString(_frac) + ".txt";
if (boost::filesystem::exists( _files.ewaldTable.c_str() ) && (linecount( _files.ewaldTable ) == pow(_nxbins,3)) ){
cout << "ewaldTable found .. reading entries from file." << endl;
readResistanceMatrixTable();
}
else{
boost::filesystem::create_directory("ewaldTables");
precomputeResistanceMatrix();
}
}
}
void CConfiguration::updateStartpos(){
//This function is used if the particle should keep moving after each run, and not start at _resetpos again, like in the first run
//This (hopefully) will give better averages without having to spend a lot of steps in the beginning of each run to get away from _resetpos
for (int i = 0; i < 3; i++){
_startpos(i) = _ppos(i) + _boxsize * _boxnumberXYZ[i];
}
}
void CConfiguration::checkDisplacementforMM(){
double movedsq = 0;
for (int i=0; i<3; i++){
movedsq += pow(_ppos(i) + _boxsize * _boxnumberXYZ[i] - _lastcheck[i] , 2);
}
if ((!_triggers.preEwald) && movedsq > _cutoffMMsq ){
// Matrix3d tmp = _resMNoLub;
calcTracerMobilityMatrix(true);
// cout << "~~~~~~\nTableResM\n" << tmp << "\nEwaldResM\n" << _resMNoLub << endl;
// cout << "difference\n" << tmp - _resMNoLub << endl;
// cout << "relative difference\n" << (tmp - _resMNoLub).cwiseQuotient(_resMNoLub) << endl;
// cout << "relative to diagonal\n" << (tmp - _resMNoLub)/_resMNoLub(0,0) << endl;
// new start point for displacement check
_lastcheck[0] = _ppos(0) + _boxsize * _boxnumberXYZ[0];
_lastcheck[1] = _ppos(1) + _boxsize * _boxnumberXYZ[1];
_lastcheck[2] = _ppos(2) + _boxsize * _boxnumberXYZ[2];
}
else calcTracerMobilityMatrix(false); //TODO fullMM: set to true
}
Vector3d CConfiguration::midpointScheme(const Vector3d & V0dt, const Vector3d & F){
// Implementation of midpoint scheme according to Banchio2003
Vector3d ppos_prime;
const double n = 500;
ppos_prime = _ppos + V0dt / n;
Vector3d vec_rij;
Matrix3d lubM = Matrix3d::Zero();
// loop over tracer - particle mobility matrix elements
for (unsigned int j = 0; j < _N_polyspheres; j++){
vec_rij = ppos_prime - _polySpheres[j].pos;
lubM += lubricate(vec_rij);
}
//cout << "############# _mobilityMatrix #########\n" << _mobilityMatrix << endl;
//cout << "############# lubM #########\n" << lubM << endl;
// Add lubrication Part to tracer Resistance Matrix and invert
Matrix3d tracerMM_prime = invert3x3(_resMNoLub + lubM);
// Note that _f_sto has variance sqrt( _tracerMM ), as it is advised in the paper of Banchio2003
Vector3d V_primedt = tracerMM_prime * (F * _timestep + _f_sto * _mu_sto);
// return V_drift * dt
return n/2. * (V_primedt - V0dt);
}
int CConfiguration::makeStep(){
//move the particle according to the forces and record trajectory like watched by outsider
// if (_HI){
ifdebugPreComp(compareTableToEwald();)
_Vdriftdt = Vector3d::Zero();
_prevpos = _ppos;
bool v_nan = true;
bool lrgDrift = true;
int tmp = 0;
if ( _triggers.noHI == true ){_V0dt = (_f_mob * _timestep + _f_sto * _mu_sto);} // tracerMM = 1
else{
while (v_nan || lrgDrift){ // This loop repeats until the the midpoint scheme does not result in a NaN anymore!
_V0dt = _tracerMM * (_f_mob * _timestep + _f_sto * _mu_sto);
//TODO del noHI
//_V0dt = Eigen::Matrix3d::Identity() * (_f_mob * _timestep + _f_sto * _mu_sto);
if (!_noLub) _Vdriftdt = midpointScheme(_V0dt, _f_mob); //TODO Enable mid-point-scheme / backflow
v_nan = std::isnan(_Vdriftdt(0));
lrgDrift = (_Vdriftdt.squaredNorm() > 2);
if (v_nan || lrgDrift) {
cout << "is Nan = " << v_nan << " - largeDrift? = " << lrgDrift << endl;
cout << "_Vdriftdt.squaredNorm() = " << _Vdriftdt.squaredNorm() << endl;
calcStochasticForces();
//cout << "drifCorrection: Vdrift^2 = " << _Vdriftdt.squaredNorm() << endl;
tmp++;
cout << tmp << endl;
}
}
}
// Update particle position
_vdisp = (_V0dt + _Vdriftdt);
_ppos += _vdisp;
//cout << "---------\n_prevpos\n" << _prevpos << "\ndisplacement\n" << (_V0dt + _Vdriftdt) << endl;
if ((_V0dt + _Vdriftdt)(0) > 0.5){
cout << "........... big jump!" << endl;
}
//cout << (_prevpos - _ppos).norm() << endl << "--------" << endl;
if (std::isnan(_ppos(0))){
report("NaN found!");
return 1;
}
//report("TEST");
//if (_V0dt(0) > 0.1 ) cout << "############ " << _V0dt << endl;
return 0;
}
void CConfiguration::report(string reason){
cout << "~*~*~*~*~*~ ALERT ALERT ! ~*~*~*~*~*~" << endl;
cout << "----------------------------------------------------\n------------------- "<<reason<<" -------------\n----------------------------------------------------\n";
cout << "_edgeParticles " << _edgeParticles << endl;
cout << "_ppos: " << _ppos(0) << ", " << _ppos(1) << ", " << _ppos(2) << endl;
cout << "_prevpos: " << _prevpos(0) << ", " << _prevpos(1) << ", " << _prevpos(2) << endl;
cout << "_tracerMM: " << endl << _tracerMM << endl << " - " << endl;
cout << "Vdriftdt:\n" << _Vdriftdt << endl << "V0dt:\n" << _V0dt << endl << " **************** " << endl;
cout << "_f_mob\n" << _f_mob << endl << "_f_sto\n" << _f_sto << endl;
//cout << "-----mobility Matrix---\n" << _mobilityMatrix << endl;
cout << "_resMNoLub:\n" << _resMNoLub << endl;
cout << "_RMLub\n" << _RMLub << endl;
cout << "Cholesky3x3(_RMLub)\n" << Cholesky3x3(_RMLub) << endl;
if (_resMNoLub(0,0) == 0) cout << "NOTE: _resMNoLub(0,0) == 0 !\nThere was probably a problem with the lookup table for the precomputed Ewald" << endl;
//overlapreport();
//testIfSpheresAreOnRods();
}
int CConfiguration::checkBoxCrossing(){
//should the particle cross the confinement of the cube, let it appear on the opposite side of the box
for (int i = 0; i < 3; i++){
int exitmarker = 0;
if (_ppos(i) < 0.){
_ppos(i) += _boxsize;
_boxnumberXYZ[i] -= 1;
exitmarker = -1;
}
else if (_ppos(i) >= _boxsize){
_ppos(i) -= _boxsize;
_boxnumberXYZ[i] += 1;
exitmarker = 1;
}
if (exitmarker!=0){
if (_ranU) _poly.shiftPolySign(i, exitmarker);
if (_ranRod){
updateRodsVec(i, exitmarker);
//cout << "[["<<i<<"," << exitmarker <<"] ";
//prinRodPos(0); // cout print rod pos!
}
if ( (_ppos(i) > _boxsize) || (_ppos(i) < -1.) ){
cout << "Error: _ppos is outside of allowed range 0 < _ppos < _boxsize!";
report("Invalid _ppos range!");
return 1;
}
}
}
ifdebug(overlapreport();)
return 0;
}
void CConfiguration::countWallCrossing(int crossaxis, int exitmarker){
if (_entryside[crossaxis] == exitmarker){ // case: entryside same as exitside
_wallcrossings[0] += 1;
}
else if (_entryside[crossaxis] == (-1.0 * exitmarker)){ // case: entryside opposite exitside
_wallcrossings[1] += 1;
}
else { // case: exiting "sideways", i.e. through one of the four other sides
_wallcrossings[2] += 1;
}
for (int i = 0; i < 3; i++){ // mark new entryside
_entryside[i] = 0;
}
_entryside[crossaxis] = -1 * exitmarker;
}
void CConfiguration::calcStochasticForces(){
// the variate generator uses m_igen (int rand number generator),
// samples from normal distribution with variance 1 (later sqrt(2) is multiplied)
boost::variate_generator<boost::mt19937&, boost::normal_distribution<double> > ran_gen(
*m_igen, boost::normal_distribution<double>(0, 1));
Vector3d ran_v = Vector3d::Zero();
ran_v(0) = ran_gen();
ran_v(1) = ran_gen();
ran_v(2) = ran_gen();
if (!_triggers.noHI){
// return correlated random vector, which is scaled later by sqrt(2 dt)
//_f_sto = _RMLub.llt().matrixL() * ran_v;
_f_sto = Cholesky3x3(_RMLub) * ran_v;
//TODO del NoHI
//_f_sto=ran_v;
//cout << "\n" << _tracerMM * Cholesky3x3(_RMLub) << "\n===========\n" << Cholesky3x3(_tracerMM) << endl;
}
else { // no HI
_f_sto = ran_v;
}
}
void CConfiguration::calcMobilityForces(){
double rExpCutoff = pow(8*_potRange,2)+ _stericrSq;// Cutoff for calculation of exponential interaction potential
double Epot = 0;
double z1, z2;
if (_ranU){
z1 = 1./4 * _boxsize;
z2 = _boxsize - z1; //z is in cylindrical coordinates. This indicates above/below which value the exp potential is modifed for random signs.
}
//reset mobility forces to zero
_f_mob = Vector3d::Zero();
const double LJcutSq = 1.25992 * _stericrSq; //cutoff for Lennard-Jones calculation (at minimum)
// Calc rod distances loop (taken from testOverlap function)
double cellwidth = _boxsize/_n_cellsAlongb;
int mx=0;// Extra box if range is larger than 0.2b.
if (_ranU || _hpi || _potRange >= 2) mx=1;
for (int i = 0; i < 2; i++){
for (int k = i+1; k < 3; k++){
for (int n_i = -mx; n_i <= _n_cellsAlongb + mx; n_i++ ){
double r_i = _ppos(i) - cellwidth * n_i;
for (int n_k = -mx; n_k <= _n_cellsAlongb + mx; n_k++ ){
double utmp = 0, frtmp = 0;
double ri = r_i;
double rk = _ppos(k) - cellwidth * n_k;
double rSq = ri * ri + rk * rk;
if (_potStrength!=0 && rSq < rExpCutoff){
double r_abs=sqrt(rSq);
calculateExpPotential(r_abs, utmp, frtmp);
}
if (_ranU){
cout << "ERROR: Not yet implemented. Abort!";
abort();
// utmp = utmp * _poly.get_sign(plane, n);
// frtmp = frtmp * _poly.get_sign(plane, n);
// if (_ppos(plane) > z2){
// if (! _poly.samesign(1, plane, n)){
// _f_mob(plane) += utmp * 4 / _boxsize; //this takes care of the derivative of the potential modification and resulting force
// modifyPot(utmp, frtmp, _boxsize - _ppos(plane));
// }
// }
// else if (_ppos(plane) < z1){
// if (! _poly.samesign(-1, plane, n)){
// _f_mob(plane) -= utmp * 4 / _boxsize; //this takes care of the derivative of the potential modification and resulting force
// modifyPot(utmp, frtmp, _ppos(plane));
// }
// }
// n++; //index of next rod in curent plane
}
if (_LJPot && ( rSq < LJcutSq || _hpi )) calcLJPot(rSq, utmp, frtmp);
Epot += utmp;
_f_mob(i) += frtmp * ri;
_f_mob(k) += frtmp * rk;
}
}
}
}
_upot = Epot;
}
void CConfiguration::calcMobForcesBeads(){
//reset mobility forces to zero
_f_mob = Vector3d::Zero();
const double LJcutSq = 1.25992 * _stericrSq;
if (_potStrength!=0 || _LJPot){
//calc mobility forces between the tracer and all monomer beads
Vector3d vrij;
Vector3d F=Vector3d::Zero();
double U = 0;
for (unsigned int j = 0; j < _N_polyspheres; j++){
vrij = minImage(_ppos - _polySpheres[j].pos);
double rSq = vrij.squaredNorm();
double rij = sqrt(rSq);
// distance cutoff here
if (_potStrength!=0 && (rij - (_polyrad+_pradius) < 6*_potRange)){
double u = _potStrength * exp(-1 * rij / _potRange);
F += u / (_potRange * rij) * vrij;
U += u;
}
if (_LJPot && ( rSq < LJcutSq )){
double frtmp = 0;
calcLJPot(rSq, U, frtmp);
F += frtmp*vrij;
}
}
_upot = U;
_f_mob += F;
//cout << F << endl;
}
}
void CConfiguration::saveXYZTraj(string name, const int& move, string a_w){
Vector3d boxCoordinates;
boxCoordinates << _boxsize *_boxnumberXYZ[0], _boxsize *_boxnumberXYZ[1], _boxsize *_boxnumberXYZ[2];
Vector3d rtmp;
FILE *f = fopen(name.c_str(), a_w.c_str());
bool writeSpheres= ( _ranRod || _2DLattice || _EwaldTest != 0);
if (!writeSpheres){
fprintf(f, "%d\n%s (%8.3f %8.3f %8.3f) t=%d \n", 1, "sim_name", _boxsize, _boxsize, _boxsize, move);
}
else fprintf(f, "%d\n%s (%8.3f %8.3f %8.3f) t=%d \n", _N_polyspheres + 1, "sim_name", _boxsize, _boxsize, _boxsize, move);
// tracer particle
rtmp = _ppos;//+boxCoordinates;
fprintf(f, "%3s%9.3f%9.3f%9.3f \n","O", rtmp(0), rtmp(1), rtmp(2)); // relative position in box
if (writeSpheres){
for (unsigned int i = 0; i < _N_polyspheres; i++) {
rtmp = _polySpheres[i].pos;//+boxCoordinates;
fprintf(f, "%3s%9.3f%9.3f%9.3f \n","H", rtmp(0), rtmp(1), rtmp(2));
}
}
fclose(f);
}
void CConfiguration::setRanNumberGen(double seed){
if (seed == 0) {
m_igen = new boost::mt19937(static_cast<unsigned int>(time(NULL)));
cout << "random seed is time!" << endl;
} else {
m_igen = new boost::mt19937(static_cast<unsigned int>(seed));
cout << "random seed is " << seed << endl;
}
}
double CConfiguration::getPosVariance(){
//function to return the variance, to save it as an instant value
double var = 0;
for (int m = 0; m < 3; m++){ //calculate (r_m - r_0)^2|_i
var += pow((_ppos(m) + _boxsize *_boxnumberXYZ[m] - _startpos(m)) , 2);
}
return var;
}
double CConfiguration::get1DPosVariance(int dim){
//function to return the variance of just one dimension x = 0, y = 1 or z = 2
return pow((_ppos(dim) + _boxsize *_boxnumberXYZ[dim] - _startpos(dim)) , 2);
}
bool CConfiguration::checkFirstPassage(double mfpPos, int dim){ //TODO
//function returns true if in the last step the momentary "way point" (_mfpIndex * xinterval) has been crossed in dim-direction
// where dim = 0, 1, 2 -> x, y, z. Otherwise it returns false
if ((_ppos(dim) + _boxsize*_boxnumberXYZ[dim] - _startpos(dim)) > (mfpPos) ) return true;
else return false;
}
void CConfiguration::moveBack(){
//moves particle back to previous position
_ppos = _prevpos;
}
//****************************POTENTIALS**********************************************************
void CConfiguration::calculateExpPotential(const double &r, double& U, double& Fr){
//function to calculate an exponential Potential U = U_0 * exp(-1 * r * k)
// k is the interaction range. U_0 is the strength of the potential
//which is attractive if direction = -1, and repulsive if direction = 1
//The potential is weighted with kT!
U = _potStrength * exp(-1 * r / _potRange);
Fr = U / (_potRange * r); //This is the force divided by the distance to the rod!
}
void CConfiguration::calculateExpHPI(const double &r, double& U, double& Fr){
double u = _hpi_u * exp( - r / _hpi_k);
U += u;
Fr += u / (_hpi_k * r);
}
void CConfiguration::modifyPot(double& U, double& Fr,const double dist){
//function to modify the potential according to the distance along the polymer axis to the next neighbor,
//in case the next neighboring polymer part is of opposite sign
U = U * 4 * dist/_boxsize;
Fr = Fr * 4 * dist/_boxsize;
}
//****************************STERIC HINDRANCE****************************************************//
bool CConfiguration::testOverlap(double stericrSq_preE){
//Function to check, whether the diffusing particle of size psize is overlapping with any one of the rods (edges of the box)
//mostly borrowed from moveParticleAndWatch()
//"PROPER" METHOD FOR EwaldTest, where the overlap is calculated for spheres in the corners, not rods.
if ((_EwaldTest != 0 || _2DLattice)){
Vector3d vrij;
for (unsigned int j = 0; j < _N_polyspheres; j++){
vrij = minImage(_ppos - _polySpheres[j].pos);
if (vrij.squaredNorm() <= _stericrSq+0.001){
return true;
}
}
return false;
}
if (_ranRod){
Vector3d testpos;
for (int axis=0;axis<3;axis++){
testpos = _ppos;
testpos(axis) = 0.;
for (int l = 0; l < _rodvec[axis].size(); l++){
if ((testpos - _rodvec[axis][l].coord).squaredNorm() < _stericrSq + 0.0001){
//cout << "overlaps! ppos = " << _ppos(0) << ", " << _ppos(1) << ", " << _ppos(2) << endl;
return true;
}
}
}
return false;
}
double r_i = 0, r_k = 0;
double r_sq = 0;
double cellwidth = _boxsize/_n_cellsAlongb;
if (stericrSq_preE != 0){
Eigen::Vector3d cellpos; //stores the position r of the particle relative to the cell
for (int i=0; i<3; i++){
cellpos(i) = fmod(_ppos(i),cellwidth); //position of the particle inside the cell
}
for (int i = 0; i < 2; i++){
for (int k = i+1; k < 3; k++){
for (int n_i = 0; n_i <= 1; n_i++ ){
r_i = _ppos(i) - cellwidth * n_i;
for (int n_k = 0; n_k <= 1; n_k++ ){
r_k = _ppos(k) - cellwidth * n_k;
r_sq = r_i * r_i + r_k * r_k; //distance to the rods
if (r_sq <= stericrSq_preE + 0.00001){
return true;
}
}
}
}
}
return false;
}
for (int i = 0; i < 2; i++){
for (int k = i+1; k < 3; k++){
for (int n_i = 0; n_i <= _n_cellsAlongb; n_i++ ){
r_i = _ppos(i) - cellwidth * n_i;
for (int n_k = 0; n_k <= _n_cellsAlongb; n_k++ ){
r_k = _ppos(k) - cellwidth * n_k;
r_sq = r_i * r_i + r_k * r_k; //distance to the rods
if (r_sq <= _stericrSq + 0.00001){
return true;
}
}
}
}
}
return false;
}
void CConfiguration::calcLJPot(const double& rSq, double& U, double& Fr){
//Function to calculate the Lennard-Jones Potential
double por6 = pow((_stericrSq / rSq ), 3); //por6 stands for "p over r to the power of 6" .
U += 4. * _epsilonLJ * ( por6*por6 - por6 + 0.25 );
Fr += 24. * _epsilonLJ / ( rSq ) * ( 2 * por6*por6 - por6 );
}
void CConfiguration::initPolySpheres(){
_polySpheres.clear();
// store the edgeParticle positions, so that I can simply loop through them later
std::vector<Vector3d> zeroPos( 3 * _edgeParticles - 2 , Vector3d::Zero() );
Vector3d nvec;
// store the edgeParticle positions in first cell in zeroPos
for (int i = 1; i < _edgeParticles; i++){
double tmp = i * _sphereoffset;
zeroPos[i](0) = tmp;
zeroPos[i + (_edgeParticles - 1)](1) = tmp;
zeroPos[i + 2 * (_edgeParticles - 1)](2) = tmp;
}
for (int nx=0; nx < _n_cellsAlongb; nx++){
for (int ny=0; ny < _n_cellsAlongb; ny++){
for (int nz=0; nz < _n_cellsAlongb; nz++){
nvec << nx, ny, nz; // Position of 0 corner of the simulation box
for (unsigned int i = 0; i < zeroPos.size(); i++){
_polySpheres.push_back( CPolySphere( zeroPos[i] + nvec * _boxsize/_n_cellsAlongb ) );
//cout << "----" << _polySpheres[i].pos << endl;
}
}
}
}
// THE HI2 one needs to come here for now!
//*********** HI2 ************
// add spheres according for nmax number of extra adjacent boxes in both directions along one axis
// if (_HI2){
// int NpolysphereTmp = _polySpheres.size();
// for (int nx=-_nmax; nx <= _nmax; nx++){
// for (int ny=-_nmax; ny <= _nmax; ny++){
// for (int nz=-_nmax; nz <= _nmax; nz++){
// nvec << nx, ny, nz;
// if (nvec == Vector3d::Zero()) continue; // Dont add spheres for central box. They're already there
// for (unsigned int i = 0; i < NpolysphereTmp; i++){
// Vector3d newpos = _polySpheres[i].pos + nvec * _boxsize;
// _polySpheres.push_back( CPolySphere( newpos ) );
// //cout << "----" << _polySpheres[i].pos << endl;
// }
// }
// }
// }
// }
// ******** Phillips1990 *********
// rods are arranged on a 2D square lattice. The rods point into the z-direction. The lattice is in the x-y-plane.
// I ONLY CHANGE THE zeroPos Vector3d Array!
if (_2DLattice){
_polySpheres.clear();
nvec = Vector3d::Zero();
zeroPos.resize(_edgeParticles);
for (int i = 0; i < _edgeParticles; i++){
double tmp = i * _sphereoffset;
zeroPos[i](0) = 0;
zeroPos[i](1) = 0;
zeroPos[i](2) = tmp;
}
for (int nx=0; nx < _n_cellsAlongb; nx++){
for (int ny=0; ny < _n_cellsAlongb; ny++){
for (int nz=0; nz < _n_cellsAlongb; nz++){
nvec << nx, ny, nz; // Position of 0 corner of the simulation box
for (unsigned int i = 0; i < zeroPos.size(); i++){
_polySpheres.push_back( CPolySphere( zeroPos[i] + nvec * _boxsize/_n_cellsAlongb ) );
//cout << "----" << _polySpheres[i].pos << endl;
}
}
}
}
}
// ****** RANDOM RODS *******
//_edgeParticles stays the same
if (_ranRod){
copySphereRods();
}
// ******* RANSPHERE ********
bool overlap = true;
Vector3d vrij;
Vector3d spos;
int Nspheres = _n_cellsAlongb * _n_cellsAlongb * _n_cellsAlongb;
if (_ranSpheres){ // This serves to assign a random position to the edgeparticles. Note: Only use it with _EwaldTest = 1!
int retry = 0;
while (overlap==true && retry < 1000){
_polySpheres.clear();
//create sphere in corner at origin
_polySpheres.push_back( CPolySphere( Vector3d::Zero() ) );
++retry;
//cout << "retry " << retry << endl;
for (int nx=0; nx < _n_cellsAlongb; nx++){
for (int ny=0; ny < _n_cellsAlongb; ny++){
for (int nz=0; nz < _n_cellsAlongb; nz++){
nvec << nx, ny, nz; // Position of 0 corner of the simulation box
if (nvec == Vector3d::Zero()) continue;
else{
Vector3d cellcoordinate = nvec * _boxsize/_n_cellsAlongb;
for (int count=0; count < 200; count++){
overlap = false;
for (int k = 0; k<3; k++){
//offset takes care that there is less chance of overlap for large polyrads
//it increases from 0 to 2*polyrad, for the cell at the origin and the one most far away from it, respectively
double offset = 2*_polyrad*(nvec.norm() / (sqrt(3)*(_n_cellsAlongb-1)));
//cout << "offset = " << offset << endl;
// Calculate random position of sphere spos
spos(k) = (_boxsize/_n_cellsAlongb - offset) *zerotoone() + cellcoordinate(k);
if (_trueRan) spos(k) = _boxsize * zerotoone();
//cout << "spos\n" <<spos << endl;
}
for (int l = 1; l < _polySpheres.size(); l++){
vrij = minImage(spos - _polySpheres[l].pos);
if (vrij.norm() < 2*_polyrad + 0.000001){
overlap = true;
//cout << "found overlap! rij = " << vrij.norm() << endl;
break;
}
}
// if there is no overlap after the previous for loop to test overlap, then stop this for loop and accept the sphere pos
if (overlap==false) break;
}
if (overlap==true){
//cout << "* Overlap between polyspheres. Retry!" << endl;
break;//break out of count loop
}
_polySpheres.push_back( CPolySphere( spos ) );
}
if (overlap==true) break;//break out of nz loop
}
if (overlap==true) break;
}
if (overlap==true) break;
}
}
cout << "ranSphere initiation retries: " << retry << endl;
if (overlap==true){
cout << "ERROR: Overlap between polyspheres could not be avoided." << endl;
throw 2;
}
}
_N_polyspheres = _polySpheres.size();
}
//**************************** HYDRODYNAMICS ****************************************************//
void CConfiguration::initConstMobilityMatrix(){
if (_triggers.noHI) return;
double rxi = 0.0, ryi = 0.0, rzi = 0.0;
double rij = 0.0, rijsq = 0.0;
const double asq = _polyrad * _polyrad;
// create mobility matrix - Some elements remain constant throughout the simulation. Those are stored here.
_mobilityMatrix = MatrixXd::Identity( 3 * (_N_polyspheres + 1) , 3 * (_N_polyspheres + 1) );
// Create matrix that stores previous result of conjugate gradient method, for faster conversion.
_prevCG = Eigen::MatrixXd::Identity(3 * (_N_polyspheres + 1) , 3 );
// Eigen-vector for interparticle distance. Needs to initialized as zero vector for self mobilities.
Vector3d vec_rij = Vector3d::Zero();
// on-diagonal elements of mobility matrix: TRACER PARTICLE
Matrix3d selfmob = realSpcSm( vec_rij, true, _pradius * _pradius ) + reciprocalSpcSm( vec_rij, _pradius * _pradius );
double self_plus = 1. + _pradius / sqrt (M_PI) * ( - 6. * _alpha + 40. * pow(_alpha,3) * _pradius * _pradius / 3. );
if (!_ranRod && !_noEwald && !_HI2) _mobilityMatrix.block<3,3>(0,0) = selfmob + Matrix3d::Identity() * self_plus; // ewaldCorr
// now on diagonals for POLYMER SPHERES
selfmob = realSpcSm( vec_rij, true, asq ) + reciprocalSpcSm( vec_rij, asq );
// double self_plus = _pradius/_polyrad + _pradius / sqrt (M_PI) * ( - 6. * _alpha ); //TODO alt
self_plus = _pradius/_polyrad + _pradius / sqrt (M_PI) * ( - 6. * _alpha + 40. * pow(_alpha,3) * _polyrad * _polyrad / 3. );
selfmob(0,0) += self_plus;
selfmob(1,1) += self_plus;
selfmob(2,2) += self_plus;
for (unsigned int i = 1; i < _N_polyspheres + 1 ; i++) {
unsigned int i_count = 3 * i;
/*_mobilityMatrix(0,0) = 1; already taken care of due to identity matrix. The extra F_i0 part in the Ewald sum is only correction to reciprocal sum.
* I leave out the reciprocal summation for the tracer particle self diff, because it is in only in the simulation box unit cell. */
if (_ranRod || _noEwald || _HI2) _mobilityMatrix.block<3,3>(i_count,i_count) = _pradius/_polyrad * Matrix3d::Identity();
else _mobilityMatrix.block<3,3>(i_count,i_count) = selfmob;
}
// The mobility matrix elements for the interacting edgeParticles are stored here, since they do not change position
Matrix3d muij = Matrix3d::Zero();
for (unsigned int i = 0; i < _N_polyspheres; i++){
unsigned int i_count = 3 * (i + 1); // plus 1 is necessary due to omitted tracer particle
for (unsigned int j = i + 1; j < _N_polyspheres; j++) {
vec_rij = _polySpheres[i].pos - _polySpheres[j].pos;
unsigned int j_count = 3 * (j + 1); // plus 1 is necessary due to omitted tracer particle
/*
* Calculation of RP Ewald sum
*/
if (_ranRod) muij = RPYamakawaPS(vec_rij, asq);
else if (_noEwald) muij = RotnePrager( minImage(vec_rij), asq );
else if (_HI2) muij = RotnePrager( vec_rij, asq );
else muij = realSpcSm( vec_rij, false, asq ) + reciprocalSpcSm( vec_rij, asq );
// both lower and upper triangular of symmetric matrix need be filled
_mobilityMatrix.block<3,3>(j_count,i_count) = muij;
_mobilityMatrix.block<3,3>(i_count,j_count) = muij;
//cout << "----------------\n" << selfmob << endl;
}
}
initMreciprocalTracer();
}
void CConfiguration::calcTracerMobilityMatrix(bool full){
if (_triggers.noHI) return;
const double asq = 0.5*(_polyrad * _polyrad + _pradius * _pradius);
// vector for outer product in muij
Vector3d vec_rij;
double rij_sq;
Matrix3d lubM = Matrix3d::Zero();
Matrix3d muij;
//Matrix3d mobmatrixHI2 = Matrix3d::Identity(); //identity matrix is the self mobility of the tracer
// full is always disabled if the precomputes Resistance Matrix is used!
if (_triggers.preEwald && !full) _resMNoLub = getTableResM();
// loop over tracer - particle mobility matrix elements
for (unsigned int j = 0; j < _N_polyspheres; j++){
vec_rij = _ppos - _polySpheres[j].pos;
if (_noEwald ) vec_rij = minImage(vec_rij);
//vec_rij = minImage(vec_rij); // tmpminim
//rij_sq = vec_rij.squaredNorm();
// if (rij_sq <= (_stericrSq + 0.00001)){ // If there is overlap between particles, the distance is set to a very small value, according to Brady and Bossis in Phung1996
// // set distance to 0.00000001 + _stericr but preserve direction
// double corr = (0.00001 + sqrt(_stericrSq)) / sqrt(rij_sq);
// vec_rij *= corr;
// }
if (full){ // when _triggers.preEwald is true, full will always be false
// Calculation of different particle width Rotne-Prager Ewald sum
unsigned int j_count = 3 * (j + 1); // plus 1 is necessary due to omitted tracer particle
if (_ranRod || _noEwald || _HI2 ) muij = RotnePrager( vec_rij, asq );
// TODO Mreci Tracer
// else muij = realSpcSm( vec_rij, false, asq ) + reciprocalSpcSm( vec_rij, asq );
else muij = realSpcSm( vec_rij, false, asq ) + reciprocalSpcSmTracer( vec_rij );
_mobilityMatrix.block<3,3>(j_count,0) = muij;
_mobilityMatrix.block<3,3>(0,j_count) = muij;
//TODO delete this if the other HI2 works!
// else {
// // This will be excecuted if I use the alternative method of calculating HI without Ewald and without matrix inversion
// mobmatrixHI2 += calcHI2MobMat( vec_rij, asq );
// }
}
if (!_noLub ) lubM += lubricate(vec_rij);
}
//cout << "############# _mobilityMatrix #########\n" << _mobilityMatrix << endl;
//cout << "############# lubM #########\n" << lubM << endl;
// create resistance matrix - Some elements remain constant throughout the simulation. Those are stored here.
if (full){
_resMNoLub = ConjGradInvert(_mobilityMatrix);
//_resMNoLub = CholInvertPart(_mobilityMatrix);
if (_triggers.preEwald){
Matrix3d tmpchol = Cholesky3x3(_resMNoLub);
_nanfound=false;
for (size_t i = 0; i < 3; i++){
for (size_t j = 0; j < 3; j++){
// look for nans
if ( std::isnan(tmpchol(i,j)) ){
cout << "\n------- Error: NaN found ------------" << endl;
cout << "--> ppos:\n" << _ppos << endl;
cout << "_resMNoLub:\n" << _resMNoLub << endl;
_nanfound=true;
_nancount += 1;
// This approximates the mobility matrix at a certain position with a neighboring value if there is problems with the numerical solution
_resMNoLub = _resMPrev;
//abort();
break;
}
}
if (_nanfound) break;
}
}
}
// else{
// _resMNoLub = invert3x3(mobmatrixHI2);
// }
// Add lubrication Part to tracer Resistance Matrix and invert
// cout << "-------\n" << _resMNoLub << endl;
_RMLub = _resMNoLub + lubM;
_tracerMM = invert3x3(_RMLub);
//cout << _tracerMM << endl << "........................." << endl;
}
void CConfiguration::updateMobilityMatrix(){// ONLY for ranRod, since I dont have pbc.
if (_triggers.noHI) return;
const double asqPoly = _polyrad * _polyrad;
const double asqTracer = 0.5*(_polyrad * _polyrad + _pradius * _pradius);
Matrix3d muij = Matrix3d::Zero();
unsigned int i_count, j_count;
// create mobility matrix - Some elements remain constant throughout the simulation. Those are stored here.
_mobilityMatrix = MatrixXd::Identity( 3 * (_N_polyspheres + 1) , 3 * (_N_polyspheres + 1) );
// resize matrix that stores previous result of conjugate gradient method, for faster conversion.
_prevCG = Eigen::MatrixXd::Identity(3 * (_N_polyspheres + 1) , 3 );
// Eigen-vector for interparticle distance. Needs to initialized as zero vector for self mobilities.
Vector3d vec_rij = Vector3d::Zero();
//TODO maybe store i_count and j_count first.
//const int Nspheres = _N_polyspheres
//std::array<int, _N_polyspheres> icount_arr;
//Update the polymer Spheres mobility matrix elements
for (unsigned int i = 0; i < _N_polyspheres; i++){
i_count = 3 * (i + 1); // plus 1 is necessary due to omitted tracer particle
// PolySphere Self interaction
_mobilityMatrix.block<3,3>(i_count,i_count) *= _pradius/_polyrad;
// Tracer-polySphere RP
vec_rij = _ppos - _polySpheres[i].pos;
muij = RotnePrager( vec_rij, asqTracer );
_mobilityMatrix.block<3,3>(i_count,0) = muij;
_mobilityMatrix.block<3,3>(0,i_count) = muij;
// PolySphere - PolySphere RP
for (unsigned int j = i + 1; j < _N_polyspheres; j++) {
vec_rij = _polySpheres[i].pos - _polySpheres[j].pos;
j_count = 3 * (j + 1); // plus 1 is necessary due to omitted tracer particle
muij = RPYamakawaPS(vec_rij, asqPoly);
// both lower and upper triangular of symmetric matrix need be filled
_mobilityMatrix.block<3,3>(j_count,i_count) = muij;
_mobilityMatrix.block<3,3>(i_count,j_count) = muij;
}
}
}
void CConfiguration::computeMobilityMatrixHere(Eigen::Vector3d rpos, double xinterval){
bool lubtmp = _noLub; //store current value for lubrication
Vector3d ppostmp = _ppos;
_noLub = true;
_ppos = rpos;
_nanfound=false;
double ptmp = _pradius;