SSAGES  0.9.3
Software Suite for Advanced General Ensemble Simulations
Public Member Functions | Static Public Member Functions | Private Member Functions | Private Attributes | List of all members
SSAGES::ABF Class Reference

Adaptive Biasing Force Algorithm. More...

#include <ABF.h>

Inheritance diagram for SSAGES::ABF:
Inheritance graph
[legend]

Public Member Functions

 ABF (const MPI_Comm &world, const MPI_Comm &comm, Grid< int > *N, Grid< int > *Nworld, std::vector< Grid< double > * > F, std::vector< Grid< double > * > Fworld, std::vector< std::vector< double >> restraint, std::vector< bool > isperiodic, std::vector< std::vector< double >> periodicboundaries, double min, bool massweigh, std::string filename, std::string Nworld_filename, std::string Fworld_filename, const std::vector< std::vector< double >> &histdetails, int FBackupInterv, double unitconv, double timestep, unsigned int frequency)
 Constructor. More...
 
void PreSimulation (Snapshot *snapshot, const class CVManager &cvmanager) override
 Method call prior to simulation initiation. More...
 
void PostIntegration (Snapshot *snapshot, const class CVManager &cvmanager) override
 Method call post integration. More...
 
void PostSimulation (Snapshot *snapshot, const class CVManager &cvmanager) override
 Method call prior to simulation initiation. More...
 
void SetIteration (const int iter)
 Set iteration of the method. More...
 
 ~ABF ()
 Destructor.
 
- Public Member Functions inherited from SSAGES::Method
 Method (unsigned int frequency, const MPI_Comm &world, const MPI_Comm &comm)
 Constructor. More...
 
void SetCVMask (const std::vector< unsigned int > &mask)
 Sets the collective variable mask. More...
 
virtual ~Method ()
 Destructor.
 
- Public Member Functions inherited from SSAGES::EventListener
 EventListener (unsigned int frequency)
 Constructor. More...
 
unsigned int GetFrequency () const
 Get frequency of event listener. More...
 
virtual ~EventListener ()
 Destructor.
 

Static Public Member Functions

static ABFBuild (const Json::Value &json, const MPI_Comm &world, const MPI_Comm &comm, const std::string &path)
 Build a derived method from JSON node. More...
 
- Static Public Member Functions inherited from SSAGES::Method
static MethodBuildMethod (const Json::Value &json, const MPI_Comm &world, const MPI_Comm &comm, const std::string &path)
 Build a derived method from JSON node. More...
 
- Static Public Member Functions inherited from SSAGES::EventListener
static unsigned int GetWalkerID (const MPI_Comm &world, const MPI_Comm &comm)
 Get walker ID number of specified communicator. More...
 
static unsigned int GetNumWalkers (const MPI_Comm &world, const MPI_Comm &comm)
 Get total number of walkers in the simulation. More...
 
static bool IsMasterRank (const MPI_Comm &comm)
 Check if current processor is master. More...
 

Private Member Functions

void CalcBiasForce (const Snapshot *snapshot, const CVList &cvs, const std::vector< double > &cvVals)
 Computes the bias force. More...
 
void WriteData ()
 Writes out data to file.
 
bool boundsCheck (const std::vector< double > &CVs)
 Checks whether the local walker is within CV bounds. More...
 

Private Attributes

Grid< int > * N_
 To store number of local hits at a given CV bin. More...
 
Grid< int > * Nworld_
 To store number of global hits at a given CV bin. More...
 
std::vector< Grid< double > * > F_
 To store running total of the local walker. More...
 
std::vector< Grid< double > * > Fworld_
 Will hold the global total, synced across walkers at every time step. More...
 
std::vector< std::vector< double > > restraint_
 Information for a harmonic restraint to keep CV in the region of interest. More...
 
std::vector< bool > isperiodic_
 For each CV, holds whether that CV has periodic boundaries or not.
 
std::vector< std::vector< double > > periodicboundaries_
 Holds periodic boundaries of CVs. More...
 
int min_
 
Eigen::VectorXd wdotp1_
 To hold last iteration wdotp value for numerical derivative.
 
Eigen::VectorXd wdotp2_
 To hold second to last iteration wdotp value for numerical derivative.
 
Eigen::VectorXd Fold_
 To hold last iterations F_ value for removing bias.
 
bool massweigh_
 Mass weighing of bias enabled/disabled.
 
std::vector< Vector3biases_
 Biases applied to atoms each timestep.

 
unsigned int dim_
 Number of CVs in system.
 
std::ofstream worldout_
 Output stream for F/N world data.
 
std::string filename_
 
std::string Nworld_filename_
 Nworld print out filename, for restarts.
 
std::string Fworld_filename_
 Fworld print out filename, for restarts.
 
