-
Notifications
You must be signed in to change notification settings - Fork 33
/
move.h
5120 lines (4594 loc) · 200 KB
/
move.h
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
#ifndef FAUNUS_MOVE_H
#define FAUNUS_MOVE_H
#ifndef SWIG
#include <functional>
#include <memory>
#include <faunus/common.h>
#include <faunus/point.h>
#include <faunus/average.h>
#include <faunus/textio.h>
#include <faunus/geometry.h>
#include <faunus/energy.h>
#include <faunus/textio.h>
#include <faunus/json.h>
#include <faunus/titrate.h>
#ifdef ENABLE_MPI
#include <faunus/mpi.h>
#endif
#endif
namespace Faunus
{
/**
* @brief Monte Carlo move related classes
*
* All moves are based on `Movebase` and most end-users
* will probably want to start with `Propagator` which
* collects all moves and allows for control via input
* JSON files.
*/
namespace Move
{
template<typename Tkey=std::string>
class AcceptanceMap
{
private:
typedef std::map<Tkey, Average<double> > map_type;
map_type accmap; //!< move acceptance ratio
map_type sqrmap; //!< mean square displacement map
public:
void accept( Tkey k, double msq )
{
accmap[k] += 1;
sqrmap[k] += msq;
}
void reject( Tkey k )
{
accmap[k] += 0;
}
string info( char l = 10 )
{
using namespace textio;
std::ostringstream o;
o << indent(SUB) << "Move Statistics:" << endl
<< indent(SUBSUB) << std::left << setw(20) << "Id"
<< setw(l + 1) << "Acc. " + percent
<< setw(l) << "Nmoves"
<< setw(l + 9) << rootof + bracket("msq" + squared) + "/" + angstrom << endl;
for ( auto m : accmap )
{
string id = m.first;
o << indent(SUBSUB) << std::left << setw(20) << id;
o.precision(3);
o << setw(l) << accmap[id].avg() * 100
<< setw(l) << accmap[id].cnt
<< setw(l) << sqrt(sqrmap[id].avg()) << endl;
}
return o.str();
}
void _test( UnitTest &t, const string &prefix )
{
for ( auto &m : accmap )
{
std::ostringstream o;
o << m.first;
t(prefix + "_Acceptance" + o.str(), m.second.avg());
}
}
};
/**
* @brief Add polarisation step to an arbitrary move
*
* This class will modify any MC move to account for polarization
* using an iterative procedure.
* An electric field calculation is inserted
* after the original trial move whereafter it will iteratively
* calculate induced dipole moments on all particles.
* The energy change function will evaluate the *total*
* system energy as all dipoles in the system may have changed.
* This is thus an expensive computation and is best used with
* MC moves that propagate all particles.
*
* Updating induced moments is an iterative N*N operation and
* very inefficient for MC moves that update only a subset of the system.
* In liquid systems that propagate only slowly as a function of MC steps
* one may attempt to update induced dipoles less frequently at the
* expense of accuracy.
* For repeating moves -- i.e. molecular translate/rotate or atomic
* translation -- polarisation is updated only after all moves have
* been carried out.
*
* @note Will currently not work for Grand Caninical moves
*/
template<class Tmove>
class PolarizeMove : public Tmove
{
private:
using Tmove::spc;
using Tmove::pot;
int Ntrials; // Number of repeats within move
int max_iter; // max numbr of iterations
double threshold; // threshold for iteration
bool updateDip; // true if ind. dipoles should be updated
Eigen::MatrixXd field; // field on each particle
Average<int> numIter; // average number of iterations per move
/**
* @brief Updates dipole moment w. permanent plus induced dipole moment
* @param pot Hamiltonian
* @param p Particles to update
*/
template<typename Tenergy, typename Tparticles>
void induceDipoles( Tenergy &pot, Tparticles &p )
{
int cnt = 0;
Eigen::VectorXd mu_err_norm((int) p.size());
do
{
cnt++;
mu_err_norm.setZero();
field.setZero();
pot.field(p, field);
for ( size_t i = 0; i < p.size(); i++ )
{
Point E = field.col(i); // field on i
Point mu_trial = p[i].alpha() * E + p[i].mup();// new tot. dipole
Point mu_err = mu_trial - p[i].mu() * p[i].muscalar();// mu difference
mu_err_norm[i] = mu_err.norm(); // norm of previous row
p[i].muscalar() = mu_trial.norm(); // update dip scalar in particle
if ( p[i].muscalar() > 1e-6 )
p[i].mu() = mu_trial / p[i].muscalar(); // update article dip.
}
if ( cnt > max_iter )
throw std::runtime_error("Field induction reached maximum number of iterations.");
}
while ( mu_err_norm.maxCoeff() > threshold ); // is threshold OK?
numIter += cnt; // average number of iterations
}
void _trialMove() override
{
Tmove::_trialMove();
Ntrials++;
int updateAt = 1; // default: dipoles are always updated
if ( !Tmove::mollist.empty())
updateAt = Tmove::mollist[Tmove::currentMolId].repeat;
else
Ntrials = 1; // in case move(n) is called w. n>1
updateDip = (Ntrials == updateAt);
if ( updateDip )
{
field.resize(3, spc->trial.size());
induceDipoles(*pot, spc->trial);
}
}
double _energyChange() override
{
if ( updateDip )
return Energy::systemEnergy(*spc, *pot, spc->trial)
- Energy::systemEnergy(*spc, *pot, spc->p);
else
return Tmove::_energyChange();
}
void _rejectMove() override
{
Tmove::_rejectMove();
if ( updateDip )
Tmove::spc->trial = Tmove::spc->p;
}
void _acceptMove() override
{
Tmove::_acceptMove();
if ( updateDip )
Tmove::spc->p = Tmove::spc->trial;
}
string _info() override
{
std::ostringstream o;
using namespace textio;
o << pad(SUB, Tmove::w, "Polarisation updates") << numIter.cnt << "\n"
<< pad(SUB, Tmove::w, "Polarisation threshold") << threshold << "\n"
<< pad(SUB, Tmove::w, "Polarisation iterations") << numIter.avg()
<< " (max. " << max_iter << ")" << "\n"
<< Tmove::_info();
return o.str();
}
public:
double getThreshold() const { return threshold; }
int getMaxIterations() const { return max_iter; }
template<class Tspace>
PolarizeMove( Tmjson &in, Energy::Energybase<Tspace> &e, Tspace &s ) :
Tmove(in, e, s)
{
threshold = in.value("pol_threshold", 0.001);
max_iter = in.value("max_iterations", 40);
}
template<class Tspace>
PolarizeMove( Energy::Energybase<Tspace> &e, Tspace &s, Tmjson &j ) :
Tmove(e, s, j)
{
threshold = j.value("pol_threshold", 0.001);
max_iter = j.value("max_iterations", 40);
}
//PolarizeMove( const Tmove &m ) : max_iter(40), threshold(0.001), Tmove(m) {};
double move( int n ) override
{
Ntrials = 0;
return Tmove::move(n);
}
};
/**
* @brief Base class for Monte Carlo moves
*
* The is a base class that handles Monte Carlo moves and derived classes
* are required to implement the following pure virtual (and private)
* functions:
*
* - `_trialMove()`
* - `_energyChange()`
* - `_acceptMove()`
* - `_rejectMove()`
* - `_info()`
*
* These functions should be pretty self-explanatory and are - via wrapper
* functions - called by move(). It is important that the _energyChange() function
* returns the full energy associated with the move. For example, for NPT
* moves the pV term should be included and so on. Try not to override
* the move() function as this should be generic to all MC moves.
*
* @date Lund, 2007-2011
*/
template<class Tspace>
class Movebase
{
private:
unsigned long int cnt_accepted; //!< number of accepted moves
double dusum; //!< Sum of all energy changes
virtual void _test( UnitTest & ); //!< Unit testing
virtual void _trialMove()=0; //!< Do a trial move
virtual void _acceptMove()=0; //!< Accept move and config
virtual void _rejectMove()=0; //!< Reject move and config
virtual double _energyChange()=0;//!< Energy change of move (kT)
void acceptMove(); //!< Accept move (wrapper)
void rejectMove(); //!< Reject move (wrapper)
double energyChange(); //!< Energy (wrapper)
bool metropolis( const double & ) const;//!< Metropolis criteria
TimeRelativeOfTotal<std::chrono::microseconds> timer;
/** @brief Information as JSON object */
virtual Tmjson _json() { return Tmjson(); }
protected:
virtual string _info()=0; //!< info for derived moves
void trialMove(); //!< Do a trial move (wrapper)
Energy::Energybase<Tspace> *pot; //!< Pointer to energy functions
Space<typename Tspace::GeometryType, typename Tspace::ParticleType> *spc; //!< Pointer to Space
string title; //!< Title of move (mandatory!)
string cite; //!< Reference, url, DOI etc.
char w; //!< info text width. Adjust this in constructor if needed.
unsigned long int cnt; //!< total number of trial moves
virtual bool run(); //!< Runfraction test
typename Tspace::Change change; //!< Object describing changes made to Space
bool useAlternativeReturnEnergy; //!< Return a different energy than returned by _energyChange(). [false]
double alternateReturnEnergy; //!< Alternative return energy
struct MolListData
{
double prob; // probability of performing a move
bool perAtom; // repeat move for each molecule?
bool perMol; // repeat move for atom in molecules?
int repeat; // total number of repeats
unsigned long Nattempts; // # of attempted moves
unsigned long Naccepted; // # of accepted moves
Point dir; // translational move directions
double dp1; // displacement parameter 1
double dp2; // displacement parameter 2
MolListData() : prob(1.0), perAtom(false), perMol(false),
repeat(1), Nattempts(0), Naccepted(0), dir(1, 1, 1), dp1(0), dp2(0) {}
MolListData( Tmjson &j )
{
*this = MolListData();
prob = j.value("prob", 1.0);
perMol = j.value("permol", false);
perAtom = j.value("peratom", false);
dir << (j["dir"] | std::string("1 1 1"));
}
};
std::map<int, MolListData> mollist; //!< Move acts on these molecule id's
/**
* @brief Iterate over json object where each key is a molecule
* name and the value is read as `MolListData`.
*/
void fillMolList( Tmjson &j )
{
for ( auto it = j.begin(); it != j.end(); ++it )
{ // iterate over molecules
auto mol = spc->molList().find(it.key()); // is molecule defined?
if ( mol != spc->molList().end())
addMol(mol->id, MolListData(it.value()));
#ifndef NDEBUG
else
std::cerr << title << ": unknown molecule '" << it.key() << "' was not added.\n";
#endif
}
}
/** @brief Internal, deterministic random number generator, independent of global */
static RandomTwister<> &_slump()
{
static RandomTwister<> r;
return r;
}
public:
Movebase( Energy::Energybase<Tspace> &, Tspace & );//!< Constructor
virtual ~Movebase();
double
runfraction; //!< Fraction of times calling move() should result in an actual move. 0=never, 1=always.
virtual double move( int= 1 ); //!< Attempt `n` moves and return energy change (kT)
string info(); //!< Returns information string
void test( UnitTest & ); //!< Perform unit test
double getAcceptance() const; //!< Get acceptance [0:1]
void addMol( int, const MolListData &d = MolListData()); //!< Specify molecule id to act upon
Group *randomMol();
int randomMolId(); //!< Random mol id from mollist
int currentMolId; //!< Current molid to act upon
Tmjson json()
{ //!< Information as JSON object
Tmjson j;
if ( cnt > 0 )
{
j[title] = {
{"trials", cnt},
{"acceptance", getAcceptance()},
{"runfraction", runfraction},
{"relative time", timer.result()}
};
j = merge(j, _json());
}
return j;
}
#ifdef ENABLE_MPI
Faunus::MPI::MPIController* mpiPtr;
#endif
};
/**
* @brief Constructor
* @param e Energy class
* @param s Space
*/
template<class Tspace>
Movebase<Tspace>::Movebase( Energy::Energybase<Tspace> &e, Tspace &s )
{
e.setSpace(s);
pot = &e;
spc = &s;
cnt = cnt_accepted = 0;
dusum = 0;
w = 30;
runfraction = 1;
useAlternativeReturnEnergy = false; //this has no influence on metropolis sampling!
change.clear();
#ifdef ENABLE_MPI
mpiPtr=nullptr;
#endif
}
template<class Tspace>
Movebase<Tspace>::~Movebase() {}
template<class Tspace>
void Movebase<Tspace>::addMol( int molid, const MolListData &d )
{
mollist[molid] = d;
}
template<class Tspace>
int Movebase<Tspace>::randomMolId()
{
if ( !mollist.empty())
{
auto it = _slump().element(mollist.begin(), mollist.end());
if ( it != mollist.end())
{
it->second.repeat = 1;
if ( it->second.perMol )
it->second.repeat *= spc->numMolecules(it->first);
if ( it->second.perAtom )
it->second.repeat *= spc->findMolecules(it->first).front()->size();
return it->first;
}
}
return -1;
}
/**
* Returns pointer to a random group matching a molecule id
* in `mollist`
*/
template<class Tspace>
Group *Movebase<Tspace>::randomMol()
{
Group *gPtr = nullptr;
if ( !mollist.empty())
{
auto it = _slump().element(mollist.begin(), mollist.end());
auto g = spc->findMolecules(it->first); // vector of group pointers
if ( !g.empty())
gPtr = *_slump().element(g.begin(), g.end());
}
return gPtr;
}
template<class Tspace>
void Movebase<Tspace>::trialMove()
{
assert(change.empty() && "Change object is not empty!");
if ( cnt == 0 )
for ( auto i : spc->groupList())
i->setMassCenter(*spc);
cnt++;
_trialMove();
}
template<class Tspace>
void Movebase<Tspace>::acceptMove()
{
cnt_accepted++;
_acceptMove();
}
template<class Tspace>
void Movebase<Tspace>::rejectMove()
{
_rejectMove();
}
/** @return Energy change in units of kT */
template<class Tspace>
double Movebase<Tspace>::energyChange()
{
double du = _energyChange();
if ( std::isnan(du))
std::cerr << "Warning: energy change from move returns not-a-number (NaN)" << endl;
return du;
}
/**
* This function performs trial move and accept/reject using
* the Metropolis criteria.
* It carries out the following `n` times:
*
* - Perform a trial move with `_trialMove()`
* - Calulate the energy change, \f$\beta\Delta U\f$ with `_energyChange()`
* - Accept with probability \f$ \min(1,e^{-\beta\Delta U}) \f$
* - Call either `_acceptMove()` or `_rejectMove()`
*
* @note Do not override this function in derived classes.
* @param n Perform move `n` times (default=1)
*
* [More info](http://dx.doi.org/10.1063/1.1699114)
*/
template<class Tspace>
double Movebase<Tspace>::move( int n )
{
timer.start();
double utot = 0;
if ( !mollist.empty())
{
currentMolId = randomMolId();
n = mollist[currentMolId].repeat;
runfraction = mollist[currentMolId].prob;
}
if ( run())
{
bool acceptance = true;
while ( n-- > 0 )
{
trialMove();
pot->updateChange(change);
double du = energyChange();
acceptance = metropolis(du); // true or false?
if ( !acceptance )
rejectMove();
else
{
acceptMove();
if ( useAlternativeReturnEnergy )
du = alternateReturnEnergy;
dusum += du;
utot += du;
}
utot += pot->update(acceptance);
change.clear();
}
}
assert(spc->p == spc->trial && "Trial particle vector out of sync!");
timer.stop();
return utot;
}
/**
* @param du Energy change for MC move (kT)
* @return True if move should be accepted; false if not.
* @note
* One could put in `if (du>0)` before the first line, but
* certain MPI communications require the random number
* generator to be in sync, i.e. each rank must call
* `slump()` equal number of times, independent of
* dU.
*/
template<class Tspace>
bool Movebase<Tspace>::metropolis( const double &du ) const
{
if ( slump() > std::exp(-du)) // core of MC!
return false;
return true;
}
template<class Tspace>
bool Movebase<Tspace>::run()
{
if ( _slump()() < runfraction )
return true;
return false;
}
template<class Tspace>
void Movebase<Tspace>::test( UnitTest &t )
{
if ( runfraction < 1e-6 || cnt == 0 )
return;
t(textio::trim(title) + "_acceptance", double(cnt_accepted) / cnt * 100);
_test(t);
}
template<class Tspace>
void Movebase<Tspace>::_test( UnitTest & )
{
}
template<class Tspace>
double Movebase<Tspace>::getAcceptance() const
{
if ( cnt > 0 )
return double(cnt_accepted) / cnt;
return 0;
}
/**
* This will return a formatted multi-line information string about the move and
* will as a minimum contain:
*
* - Name of move
* - Runfraction
* - Number of times the move has been called
* - Acceptance
* - Total energy change
*
* Typically, additional information will be provided as well.
*
* @note Do not override in derived classes - use _info().
*/
template<class Tspace>
string Movebase<Tspace>::info()
{
using namespace textio;
assert(!title.empty() && "Markov Moves must have a title");
std::ostringstream o;
if ( runfraction < 1e-10 )
return o.str();
o << header("Markov Move: " + title);
if ( !cite.empty())
o << pad(SUB, w, "More information:") << cite << endl;
if ( cnt > 0 )
o << pad(SUB, w, "Number of trials") << cnt << endl
<< pad(SUB, w, "Relative time consumption") << timer.result() << endl
<< pad(SUB, w, "Acceptance") << getAcceptance() * 100 << percent << endl
<< pad(SUB, w, "Runfraction") << runfraction * 100 << percent << endl
<< pad(SUB, w, "Total energy change") << dusum << kT << endl;
o << _info();
return o.str();
}
/**
* @brief Generate new configurations by looping through XTC trajectory
*
* This move will load frames from a trajectory file and with this
* replace particle positions in the system. No energy is evaluated
* and energyChange will always return 0.
*
* If the trajectory is saved with molecules that extend beyond
* the box boundaries, the PBC boundary control should be set
* to true.
*
* Keyword | Description
* -------- | ---------------
* `file` | Trajectory file to load (.xtc)
* `trump` | Enforce (PBC) boundary control (default: false)
*
* Notes:
*
* - Geometry must be derived from `Geometry::Cuboid`.
* - Number of particle in Space must match that of the trajectory
* - Particles must not overlap with geometry boundaries
* - if the above is violated an exception is thrown
*
* @date January 2017
* @warning Untested
*/
template<class Tspace, class base=Movebase<Tspace>>
class TrajectoryMove : public base
{
FormatXTC xtc;
bool _continue;
int framecnt;
string file;
bool applyPBC; // true if PBC should be applied to loaded frames
void _acceptMove() override {};
void _rejectMove() override {};
string _info() override { return string(); };
double _energyChange() override { return 0; };
Tmjson _json() override
{
Tmjson js;
if ( base::cnt > 0 )
{
auto &j = js[base::title];
j = {
{ "file", file },
{ "boundary control", applyPBC },
{ "frames loaded", framecnt}
};
}
return js;
}
void _trialMove() override
{
if (_continue)
_continue = xtc.loadnextframe( *base::spc, true, applyPBC );
if (_continue)
framecnt++;
}
public:
TrajectoryMove( Energy::Energybase<Tspace> &e, Tspace &s, Tmjson &j )
: Movebase<Tspace>(e, s), xtc(1), _continue(true), framecnt(0)
{
base::title = "XTC Trajectory Move";
file = j.at("file");
applyPBC = j.value("trump", false);
if ( xtc.open(file) == false)
throw std::runtime_error(base::title + ": xtc file " + file + " cannot be loaded");
}
bool eof() { return _continue; } //!< True if all frames have been loaded
};
/**
* @brief Translation of atomic particles
*
* This Markov move can work in two modes:
* - Move a single particle in space set by setParticle()
* - Move single particles randomly selected in a Group set by setGroup().
*
* The move directions can be controlled with the dir vector - for instance if you wish
* to translate only in the `z` direction, set `dir.x()=dir.y()=0`.
*
* @date Lund, 2011
*/
template<class Tspace>
class AtomicTranslation : public Movebase<Tspace>
{
private:
typedef Movebase<Tspace> base;
typedef std::map<short, Average<double> > map_type;
bool run() override; //!< Runfraction test
Tmjson _json() override;
protected:
string _info() override;
void _acceptMove() override;
void _rejectMove() override;
double _energyChange() override;
void _trialMove() override;
using base::spc;
map_type accmap; //!< Single particle acceptance map
map_type sqrmap; //!< Single particle mean square displacement map
int iparticle; //!< Select single particle to move (-1 if none, default)
Group *igroup; //!< Group pointer in which particles are moved randomly (NULL if none, default)
double genericdp;//!< Generic atom displacement parameter - ignores individual dps
Average<unsigned long long int> gsize; //!< Average size of igroup;
public:
AtomicTranslation( Energy::Energybase<Tspace> &, Tspace &, Tmjson & );
void setGenericDisplacement( double ); //!< Set single displacement for all atoms
Point dir; //!< Translation directions (default: x=y=z=1)
};
/**
* @brief Constructor
*
* The json entry is read on a per-molecule basis, each with
* the following keywords,
*
* Value | Description
* :------------------- | :-------------------------------------------------------------
* `dir` | Move directions (default: "1 1 1" = xyz)
* `peratom` | Repeat move for each atom in molecule (default: false)
* `permol` | Repeat move for each molecule in system (default: false)
* `prob` | Probability of performing the move (default: 1)
*
* Example:
*
* {
* "salt" : { "dir":"1 1 0", "peratom":true }
* }
*
* Atomic displacement parameters are read from `Faunus::AtomData`.
*/
template<class Tspace>
AtomicTranslation<Tspace>::AtomicTranslation(
Energy::Energybase<Tspace> &e, Tspace &s, Tmjson &j ) : Movebase<Tspace>(e, s)
{
base::title = "Single Particle Translation";
iparticle = -1;
igroup = nullptr;
dir = {1, 1, 1};
genericdp = 0;
base::fillMolList(j);
}
/**
* The generic displacement parameter will be used only if the specific
* atomic dp is zero.
*/
template<class Tspace>
void AtomicTranslation<Tspace>::setGenericDisplacement( double dp )
{
genericdp = dp;
}
template<class Tspace>
bool AtomicTranslation<Tspace>::run()
{
if ( !this->mollist.empty() )
if ( spc->findMolecules(this->currentMolId).empty() )
return false;
if ( igroup != nullptr )
if ( igroup->empty())
return false;
return base::run();
}
template<class Tspace>
void AtomicTranslation<Tspace>::_trialMove()
{
if ( !this->mollist.empty())
{
auto gvec = spc->findMolecules(this->currentMolId);
assert(!gvec.empty());
igroup = *slump.element(gvec.begin(), gvec.end());
assert(!igroup->empty());
dir = this->mollist[this->currentMolId].dir;
}
if ( igroup != nullptr )
{
iparticle = igroup->random();
gsize += igroup->size();
}
if ( iparticle > -1 )
{
double dp = atom[spc->p.at(iparticle).id].dp;
if ( dp < 1e-6 )
dp = genericdp;
assert(iparticle < (int) spc->p.size()
&& "Trial particle out of range");
Point t = dir * dp;
t.x() *= slump() - 0.5;
t.y() *= slump() - 0.5;
t.z() *= slump() - 0.5;
spc->trial[iparticle].translate(spc->geo, t);
// make sure trial mass center is updated for molecular groups
// (certain energy functions may rely on up-to-date mass centra)
auto gi = spc->findGroup(iparticle);
assert(gi != nullptr);
assert((gi->cm - gi->cm_trial).squaredNorm() < 1e-6);
if ( gi->isMolecular())
gi->cm_trial = Geometry::massCenter(spc->geo, spc->trial, *gi);
#ifndef NDEBUG
// are untouched particles in group synched?
for ( auto j : *gi )
if ( j != iparticle )
assert((base::spc->p[j] - base::spc->trial[j]).squaredNorm() < 1e-6);
#endif
}
base::change.mvGroup[spc->findIndex(igroup)].push_back(iparticle);
}
template<class Tspace>
void AtomicTranslation<Tspace>::_acceptMove()
{
double r2 = spc->geo.sqdist(spc->p[iparticle], spc->trial[iparticle]);
sqrmap[spc->p[iparticle].id] += r2;
accmap[spc->p[iparticle].id] += 1;
spc->p[iparticle] = spc->trial[iparticle];
auto gi = spc->findGroup(iparticle);
assert(gi != nullptr);
if ( gi->isMolecular())
gi->cm = gi->cm_trial;
}
template<class Tspace>
void AtomicTranslation<Tspace>::_rejectMove()
{
spc->trial[iparticle] = spc->p[iparticle];
sqrmap[spc->p[iparticle].id] += 0;
accmap[spc->p[iparticle].id] += 0;
auto gi = spc->findGroup(iparticle);
assert(gi != nullptr);
if ( gi->isMolecular())
gi->cm_trial = gi->cm;
}
template<class Tspace>
double AtomicTranslation<Tspace>::_energyChange()
{
if ( iparticle > -1 )
{
assert(spc->geo.collision(spc->p[iparticle], spc->p[iparticle].radius) == false
&& "An untouched particle collides with simulation container.");
return Energy::energyChange(*spc, *base::pot, base::change);
}
return 0;
}
template<class Tspace>
string AtomicTranslation<Tspace>::_info()
{
using namespace textio;
std::ostringstream o;
if ( gsize.cnt > 0 )
o << pad(SUB, base::w, "Average moves/particle")
<< base::cnt / gsize.avg() << endl;
o << pad(SUB, base::w, "Displacement vector")
<< dir.transpose() << endl;
if ( genericdp > 1e-6 )
o << pad(SUB, base::w, "Generic displacement")
<< genericdp << _angstrom << endl;
if ( base::cnt > 0 )
{
char l = 12;
o << endl
<< indent(SUB) << "Individual particle movement:" << endl << endl
<< indent(SUBSUB) << std::left << string(7, ' ')
<< setw(l - 6) << "dp"
<< setw(l + 1) << "Acc. " + percent
<< setw(l) << "Nmoves"
<< setw(l + 7) << bracket("r" + squared) + "/" + angstrom + squared
<< rootof + bracket("r" + squared) + "/" + angstrom << endl;
for ( auto m : sqrmap )
{
auto id = m.first;
o << indent(SUBSUB) << std::left << setw(7) << atom[id].name
<< setw(l - 6) << ((atom[id].dp < 1e-6) ? genericdp : atom[id].dp);
o.precision(3);
o << setw(l) << accmap[id].avg() * 100
<< setw(l) << accmap[id].cnt
<< setw(l) << sqrmap[id].avg()
<< setw(l) << sqrt(sqrmap[id].avg()) << endl;
}
}
return o.str();
}
/** @brief Create json object with move details */
template<class Tspace>
Tmjson AtomicTranslation<Tspace>::_json()
{
Tmjson js;
if ( base::cnt > 0 )
{
auto &j = js[base::title];
j = {
{"moves/particle", base::cnt / gsize.avg()},
{"dir", vector<double>( dir ) },
{"genericdp", genericdp}
};
for ( auto m : sqrmap )
{ // loop over particle id
int id = m.first;
double dp = (atom[id].dp < 1e-6) ? genericdp : atom[id].dp;
j["atoms"][atom[id].name] = {
{"dp", dp},
{"acceptance", accmap[id].avg() * 100},
{"mean displacement", sqrt(sqrmap[id].avg())}
};
}
}
return js;
}
/**
* @brief Rotate single particles
*
* This move works in the same way as AtomicTranslation but does
* rotations of non-isotropic particles instead of translation. This move
* has no effect on isotropic particles such as Faunus::PointParticle.
*/
template<class Tspace>
class AtomicRotation : public AtomicTranslation<Tspace>
{
protected:
typedef AtomicTranslation<Tspace> base;
using base::spc;
using base::iparticle;
using base::igroup;
using base::w;
using base::gsize;
using base::genericdp;
using base::accmap;
using base::sqrmap;
Geometry::QuaternionRotate rot;
string _info();
void _trialMove();
void _acceptMove();
void _rejectMove();
double dprot; //!< Temporary storage for current angle
public:
AtomicRotation( Energy::Energybase<Tspace> &, Tspace &, Tmjson & );
};
template<class Tspace>
AtomicRotation<Tspace>::AtomicRotation(
Energy::Energybase<Tspace> &e, Tspace &s, Tmjson &j ) : base(e, s, j)
{
base::title = "Single Particle Rotation";