std::vector< std::vector< double > > histdetails_
 Histogram details. More...
 
int FBackupInterv_
 Integer to hold F estimate backup information. More...
 
double unitconv_
 Unit Conversion Constant from W dot P to Force. More...
 
double timestep_
 Timestep of integration.
 
unsigned int iteration_
 Iteration counter.
 
Eigen::VectorXd mass_
 Mass vector. Empty unless required.
 

Additional Inherited Members

- Protected Attributes inherited from SSAGES::Method
mxx::comm world_
 Global MPI communicator.
 
mxx::comm comm_
 Local MPI communicator.
 
std::vector< unsigned int > cvmask_
 Mask which identifies which CVs to act on.
 

Detailed Description

Adaptive Biasing Force Algorithm.

Implementation of the Adaptive Biasing Force algorithm based on [2]

Definition at line 40 of file ABF.h.

Constructor & Destructor Documentation

◆ ABF()

SSAGES::ABF::ABF ( const MPI_Comm &  world,
const MPI_Comm &  comm,
Grid< int > *  N,
Grid< int > *  Nworld,
std::vector< Grid< double > * >  F,
std::vector< Grid< double > * >  Fworld,
std::vector< std::vector< double >>  restraint,
std::vector< bool >  isperiodic,
std::vector< std::vector< double >>  periodicboundaries,
double  min,
bool  massweigh,
std::string  filename,
std::string  Nworld_filename,
std::string  Fworld_filename,
const std::vector< std::vector< double >> &  histdetails,
int  FBackupInterv,
double  unitconv,
double  timestep,
unsigned int  frequency 
)
inline

Constructor.

Parameters
worldMPI global communicator.
commMPI local communicator.
NLocal CV histogram.
NworldGlobal CV histogram.
FVector of grids holding local raw generalized force totals per bin per CV.
FworldVector of grids holding global raw generalized force totals per bin per CV.
restraintMinimum, maximum and spring constant for CV restraints.
isperiodicVector of bools that holds whether each CV is periodic or not.
periodicboundariesPeriodic boundaries of each CV.
minMinimum number of hist in a histogram bin before biasing is applied.
massweighTurn mass weighing on/off.
filenameName for output file.
Nworld_filenameName to read/write CV histogram.
Fworld_filenameName to read/write raw generalized force histograms.
histdetailsMinimum, maximum and number of bins for each CV.
FBackupIntervSet how often the adaptive force histograms are backed up.
unitconvUnit conversion from d(momentum)/d(time) to force.
timestepSimulation time step.
frequencyFrequency with which this method is invoked.

Constructs an instance of Adaptive Biasing Force method.

Note
The restraints should be outside of the range defined in histdetails_ by at least one bin size on each side.

Definition at line 213 of file ABF.h.

231  :
232  Method(frequency, world, comm), N_(N), Nworld_(Nworld), F_(F), Fworld_(Fworld), restraint_(restraint), isperiodic_(isperiodic), periodicboundaries_(periodicboundaries),
233  min_(min), wdotp1_(), wdotp2_(), Fold_(), massweigh_(massweigh),
234  biases_(), dim_(0), filename_(filename), Nworld_filename_(Nworld_filename), Fworld_filename_(Fworld_filename),
235  histdetails_(histdetails),
236  FBackupInterv_(FBackupInterv), unitconv_(unitconv), timestep_(timestep),
237  iteration_(0)
238  {
239  }
double unitconv_
Unit Conversion Constant from W dot P to Force.
Definition: ABF.h:155
Eigen::VectorXd Fold_
To hold last iterations F_ value for removing bias.
Definition: ABF.h:107
std::vector< std::vector< double > > histdetails_
Histogram details.
Definition: ABF.h:140
Eigen::VectorXd wdotp2_
To hold second to last iteration wdotp value for numerical derivative.
Definition: ABF.h:104
double timestep_
Timestep of integration.
Definition: ABF.h:169
Grid< int > * N_
To store number of local hits at a given CV bin.
Definition: ABF.h:48
std::vector< Grid< double > * > F_
To store running total of the local walker.
Definition: ABF.h:62
std::string Nworld_filename_
Nworld print out filename, for restarts.
Definition: ABF.h:126
Eigen::VectorXd wdotp1_
To hold last iteration wdotp value for numerical derivative.
Definition: ABF.h:101
std::vector< Grid< double > * > Fworld_
Will hold the global total, synced across walkers at every time step.
Definition: ABF.h:70
std::vector< std::vector< double > > restraint_
Information for a harmonic restraint to keep CV in the region of interest.
Definition: ABF.h:81
std::vector< std::vector< double > > periodicboundaries_
Holds periodic boundaries of CVs.
Definition: ABF.h:94
std::string filename_
Definition: ABF.h:123
int min_
Definition: ABF.h:98
unsigned int dim_
Number of CVs in system.
Definition: ABF.h:116
unsigned int iteration_
Iteration counter.
Definition: ABF.h:172
std::vector< bool > isperiodic_
For each CV, holds whether that CV has periodic boundaries or not.
Definition: ABF.h:84
bool massweigh_
Mass weighing of bias enabled/disabled.
Definition: ABF.h:110
int FBackupInterv_
Integer to hold F estimate backup information.
Definition: ABF.h:146
Grid< int > * Nworld_
To store number of global hits at a given CV bin.
Definition: ABF.h:55
std::vector< Vector3 > biases_
Biases applied to atoms each timestep.
Definition: ABF.h:113
std::string Fworld_filename_
Fworld print out filename, for restarts.
Definition: ABF.h:129
Method(unsigned int frequency, const MPI_Comm &world, const MPI_Comm &comm)
Constructor.
Definition: Method.h:61

Member Function Documentation

◆ boundsCheck()

bool SSAGES::ABF::boundsCheck ( const std::vector< double > &  CVs)
private

Checks whether the local walker is within CV bounds.

Parameters
CVsCurrent values of CVs.
Returns
Whether the walker is in bounds or not.

Definition at line 284 of file ABF.cpp.

285  {
286  for(size_t i = 0; i < dim_ ; ++i)
287  {
288  if((CVs[i] < N_->GetLower(i)) || (CVs[i] > N_->GetUpper(i)))
289  {
290  return false;
291  }
292  }
293  return true;
294  }
const std::vector< double > GetLower() const
Return the lower edges of the Grid.
Definition: GridBase.h:231
const std::vector< double > GetUpper() const
Return the upper edges of the Grid.
Definition: GridBase.h:262

◆ Build()

ABF * SSAGES::ABF::Build ( const Json::Value &  json,
const MPI_Comm &  world,
const MPI_Comm &  comm,
const std::string &  path 
)
static

Build a derived method from JSON node.

Parameters
jsonJSON Value containing all input information.
worldMPI global communicator.
commMPI local communicator.
pathPath for JSON path specification.
Returns
Pointer to the Method built. nullptr if an unknown error occurred.

This function builds a registered method from a JSON node. The difference between this function and "Build" is that this automatically determines the appropriate derived type based on the JSON node information.

Note
Object lifetime is the caller's responsibility.

Definition at line 297 of file ABF.cpp.

301  {
302  ObjectRequirement validator;
303  Value schema;
304  CharReaderBuilder rbuilder;
305  CharReader* reader = rbuilder.newCharReader();
306 
307  reader->parse(JsonSchema::ABFMethod.c_str(),
308  JsonSchema::ABFMethod.c_str() + JsonSchema::ABFMethod.size(),
309  &schema, nullptr);
310  validator.Parse(schema, path);
311 
312  // Validate inputs.
313  validator.Validate(json, path);
314  if(validator.HasErrors())
315  throw BuildException(validator.GetErrors());
316 
317  //bool multiwalkerinput = false;
318 
319  // Obtain lower bound for each CV.
320  std::vector<double> minsCV;
321  for(auto& mins : json["CV_lower_bounds"])
322  if(mins.isArray())
323  {
324  throw BuildException({"Separate inputs for multi-walker not fully implemented. Please use global entries for CV ranges"});
325  //multiwalkerinput = true;
326  //for(auto& bound : mins)
327  // minsCV.push_back(bound.asDouble());
328  }
329  else
330  minsCV.push_back(mins.asDouble());
331 
332  // Obtain upper bound for each CV.
333  std::vector<double> maxsCV;
334  for(auto& maxs : json["CV_upper_bounds"])
335  /*if(maxs.isArray())
336  {
337  for(auto& bound : maxs)
338  maxsCV.push_back(bound.asDouble());
339  }*/
340  //else
341  maxsCV.push_back(maxs.asDouble());
342 
343  // Obtain number of bins for each CV dimension.
344  std::vector<int> binsCV;
345  for(auto& bins : json["CV_bins"])
346  binsCV.push_back(bins.asInt());
347 
348  // Obtain lower bounds for restraints for each CV.
349  std::vector<double> minsrestCV;
350  for(auto& mins : json["CV_restraint_minimums"])
351  /*if(mins.isArray())
352  {
353  for(auto& bound : mins)
354  minsrestCV.push_back(bound.asDouble());
355  }*/
356  //else
357  minsrestCV.push_back(mins.asDouble());
358 
359  // Obtain upper bounds for restraints for each CV.
360  std::vector<double> maxsrestCV;
361  for(auto& maxs : json["CV_restraint_maximums"])
362  /*if(maxs.isArray())
363  {
364  for(auto& bound : maxs)
365  maxsrestCV.push_back(bound.asDouble());
366  }*/
367  //else
368  maxsrestCV.push_back(maxs.asDouble());
369 
370  // Obtain harmonic spring constant for restraints for each CV.
371  std::vector<double> springkrestCV;
372  for(auto& springkrest : json["CV_restraint_spring_constants"])
373  {
374  if(springkrest.asDouble() < 0)
375  {
376  throw BuildException({"Restraint spring constants must be non-negative."});
377  }
378  springkrestCV.push_back(springkrest.asDouble());
379  }
380 
381  // Obtain periodicity information for restraints for each CV for the purpose of correctly applying restraints through periodic boundaries.
382  std::vector<bool> isperiodic;
383  for(auto& isperCV : json["CV_isperiodic"])
384  isperiodic.push_back(isperCV.asBool());
385 
386  // Obtain lower periodic boundary for each CV.
387  std::vector<double> minperboundaryCV;
388  for(auto& minsperCV : json["CV_periodic_boundary_lower_bounds"])
389  minperboundaryCV.push_back(minsperCV.asDouble());
390 
391  // Obtain upper periodic boundary for each CV.
392  std::vector<double> maxperboundaryCV;
393  for(auto& maxsperCV : json["CV_periodic_boundary_upper_bounds"])
394  maxperboundaryCV.push_back(maxsperCV.asDouble());
395 
396  // Verify inputs are all correct lengths.
397  if(!(( minsCV.size() == maxsCV.size() &&
398  maxsCV.size() == minsrestCV.size() &&
399  minsrestCV.size() == maxsrestCV.size()) &&
400  (binsCV.size() == springkrestCV.size() &&
401  springkrestCV.size() == isperiodic.size())))
402  throw BuildException({"CV lower bounds, upper bounds, restrain minimums, restrains maximums must match in size. Bins, spring constants and periodicity info must match in size."});
403 
404  // Verify that all periodicity information is provided if CVs are periodic.
405  bool anyperiodic=false;
406  for(size_t i = 0; i<isperiodic.size(); ++i)
407  if(isperiodic[i])
408  {
409  anyperiodic = true;
410  if(!(isperiodic.size() == minperboundaryCV.size() &&
411  minperboundaryCV.size() == maxperboundaryCV.size()))
412  throw BuildException({"If any CV is defined as periodic, please define the full upper and lower bound vectors. They should both have the same number of entries as CV lower bounds, upper bounds... Entries corresponding to non-periodic CVs will not be used."});
413  }
414 
415  size_t dim = binsCV.size();
416 
417  // Read in JSON info.
418  auto FBackupInterv = json.get("output_frequency", 1000).asInt();
419  auto unitconv = json.get("unit_conversion", 0).asDouble();
420  auto timestep = json.get("timestep", 2).asDouble();
421  auto min = json.get("minimum_count", 200).asDouble();
422  auto massweigh = json.get("mass_weighing",false).asBool();
423 
424  std::vector<std::vector<double>> histdetails;
425  std::vector<std::vector<double>> restraint;
426  std::vector<std::vector<double>> periodicboundaries;
427  std::vector<double> temp1(3);
428  std::vector<double> temp2(3);
429  std::vector<double> temp3(2);
430 
431  auto freq = json.get("frequency", 1).asInt();
432  auto filename = json.get("output_file", "F_out").asString();
433  auto Nworld_filename = json.get("Nworld_output_file", "Nworld").asString();
434  auto Fworld_filename = json.get("Fworld_output_file", "Fworld_cv").asString();
435 
436  // Generate the grids based on JSON.
437  Grid<int> *N;
438  Grid<int> *Nworld;
439  std::vector<Grid<double>*> F(dim);
440  std::vector<Grid<double>*> Fworld(dim);
441 
442  //unsigned int wid = GetWalkerID(world, comm);
443 
444  // This feature is disabled for now.
445 
446  /*if(multiwalkerinput)
447  {
448  for(size_t i=0; i<dim; ++i)
449  {
450  temp1 = {minsCV[i+wid*dim], maxsCV[i+wid*dim], binsCV[i]};
451  temp2 = {minsrestCV[i+wid*dim], maxsrestCV[i+wid*dim], springkrestCV[i]};
452  histdetails.push_back(temp1);
453  restraint.push_back(temp2);
454  if(anyperiodic)
455  {
456  temp3 = {minperboundaryCV[i], maxperboundaryCV[i]};
457  periodicboundaries.push_back(temp3);
458  }
459  }
460  for(size_t i=0; i<dim; ++i)
461  {
462  minsCVperwalker[i] = histdetails[i][0];
463  maxsCVperwalker[i] = histdetails[i][1];
464  }
465 
466  N= new Grid<int>(binsCV, minsCVperwalker, maxsCVperwalker, isperiodic);
467  Nworld= new Grid<int>(binsCV, minsCVperwalker, maxsCVperwalker, isperiodic);
468 
469  for(auto& grid : F)
470  {
471  grid= new Grid<double>(binsCV, minsCVperwalker, maxsCVperwalker, isperiodic);
472  }
473  for(auto& grid : Fworld)
474  {
475  grid= new Grid<double>(binsCV, minsCVperwalker, maxsCVperwalker, isperiodic);
476  }
477 
478  }
479  */
480  //else
481  //{
482 
483  // Appropriately size the grids.
484 
485  N = new Grid<int>(binsCV, minsCV, maxsCV, isperiodic);
486  Nworld = new Grid<int>(binsCV, minsCV, maxsCV, isperiodic);
487 
488  for(auto& grid : F)
489  {
490  grid = new Grid<double>(binsCV, minsCV, maxsCV, isperiodic);
491  }
492  for(auto& grid : Fworld)
493  {
494  grid = new Grid<double>(binsCV, minsCV, maxsCV, isperiodic);
495  }
496 
497  for(size_t i = 0; i < dim; ++i)
498  {
499  temp1 = {minsCV[i], maxsCV[i], double(binsCV[i])};
500  temp2 = {minsrestCV[i], maxsrestCV[i], springkrestCV[i]};
501  histdetails.push_back(temp1);
502  restraint.push_back(temp2);
503  if(anyperiodic)
504  {
505  temp3 = {minperboundaryCV[i], maxperboundaryCV[i]};
506  periodicboundaries.push_back(temp3);
507  }
508  }
509  //}
510 
511  // Check if a restart is requested.
512  bool restart = json.get("restart",false).asBool();
513 
514  // Either load previous grid, or back it up.
515  if(IsMasterRank(world))
516  {
517  if(restart)
518  {
519  std::cout << "Attempting to load data from a previous run of ABF..." << std::endl;
520  N->LoadFromFile(Nworld_filename);
521  for(size_t i = 0; i < dim; ++i)
522  {
523  F[i]->LoadFromFile(Fworld_filename+std::to_string(i));
524  }
525  }
526  else
527  {
528  std::ifstream Nworldbackupsource(Nworld_filename, std::ios::binary);
529  if(Nworldbackupsource)
530  {
531  std::cout << "Backing up previous copy of Nworld." << std::endl;
532  std::ofstream Nworldbackuptarget(Nworld_filename+"_backup", std::ios::binary);
533  Nworldbackuptarget << Nworldbackupsource.rdbuf();
534  }
535  for(size_t i = 0; i < dim; ++i)
536  {
537  std::ifstream Fworldbackupsource(Fworld_filename+std::to_string(i), std::ios::binary);
538  if(Fworldbackupsource)
539  {
540  std::cout << "Backing up previous copy of Fworld_cv"+std::to_string(i)+"." << std::endl;
541  std::ofstream Fworldbackuptarget(Fworld_filename+std::to_string(i)+"_backup", std::ios::binary);
542  Fworldbackuptarget << Fworldbackupsource.rdbuf();
543  }
544  }
545  }
546  }
547 
548  auto* m = new ABF(world, comm, N, Nworld, F, Fworld, restraint, isperiodic, periodicboundaries, min, massweigh, filename, Nworld_filename, Fworld_filename, histdetails, FBackupInterv, unitconv, timestep, freq);
549 
550  if(json.isMember("iteration"))
551  m->SetIteration(json.get("iteration",0).asInt());
552 
553  return m;
554 
555  }
Requirements on an object.
virtual void Parse(Value json, const std::string &path) override
Parse JSON value to generate Requirement(s).
virtual void Validate(const Value &json, const std::string &path) override
Validate JSON value.
std::vector< std::string > GetErrors()
Get list of error messages.
Definition: Requirement.h:92
bool HasErrors()
Check if errors have occured.
Definition: Requirement.h:86
ABF(const MPI_Comm &world, const MPI_Comm &comm, Grid< int > *N, Grid< int > *Nworld, std::vector< Grid< double > * > F, std::vector< Grid< double > * > Fworld, std::vector< std::vector< double >> restraint, std::vector< bool > isperiodic, std::vector< std::vector< double >> periodicboundaries, double min, bool massweigh, std::string filename, std::string Nworld_filename, std::string Fworld_filename, const std::vector< std::vector< double >> &histdetails, int FBackupInterv, double unitconv, double timestep, unsigned int frequency)
Constructor.
Definition: ABF.h:213
static bool IsMasterRank(const MPI_Comm &comm)
Check if current processor is master.

References Json::Requirement::GetErrors(), Json::Requirement::HasErrors(), SSAGES::Grid< T >::LoadFromFile(), Json::ObjectRequirement::Parse(), and Json::ObjectRequirement::Validate().

Here is the call graph for this function:

◆ CalcBiasForce()

void SSAGES::ABF::CalcBiasForce ( const Snapshot snapshot,
const CVList cvs,
const std::vector< double > &  cvVals 
)
private

Computes the bias force.

Parameters
snapshotCurrent simulation snapshot.
cvsDetails of CVs.
cvValsCurrent values of CVs.

Definition at line 176 of file ABF.cpp.

177  {
178  // Reset the bias.
179  biases_.resize(snapshot->GetNumAtoms(), Vector3{0,0,0});
180  for(auto& b : biases_)
181  b.setZero();
182 
183  // Compute bias if within bounds.
184  if(boundsCheck(cvVals))
185  {
186  for(size_t i = 0; i < dim_; ++i)
187  {
188  auto& grad = cvs[i]->GetGradient();
189  for(size_t j = 0; j < biases_.size(); ++j)
190  biases_[j] -= (Fworld_[i]->at(cvVals))*grad[j]/std::max(min_,Nworld_->at(cvVals));
191  }
192  }
193  // Otherwise, apply harmonic restraint if enabled.
194  else
195  {
196  for(size_t i = 0; i < dim_; ++i)
197  {
198  double cvVal = cvs[i]->GetValue();
199  auto k = 0.;
200  auto x0 = 0.;
201 
202  if(isperiodic_[i])
203  {
204  double periodsize = periodicboundaries_[i][1]-periodicboundaries_[i][0];
205  double cvRestrMidpoint = (restraint_[i][1]+restraint_[i][0])/2;
206  while((cvVal-cvRestrMidpoint) > periodsize/2)
207  cvVal -= periodsize;
208  while((cvVal-cvRestrMidpoint) < -periodsize/2)
209  cvVal += periodsize;
210  }
211 
212  if(cvVal < restraint_[i][0])
213  {
214  k = restraint_[i][2];
215  x0 = restraint_[i][0];
216  }
217  else if (cvVal > restraint_[i][1])
218  {
219  k = restraint_[i][2];
220  x0 = restraint_[i][1];
221  }
222 
223  auto& grad = cvs[i]->GetGradient();
224  for(size_t j = 0; j < biases_.size(); ++j)
225  biases_[j] -= (cvVal - x0)*k*grad[j];
226  }
227  }
228  }
bool boundsCheck(const std::vector< double > &CVs)
Checks whether the local walker is within CV bounds.
Definition: ABF.cpp:284
const T & at(const std::vector< int > &indices) const
Access Grid element read-only.
Definition: GridBase.h:546
Eigen::Vector3d Vector3
Three-dimensional vector.
Definition: types.h:33

References SSAGES::Snapshot::GetNumAtoms().

Here is the call graph for this function:

◆ PostIntegration()

void SSAGES::ABF::PostIntegration ( Snapshot snapshot,
const class CVManager cvmanager 
)
overridevirtual

Method call post integration.

Post-integration hook.

Parameters
snapshotPointer to the simulation snapshot.
cvmanagerCollective variable manager.

This function will be called after each integration step.

Post-integration hook is where processes carried out every timestep happen. First, information from current snapshot is retrieved and stored in variables as necessary. Then, coordinates in CV space are determined. Then, for each CV, the time derivative of w.p is calculated. Then, information is printed out if its enabled. Finally, bias is applied from current estimate of generalized force.

Coord holds where we are in CV space in current timestep.

Eigen::MatrixXd to hold the CV gradient.

std::vector<double> to hold CV values to address grid.

Implements SSAGES::Method.

Definition at line 72 of file ABF.cpp.

73  {
74 
75  ++iteration_;
76 
77  // Gather information.
78  auto cvs = cvmanager.GetCVs(cvmask_);
79  auto& vels = snapshot->GetVelocities();
80  auto& mass = snapshot->GetMasses();
81  auto& forces = snapshot->GetForces();
82  auto n = snapshot->GetNumAtoms();
83 
84 
86  //int coord = histCoords(cvs);
87 
89  Eigen::MatrixXd J(dim_, 3*n);
90 
92  std::vector<double> cvVals(dim_);
93 
94  // Fill J and CV. Each column represents grad(CV) with flattened Cartesian elements.
95  for(size_t i = 0; i < dim_; ++i)
96  {
97  auto& grad = cvs[i]->GetGradient();
98  for(size_t j = 0; j < n; ++j)
99  J.block<1, 3>(i,3*j) = grad[j];
100  cvVals[i] = cvs[i]->GetValue();
101  }
102 
103  //* Calculate W using Darve's approach (http://mc.stanford.edu/cgi-bin/images/0/06/Darve_2008.pdf).
104  Eigen::MatrixXd Jmass = J.transpose();
105  if(massweigh_)
106  {
107  for(size_t i = 0; i < forces.size(); ++i)
108  Jmass.block(3*i, 0, 3, dim_) = Jmass.block(3*i, 0, 3, dim_)/mass[i];
109  }
110 
111  Eigen::MatrixXd Minv = J*Jmass;
112  MPI_Allreduce(MPI_IN_PLACE, Minv.data(), Minv.size(), MPI_DOUBLE, MPI_SUM, comm_);
113  Eigen::MatrixXd Wt = Minv.inverse()*Jmass.transpose();
114  // Fill momenta.
115  Eigen::VectorXd momenta(3*vels.size());
116  for(size_t i = 0; i < vels.size(); ++i)
117  momenta.segment<3>(3*i) = mass[i]*vels[i];
118 
119  // Compute dot(w,p)
120  Eigen::VectorXd wdotp = Wt*momenta;
121 
122 
123  // Reduce dot product across processors.
124  MPI_Allreduce(MPI_IN_PLACE, wdotp.data(), wdotp.size(), MPI_DOUBLE, MPI_SUM, comm_);
125 
126 
127  // Compute d(wdotp)/dt second order backwards finite difference.
128  // Adding old force removes bias.
129  Eigen::VectorXd dwdotpdt = unitconv_*(1.5*wdotp - 2.0*wdotp1_ + 0.5*wdotp2_)/timestep_ + Fold_;
130 
131  // If we are in bounds, sum force into running total.
132  if(boundsCheck(cvVals) && IsMasterRank(comm_))
133  {
134  for(size_t i = 0; i < dim_; ++i)
135  F_[i]->at(cvVals) += dwdotpdt[i];
136  N_->at(cvVals)++;
137  }
138 
139  // Reduce data across processors.
140  for(size_t i = 0; i < dim_; ++i)
141  MPI_Allreduce(F_[i]->data(), Fworld_[i]->data(), (F_[i]->size()), MPI_DOUBLE, MPI_SUM, world_);
142  MPI_Allreduce(N_->data(), Nworld_->data(), N_->size(), MPI_INT, MPI_SUM, world_);
143 
144  // If we are in bounds, store the old summed force.
145  if(boundsCheck(cvVals))
146  {
147  for(size_t i=0; i < dim_; ++i)
148  Fold_[i] = Fworld_[i]->at(cvVals)/std::max(min_, Nworld_->at(cvVals));
149  }
150 
151  // Update finite difference time derivatives.
152  wdotp2_ = wdotp1_;
153  wdotp1_ = wdotp;
154 
155  // Write out data to file.
156  if(iteration_ % FBackupInterv_ == 0){
157  WriteData();
158  }
159 
160  // Calculate the bias from averaged F at current CV coordinates.
161  // Or apply harmonic restraints to return CVs back in bounds.
162  CalcBiasForce(snapshot, cvs, cvVals);
163 
164  // Update the forces in snapshot by adding in the force bias from each
165  // CV to each atom based on the gradient of the CV.
166  for (size_t j = 0; j < forces.size(); ++j)
167  forces[j] += biases_[j];
168  }
void CalcBiasForce(const Snapshot *snapshot, const CVList &cvs, const std::vector< double > &cvVals)
Computes the bias force.
Definition: ABF.cpp:176
void WriteData()
Writes out data to file.
Definition: ABF.cpp:232
size_t size() const
Get the size of the internal storage vector.
Definition: GridBase.h:326
T * data()
Get pointer to the internal data storage vector.
Definition: GridBase.h:338
mxx::comm comm_
Local MPI communicator.
Definition: Method.h:47
std::vector< unsigned int > cvmask_
Mask which identifies which CVs to act on.
Definition: Method.h:50
mxx::comm world_
Global MPI communicator.
Definition: Method.h:46

References SSAGES::CVManager::GetCVs(), SSAGES::Snapshot::GetForces(), SSAGES::Snapshot::GetMasses(), SSAGES::Snapshot::GetNumAtoms(), and SSAGES::Snapshot::GetVelocities().

Here is the call graph for this function:

◆ PostSimulation()

void SSAGES::ABF::PostSimulation ( Snapshot snapshot,
const class CVManager cvmanager 
)
overridevirtual

Method call prior to simulation initiation.

Parameters
snapshotPointer to the simulation snapshot.
cvmanagerCollective variable manager.

This function will be called before the simulation is started.

Implements SSAGES::Method.

Definition at line 171 of file ABF.cpp.

172  {
173  WriteData();
174  }

◆ PreSimulation()

void SSAGES::ABF::PreSimulation ( Snapshot snapshot,
const class CVManager cvmanager 
)
overridevirtual

Method call prior to simulation initiation.

Parameters
snapshotPointer to the simulation snapshot.
cvmanagerCollective variable manager.

This function will be called before the simulation is started.

Implements SSAGES::Method.

Definition at line 39 of file ABF.cpp.

40  {
41  // Open/close outfile to create it fresh.
42  if(IsMasterRank(world_))
43  {
44  worldout_.open(filename_);
45  worldout_.close();
46  }
47 
48  // Convenience. Number of CVs.
49  auto cvs = cvmanager.GetCVs(cvmask_);
50  dim_ = cvs.size();
51 
52  // Size and initialize Fold_
53  Fold_.setZero(dim_);
54 
55  // Initialize biases.
56  biases_.resize(snapshot->GetPositions().size(), Vector3{0, 0, 0});
57 
58  // Initialize w \dot p's for finite difference.
59  wdotp1_.setZero(dim_);
60  wdotp2_.setZero(dim_);
61  }
std::ofstream worldout_
Output stream for F/N world data.
Definition: ABF.h:119

References SSAGES::CVManager::GetCVs(), and SSAGES::Snapshot::GetPositions().

Here is the call graph for this function:

◆ SetIteration()

void SSAGES::ABF::SetIteration ( const int  iter)
inline

Set iteration of the method.

Parameters
iterNew value for the iteration counter.

Definition at line 254 of file ABF.h.

255  {
256  iteration_ = iter;
257  }

References iteration_.

Member Data Documentation

◆ F_

std::vector<Grid<double>*> SSAGES::ABF::F_
private

To store running total of the local walker.

This is a grid that holds dF/dCVx where x is one of the CVs. For N CVs, there will be N grids, and thus this vector will be N long.

Definition at line 62 of file ABF.h.

◆ FBackupInterv_

int SSAGES::ABF::FBackupInterv_
private

Integer to hold F estimate backup information.

Print every how many timesteps? ; -1: Do not backup during simulation

Definition at line 146 of file ABF.h.

◆ filename_

std::string SSAGES::ABF::filename_
private

File name for world data. Principal output of the method.

Definition at line 123 of file ABF.h.

◆ Fworld_

std::vector<Grid<double>*> SSAGES::ABF::Fworld_
private

Will hold the global total, synced across walkers at every time step.

This is a grid that holds dF/dCVx where x is one of the CVs. For N CVs, there will be N grids, and thus this vector will be N long. Global version.

Definition at line 70 of file ABF.h.

◆ histdetails_

std::vector<std::vector<double> > SSAGES::ABF::histdetails_
private

Histogram details.

This is a 2 Dimensional object set up as the following: Histdetails is a vector of (nr of CV) vectors, ordered in CV order. Each of those vectors are 3 long. First entry of each vector holds the lower bound for that CV. Second entry of each vector holds the upper bound for that CV. Third entry of each vector holds the nr of bins for that CV dimension.

Definition at line 140 of file ABF.h.

◆ min_

int SSAGES::ABF::min_
private

The minimum number of hits required before full biasing, bias is F_[i]/max(N_[i],min_).

Definition at line 98 of file ABF.h.

◆ N_

Grid<int>* SSAGES::ABF::N_
private

To store number of local hits at a given CV bin.

Stores the number of times each bin was visited in CV space.

Definition at line 48 of file ABF.h.

◆ Nworld_

Grid<int>* SSAGES::ABF::Nworld_
private

To store number of global hits at a given CV bin.

Stores the number of times each bin was visited in CV space. Global version.

Definition at line 55 of file ABF.h.

◆ periodicboundaries_

std::vector<std::vector<double> > SSAGES::ABF::periodicboundaries_
private

Holds periodic boundaries of CVs.

This is a 2 Dimensional object set up as the following: periodicboundaries_ is a vector of (nr of CV) vectors, ordered in CV order. Each of those vectors are 2 long. First entry of each vector holds the lower bound for that CV periodic boundary. Second entry of each vector holds the upper bound for that CV periodic boundary.

Definition at line 94 of file ABF.h.

◆ restraint_

std::vector<std::vector<double> > SSAGES::ABF::restraint_
private

Information for a harmonic restraint to keep CV in the region of interest.

This is a 2 Dimensional object set up as the following: restraint_ is a vector of (nr of CV) vectors, ordered in CV order. Each of those vectors are 3 long. First entry of each vector holds the lower bound for that CV restraint. Second entry of each vector holds the upper bound for that CV restraint. Third entry of each vector holds the spring constant for that CV restraint.

Definition at line 81 of file ABF.h.

◆ unitconv_

double SSAGES::ABF::unitconv_
private

Unit Conversion Constant from W dot P to Force.

It is crucial that unit conversion is entered correctly. Unit conversion from d(momentum)/d(time) to force for the simulation. For LAMMPS using units real, this is 2390.06 (gram.angstrom/mole.femtosecond^2 -> kcal/mole.angstrom)

Definition at line 155 of file ABF.h.


The documentation for this class was generated from the following files: