All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
MetaD.cpp
Go to the documentation of this file.
1 /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2  Copyright (c) 2013 The plumed team
3  (see the PEOPLE file at the root of the distribution for a list of names)
4 
5  See http://www.plumed-code.org for more information.
6 
7  This file is part of plumed, version 2.0.
8 
9  plumed is free software: you can redistribute it and/or modify
10  it under the terms of the GNU Lesser General Public License as published by
11  the Free Software Foundation, either version 3 of the License, or
12  (at your option) any later version.
13 
14  plumed is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  GNU Lesser General Public License for more details.
18 
19  You should have received a copy of the GNU Lesser General Public License
20  along with plumed. If not, see <http://www.gnu.org/licenses/>.
21 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
22 #include "Bias.h"
23 #include "ActionRegister.h"
24 #include "tools/Grid.h"
25 #include "core/PlumedMain.h"
26 #include "core/Atoms.h"
27 #include "tools/Exception.h"
28 #include "core/FlexibleBin.h"
29 #include "tools/Matrix.h"
30 #include "tools/Random.h"
31 #include <string>
32 #include <cstring>
33 #include "tools/File.h"
34 #include "time.h"
35 #include <iostream>
36 
37 #define DP2CUTOFF 6.25
38 
39 using namespace std;
40 
41 
42 namespace PLMD{
43 namespace bias{
44 
45 //+PLUMEDOC BIAS METAD
46 /*
47 Used to performed MetaDynamics on one or more collective variables.
48 
49 In a metadynamics simulations a history dependent bias composed of
50 intermittently added Gaussian functions is added to the potential \cite metad.
51 
52 \f[
53 V(\vec{s},t) = \sum_{ k \tau < t} W(k \tau)
54 \exp\left(
55 -\sum_{i=1}^{d} \frac{(s_i-s_i^{(0)}(k \tau))^2}{2\sigma_i^2}
56 \right).
57 \f]
58 
59 This potential forces the system away from the kinetic traps in the potential energy surface
60 and out into the unexplored parts of the energy landscape. Information on the Gaussian
61 functions from which this potential is composed is output to a file called HILLS, which
62 is used both the restart the calculation and to reconstruct the free energy as a function of the CVs.
63 The free energy can be reconstructed from a metadynamics calculation because the final bias is given
64 by:
65 
66 \f[
67 V(\vec{s}) = -F(\vec(s))
68 \f]
69 
70 During post processing the free energy can be calculated in this way using the \ref sum_hills
71 utility.
72 
73 In the simplest possible implementation of a metadynamics calculation the expense of a metadynamics
74 calculation increases with the length of the simulation as one has to, at every step, evaluate
75 the values of a larger and larger number of Gaussians. To avoid this issue you can in plumed 2.0
76 store the bias on a grid. This approach is similar to that proposed in \cite babi+08jcp but has the
77 advantage that the grid spacing is independent on the Gaussian width.
78 
79 Another option that is available in plumed 2.0 is well-tempered metadynamics \cite Barducci:2008. In this
80 varient of metadynamics the heights of the Gaussian hills are rescaled at each step so the bias is now
81 given by:
82 
83 \f[
84 V({s},t)= \sum_{t'=0,\tau_G,2\tau_G,\dots}^{t'<t} W e^{-V({s}({q}(t'),t')/\Delta T} \exp\left(
85 -\sum_{i=1}^{d} \frac{(s_i({q})-s_i({q}(t'))^2}{2\sigma_i^2}
86 \right),
87 \f]
88 
89 This method ensures that the bias converges more smoothly. It should be noted that, in the case of well-tempered metadynamics, in
90 the output printed the Gaussian height is re-scaled using the bias factor.
91 Also notice that with well-tempered metadynamics the HILLS file does not contain the bias,
92 but the negative of the free-energy estimate. This choice has the advantage that
93 one can restart a simulation using a different value for the \f$\Delta T\f$. The applied bias will be scaled accordingly.
94 
95 Note that you can use here also the flexible gaussian approach \cite Branduardi:2012dl
96 in which you can adapt the gaussian to the extent of Cartesian space covered by a variable or
97 to the space in collective variable covered in a given time. In this case the width of the deposited
98 gaussian potential is denoted by one value only that is a Cartesian space (ADAPTIVE=GEOM) or a time
99 (ADAPTIVE=DIFF). Note that a specific integration technique for the deposited gaussians
100 should be used in this case. Check the documentation for utility sum_hills.
101 
102 With the keyword INTERVAL one changes the metadynamics algorithm setting the bias force equal to zero
103 outside boundary \cite baftizadeh2012protein. If, for example, metadynamics is performed on a CV s and one is interested only
104 to the free energy for s > sw, the history dependent potential is still updated according to the above
105 equations but the metadynamics force is set to zero for s < sw. Notice that Gaussians are added also
106 if s < sw, as the tails of these Gaussians influence VG in the relevant region s > sw. In this way, the
107 force on the system in the region s > sw comes from both metadynamics and the force field, in the region
108 s < sw only from the latter. This approach allows obtaining a history-dependent bias potential VG that
109 fluctuates around a stable estimator, equal to the negative of the free energy far enough from the
110 boundaries. Note that:
111 - It works only for one-dimensional biases;
112 - It works both with and without GRID;
113 - The interval limit sw in a region where the free energy derivative is not large;
114 - If in the region outside the limit sw the system has a free energy minimum, the INTERVAL keyword should
115  be used together with a soft wall at sw
116 
117 As a final note, since version 2.0.2 when the system is outside of the selected interval the force
118 is set to zero and the bias value to the value at the corresponding boundary. This allows acceptances
119 for replica exchange methods to be computed correctly.
120 
121 Multiple walkers \cite multiplewalkers can also be used. See below the examples.
122 
123 \par Examples
124 The following input is for a standard metadynamics calculation using as
125 collective variables the distance between atoms 3 and 5
126 and the distance between atoms 2 and 4. The value of the CVs and
127 the metadynamics bias potential are written to the COLVAR file every 100 steps.
128 \verbatim
129 DISTANCE ATOMS=3,5 LABEL=d1
130 DISTANCE ATOMS=2,4 LABEL=d2
131 METAD ARG=d1,d2 SIGMA=0.2,0.2 HEIGHT=0.3 PACE=500 LABEL=restraint
132 PRINT ARG=d1,d2,restraint.bias STRIDE=100 FILE=COLVAR
133 \endverbatim
134 (See also \ref DISTANCE \ref PRINT).
135 
136 \par
137 If you use adaptive Gaussians, with diffusion scheme where you use
138 a Gaussian that should cover the space of 20 timesteps in collective variables.
139 Note that in this case the histogram correction is needed when summing up hills.
140 \verbatim
141 DISTANCE ATOMS=3,5 LABEL=d1
142 DISTANCE ATOMS=2,4 LABEL=d2
143 METAD ARG=d1,d2 SIGMA=20 HEIGHT=0.3 PACE=500 LABEL=restraint ADAPTIVE=DIFF
144 PRINT ARG=d1,d2,restraint.bias STRIDE=100 FILE=COLVAR
145 \endverbatim
146 
147 \par
148 If you use adaptive Gaussians, with geometrical scheme where you use
149 a Gaussian that should cover the space of 0.05 nm in Cartesian space.
150 Note that in this case the histogram correction is needed when summing up hills.
151 \verbatim
152 DISTANCE ATOMS=3,5 LABEL=d1
153 DISTANCE ATOMS=2,4 LABEL=d2
154 METAD ARG=d1,d2 SIGMA=0.05 HEIGHT=0.3 PACE=500 LABEL=restraint ADAPTIVE=GEOM
155 PRINT ARG=d1,d2,restraint.bias STRIDE=100 FILE=COLVAR
156 \endverbatim
157 
158 \par
159 When using adaptive Gaussians you might want to limit how the hills width can change.
160 You can use SIGMA_MIN and SIGMA_MAX keywords.
161 The sigmas should specified in terms of CV so you should use the CV units.
162 Note that if you use a negative number, this means that the limit is not set.
163 Note also that in this case the histogram correction is needed when summing up hills.
164 \verbatim
165 DISTANCE ATOMS=3,5 LABEL=d1
166 DISTANCE ATOMS=2,4 LABEL=d2
167 METAD ...
168  ARG=d1,d2 SIGMA=0.05 HEIGHT=0.3 PACE=500 LABEL=restraint ADAPTIVE=GEOM
169  SIGMA_MIN=0.2,0.1 SIGMA_MAX=0.5,1.0
170 ... METAD
171 PRINT ARG=d1,d2,restraint.bias STRIDE=100 FILE=COLVAR
172 \endverbatim
173 
174 
175 \par
176 Multiple walkers can be also use as in \cite multiplewalkers
177 These are enabled by setting the number of walker used, the id of the
178 current walker which interprets the input file, the directory where the
179 hills containing files resides, and the frequency to read the other walkers.
180 Here is an example
181 \verbatim
182 DISTANCE ATOMS=3,5 LABEL=d1
183 METAD ...
184  ARG=d1 SIGMA=0.05 HEIGHT=0.3 PACE=500 LABEL=restraint
185  WALKERS_N=10
186  WALKERS_ID=3
187  WALKERS_DIR=../
188  WALKERS_RSTRIDE=100
189 ... METAD
190 \endverbatim
191 where WALKERS_N is the total number of walkers, WALKERS_ID is the
192 id of the present walker (starting from 0 ) and the WALKERS_DIR is the directory
193 where all the walkers are located. WALKERS_RSTRIDE is the number of step between
194 one update and the other.
195 
196 
197 */
198 //+ENDPLUMEDOC
199 
200 class MetaD : public Bias{
201 
202 private:
203  struct Gaussian {
204  vector<double> center;
205  vector<double> sigma;
206  double height;
207  bool multivariate; // this is required to discriminate the one dimensional case
208  vector<double> invsigma;
209  Gaussian(const vector<double> & center,const vector<double> & sigma,double height, bool multivariate ):
210  center(center),sigma(sigma),height(height),multivariate(multivariate),invsigma(sigma){
211  for(unsigned i=0;i<invsigma.size();++i)abs(invsigma[i])>1.e-20?invsigma[i]=1.0/invsigma[i]:0.; // to avoid troubles from zero element in flexible hills
212  }
213  };
214  vector<double> sigma0_;
215  vector<double> sigma0min_;
216  vector<double> sigma0max_;
217  vector<Gaussian> hills_;
223  std::string gridfilename_,gridreadfilename_;
225  bool grid_,hasextgrid_;
226  double height0_;
227  double biasf_;
228  double temp_;
229  int stride_;
230  bool welltemp_;
231  double* dp_;
234  int mw_n_;
235  string mw_dir_;
236  int mw_id_;
238  vector<IFile*> ifiles;
239  vector<string> ifilesnames;
240  double uppI_;
241  double lowI_;
242  bool doInt_;
244 
245  void readGaussians(IFile*);
246  bool readChunkOfGaussians(IFile *ifile, unsigned n);
247  void writeGaussian(const Gaussian&,OFile&);
248  void addGaussian(const Gaussian&);
249  double getHeight(const vector<double>&);
250  double getBiasAndDerivatives(const vector<double>&,double* der=NULL);
251  double evaluateGaussian(const vector<double>&, const Gaussian&,double* der=NULL);
252  void finiteDifferenceGaussian(const vector<double>&, const Gaussian&);
253  vector<unsigned> getGaussianSupport(const Gaussian&);
254  bool scanOneHill(IFile *ifile, vector<Value> &v, vector<double> &center, vector<double> &sigma, double &height, bool &multivariate );
255  std::string fmt;
256 
257 public:
258  MetaD(const ActionOptions&);
259  ~MetaD();
260  void calculate();
261  void update();
262  static void registerKeywords(Keywords& keys);
263  bool checkNeedsGradients()const{if(adaptive_==FlexibleBin::geometry){return true;}else{return false;}}
264 };
265 
266 PLUMED_REGISTER_ACTION(MetaD,"METAD")
267 
268 void MetaD::registerKeywords(Keywords& keys){
269  Bias::registerKeywords(keys);
270  componentsAreNotOptional(keys);
271  keys.addOutputComponent("bias","default","the instantaneous value of the bias potential");
272  keys.use("ARG");
273  keys.add("compulsory","SIGMA","the widths of the Gaussian hills");
274  keys.add("compulsory","HEIGHT","the heights of the Gaussian hills");
275  keys.add("compulsory","PACE","the frequency for hill addition");
276  keys.add("compulsory","FILE","HILLS","a file in which the list of added hills is stored");
277  keys.add("optional","FMT","specify format for HILLS files (useful for decrease the number of digits in regtests)");
278  keys.add("optional","BIASFACTOR","use well tempered metadynamics and use this biasfactor. Please note you must also specify temp");
279  keys.add("optional","TEMP","the system temperature - this is only needed if you are doing well-tempered metadynamics");
280  keys.add("optional","GRID_MIN","the lower bounds for the grid");
281  keys.add("optional","GRID_MAX","the upper bounds for the grid");
282  keys.add("optional","GRID_BIN","the number of bins for the grid");
283  keys.addFlag("GRID_SPARSE",false,"use a sparse grid to store hills");
284  keys.addFlag("GRID_NOSPLINE",false,"don't use spline interpolation with grids");
285  keys.add("optional","GRID_WSTRIDE","write the grid to a file every N steps");
286  keys.add("optional","GRID_WFILE","the file on which to write the grid");
287  keys.addFlag("STORE_GRIDS",false,"store all the grid files the calculation generates. They will be deleted if this keyword is not present");
288  keys.add("optional","ADAPTIVE","use a geometric (=GEOM) or diffusion (=DIFF) based hills width scheme. Sigma is one number that has distance units or timestep dimensions");
289  keys.add("optional","WALKERS_ID", "walker id");
290  keys.add("optional","WALKERS_N", "number of walkers");
291  keys.add("optional","WALKERS_DIR", "shared directory with the hills files from all the walkers");
292  keys.add("optional","WALKERS_RSTRIDE","stride for reading hills files");
293  keys.add("optional","INTERVAL","monodimensional lower and upper limits, outside the limits the system will not feel the biasing force.");
294  keys.add("optional","GRID_RFILE","a grid file from which the bias should be read at the initial step of the simulation");
295  keys.add("optional","SIGMA_MAX","the upper bounds for the sigmas (in CV units) when using adaptive hills. Negative number means no bounds ");
296  keys.add("optional","SIGMA_MIN","the lower bounds for the sigmas (in CV units) when using adaptive hills. Negative number means no bounds ");
297 }
298 
299 MetaD::~MetaD(){
300  if(flexbin) delete flexbin;
301  if(BiasGrid_) delete BiasGrid_;
302  hillsOfile_.close();
303  if(wgridstride_>0) gridfile_.close();
304  delete [] dp_;
305  // close files
306  for(int i=0;i<mw_n_;++i){
307  if(ifiles[i]->isOpen()) ifiles[i]->close();
308  delete ifiles[i];
309  }
310 }
311 
312 MetaD::MetaD(const ActionOptions& ao):
313 PLUMED_BIAS_INIT(ao),
314 // Grid stuff initialization
315 BiasGrid_(NULL),ExtGrid_(NULL), wgridstride_(0), grid_(false), hasextgrid_(false),
316 // Metadynamics basic parameters
317 height0_(0.0), biasf_(1.0), temp_(0.0),
318 stride_(0), welltemp_(false),
319 // Other stuff
320 dp_(NULL), adaptive_(FlexibleBin::none),
321 flexbin(NULL),
322 // Multiple walkers initialization
323 mw_n_(1), mw_dir_("./"), mw_id_(0), mw_rstride_(1),
324 // Interval initialization
325 uppI_(-1), lowI_(-1), doInt_(false),
326 isFirstStep(true)
327 {
328  // parse the flexible hills
329  string adaptiveoption;
330  adaptiveoption="NONE";
331  parse("ADAPTIVE",adaptiveoption);
332  if (adaptiveoption=="GEOM"){
333  log.printf(" Uses Geometry-based hills width: sigma must be in distance units and only one sigma is needed\n");
335  }else if (adaptiveoption=="DIFF"){
336  log.printf(" Uses Diffusion-based hills width: sigma must be in timesteps and only one sigma is needed\n");
338  }else if (adaptiveoption=="NONE"){
340  }else{
341  error("I do not know this type of adaptive scheme");
342  }
343  // parse the sigma
344  parseVector("SIGMA",sigma0_);
345 
346  parse("FMT",fmt);
347 
348  // if you use normal sigma you need one sigma per argument
350  if( sigma0_.size()!=getNumberOfArguments() ) error("number of arguments does not match number of SIGMA parameters");
351  }else{
352  // if you use flexible hills you need one sigma
353  if(sigma0_.size()!=1){
354  error("If you choose ADAPTIVE you need only one sigma according to your choice of type (GEOM/DIFF)");
355  }
356  // if adaptive then the number must be an integer
358  if(int(sigma0_[0])-sigma0_[0]>1.e-9 || int(sigma0_[0])-sigma0_[0] <-1.e-9 || int(sigma0_[0])<1 ){
359  plumed_merror("In case of adaptive hills with diffusion, the sigma must be an integer which is the number of timesteps\n");
360  }
361  }
362  // here evtl parse the sigma min and max values
363 
364  parseVector("SIGMA_MIN",sigma0min_);
365  if(sigma0min_.size()>0 && sigma0min_.size()<getNumberOfArguments()){error("the number of SIGMA_MIN values be at least the number of the arguments"); }
366  else if(sigma0min_.size()==0) { sigma0min_.resize(getNumberOfArguments());for(unsigned i=0;i<getNumberOfArguments();i++){sigma0min_[i]=-1.;} }
367 
368  parseVector("SIGMA_MAX",sigma0max_);
369  if(sigma0max_.size()>0 && sigma0max_.size()<getNumberOfArguments()){error("the number of SIGMA_MAX values be at least the number of the arguments"); }
370  else if(sigma0max_.size()==0) { sigma0max_.resize(getNumberOfArguments());for(unsigned i=0;i<getNumberOfArguments();i++){sigma0max_[i]=-1.;} }
371 
373  }
374  parse("HEIGHT",height0_);
375  if( height0_<=0.0 ) error("error cannot add zero height or negative height hills");
376  parse("PACE",stride_);
377  if(stride_<=0 ) error("frequency for hill addition is nonsensical");
378  string hillsfname="HILLS";
379  parse("FILE",hillsfname);
380  parse("BIASFACTOR",biasf_);
381  if( biasf_<1.0 ) error("well tempered bias factor is nonsensical");
382  parse("TEMP",temp_);
383  if(biasf_>1.0){
384  if(temp_==0.0) error("if you are doing well tempered metadynamics you must specify the temperature using TEMP");
385  welltemp_=true;
386  }
387 
388  // Grid Stuff
389  vector<std::string> gmin(getNumberOfArguments());
390  parseVector("GRID_MIN",gmin);
391  if(gmin.size()!=getNumberOfArguments() && gmin.size()!=0) error("not enough values for GRID_MIN");
392  vector<std::string> gmax(getNumberOfArguments());
393  parseVector("GRID_MAX",gmax);
394  if(gmax.size()!=getNumberOfArguments() && gmax.size()!=0) error("not enough values for GRID_MAX");
395  vector<unsigned> gbin(getNumberOfArguments());
396  parseVector("GRID_BIN",gbin);
397  if(gbin.size()!=getNumberOfArguments() && gbin.size()!=0) error("not enough values for GRID_BIN");
398  if( gmin.size()!=gmax.size() || gmin.size()!=gbin.size() ) error("GRID MIN was specified without either GRID_MAX or GRID_BIN");
399  bool sparsegrid=false;
400  parseFlag("GRID_SPARSE",sparsegrid);
401  bool nospline=false;
402  parseFlag("GRID_NOSPLINE",nospline);
403  bool spline=!nospline;
404  if(gbin.size()>0){grid_=true;}
405  parse("GRID_WSTRIDE",wgridstride_);
406  parse("GRID_WFILE",gridfilename_);
407  parseFlag("STORE_GRIDS",storeOldGrids_);
408  if(grid_ && gridfilename_.length()>0){
409  if(wgridstride_==0 ) error("frequency with which to output grid not specified use GRID_WSTRIDE");
410  }
411 
412  if(grid_ && wgridstride_>0){
413  if(gridfilename_.length()==0) error("grid filename not specified use GRID_WFILE");
414  }
415 
416  parse("GRID_RFILE",gridreadfilename_);
417 
418  // Multiple walkers
419  parse("WALKERS_N",mw_n_);
420  parse("WALKERS_ID",mw_id_);
421  if(mw_n_<=mw_id_) error("walker ID should be a numerical value less than the total number of walkers");
422  parse("WALKERS_DIR",mw_dir_);
423  parse("WALKERS_RSTRIDE",mw_rstride_);
424 
425  // Inteval keyword
426  vector<double> tmpI(2);
427  parseVector("INTERVAL",tmpI);
428  if(tmpI.size()!=2&&tmpI.size()!=0) error("both a lower and an upper limits must be provided with INTERVAL");
429  else if(tmpI.size()==2) {
430  lowI_=tmpI.at(0);
431  uppI_=tmpI.at(1);
432  if(getNumberOfArguments()!=1) error("INTERVAL limits correction works only for monodimensional metadynamics!");
433  if(uppI_<lowI_) error("The Upper limit must be greater than the Lower limit!");
434  doInt_=true;
435  }
436 
437  checkRead();
438 
439  log.printf(" Gaussian width ");
440  if (adaptive_==FlexibleBin::diffusion)log.printf(" (Note: The units of sigma are in timesteps) ");
441  if (adaptive_==FlexibleBin::geometry)log.printf(" (Note: The units of sigma are in dist units) ");
442  for(unsigned i=0;i<sigma0_.size();++i) log.printf(" %f",sigma0_[i]);
443  log.printf(" Gaussian height %f\n",height0_);
444  log.printf(" Gaussian deposition pace %d\n",stride_);
445  log.printf(" Gaussian file %s\n",hillsfname.c_str());
446  if(welltemp_){log.printf(" Well-Tempered Bias Factor %f\n",biasf_);}
447  if(doInt_) log.printf(" Upper and Lower limits boundaries for the bias are activated at %f - %f\n", lowI_, uppI_);
448  if(grid_){
449  log.printf(" Grid min");
450  for(unsigned i=0;i<gmin.size();++i) log.printf(" %s",gmin[i].c_str() );
451  log.printf("\n");
452  log.printf(" Grid max");
453  for(unsigned i=0;i<gmax.size();++i) log.printf(" %s",gmax[i].c_str() );
454  log.printf("\n");
455  log.printf(" Grid bin");
456  for(unsigned i=0;i<gbin.size();++i) log.printf(" %d",gbin[i]);
457  log.printf("\n");
458  if(spline){log.printf(" Grid uses spline interpolation\n");}
459  if(sparsegrid){log.printf(" Grid uses sparse grid\n");}
460  if(wgridstride_>0){log.printf(" Grid is written on file %s with stride %d\n",gridfilename_.c_str(),wgridstride_);}
461  }
462  if(gridreadfilename_.length()>0){
463  log.printf(" Reading an additional bias from grid in file %s \n",gridreadfilename_.c_str());
464  }
465 
466 
467  if(mw_n_>1){
468  log.printf(" %d multiple walkers active\n",mw_n_);
469  log.printf(" walker id %d\n",mw_id_);
470  log.printf(" reading stride %d\n",mw_rstride_);
471  log.printf(" directory with hills files %s\n",mw_dir_.c_str());
472  }
473 
474  addComponent("bias"); componentIsNotPeriodic("bias");
475 
476 // for performance
477  dp_ = new double[getNumberOfArguments()];
478 
479 // initializing grid
480  if(grid_){
481  std::string funcl=getLabel() + ".bias";
482  if(!sparsegrid){BiasGrid_=new Grid(funcl,getArguments(),gmin,gmax,gbin,spline,true);}
483  else{BiasGrid_=new SparseGrid(funcl,getArguments(),gmin,gmax,gbin,spline,true);}
484  std::vector<std::string> actualmin=BiasGrid_->getMin();
485  std::vector<std::string> actualmax=BiasGrid_->getMax();
486  for(unsigned i=0;i<getNumberOfArguments();i++){
487  if(gmin[i]!=actualmin[i]) log<<" WARNING: GRID_MIN["<<i<<"] has been adjusted to "<<actualmin[i]<<" to fit periodicity\n";
488  if(gmax[i]!=actualmax[i]) log<<" WARNING: GRID_MAX["<<i<<"] has been adjusted to "<<actualmax[i]<<" to fit periodicity\n";
489  }
490  }
491 
492  if(wgridstride_>0){
493  gridfile_.link(*this);
495  }
496 
497 // initializing external grid
498  if(gridreadfilename_.length()>0){
499  hasextgrid_=true;
500  // read the grid in input, find the keys
501  IFile gridfile; gridfile.open(gridreadfilename_);
502  std::string funcl=getLabel() + ".bias";
503  ExtGrid_=Grid::create(funcl,getArguments(),gridfile,false,false,true);
504  gridfile.close();
505  if(ExtGrid_->getDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments");
506  for(unsigned i=0;i<getNumberOfArguments();++i){
507  if( getPntrToArgument(i)->isPeriodic()!=ExtGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias");
508  }
509  }
510 
511 // creating vector of ifile* for hills reading
512 // open all files at the beginning and read Gaussians if restarting
513  for(int i=0;i<mw_n_;++i){
514  string fname;
515  if(mw_n_>1) {
516  stringstream out; out << i;
517  fname = mw_dir_+"/"+hillsfname+"."+out.str();
518  } else {
519  fname = hillsfname;
520  }
521  IFile *ifile = new IFile();
522  ifile->link(*this);
523  ifiles.push_back(ifile);
524  ifilesnames.push_back(fname);
525  if(ifile->FileExist(fname)){
526  ifile->open(fname);
527  if(plumed.getRestart()){
528  log.printf(" Restarting from %s:",ifilesnames[i].c_str());
529  readGaussians(ifiles[i]);
530  }
531  ifiles[i]->reset(false);
532  // close only the walker own hills file for later writing
533  if(i==mw_id_) ifiles[i]->close();
534  }
535  }
536 
537 // open hills file for writing
538  hillsOfile_.link(*this);
540  if(fmt.length()>0) hillsOfile_.fmtField(fmt);
541  hillsOfile_.addConstantField("multivariate");
543 // output periodicities of variables
544  for(unsigned i=0;i<getNumberOfArguments();++i) hillsOfile_.setupPrintValue( getPntrToArgument(i) );
545 
546  log<<" Bibliography "<<plumed.cite("Laio and Parrinello, PNAS 99, 12562 (2002)");
547  if(welltemp_) log<<plumed.cite(
548  "Barducci, Bussi, and Parrinello, Phys. Rev. Lett. 100, 020603 (2008)");
549  if(mw_n_>1) log<<plumed.cite(
550  "Raiteri, Laio, Gervasio, Micheletti, and Parrinello, J. Phys. Chem. B 110, 3533 (2006)");
552  "Branduardi, Bussi, and Parrinello, J. Chem. Theory Comput. 8, 2247 (2012)");
553  if(doInt_) log<<plumed.cite(
554  "Baftizadeh, Cossio, Pietrucci, and Laio, Curr. Phys. Chem. 2, 79 (2012)");
555  log<<"\n";
556 
557 }
558 
560 {
561  unsigned ncv=getNumberOfArguments();
562  vector<double> center(ncv);
563  vector<double> sigma(ncv);
564  double height;
565  int nhills=0;
566  bool multivariate=false;
567 
568  std::vector<Value> tmpvalues;
569  for(unsigned j=0;j<getNumberOfArguments();++j) tmpvalues.push_back( Value( this, getPntrToArgument(j)->getName(), false ) );
570 
571  while(scanOneHill(ifile,tmpvalues,center,sigma,height,multivariate)){;
572  nhills++;
573  if(welltemp_){height*=(biasf_-1.0)/biasf_;}
574  addGaussian(Gaussian(center,sigma,height,multivariate));
575  }
576  log.printf(" %d Gaussians read\n",nhills);
577 }
578 
579 bool MetaD::readChunkOfGaussians(IFile *ifile, unsigned n)
580 {
581  unsigned ncv=getNumberOfArguments();
582  vector<double> center(ncv);
583  vector<double> sigma(ncv);
584  double height;
585  unsigned nhills=0;
586  bool multivariate=false;
587  std::vector<Value> tmpvalues;
588  for(unsigned j=0;j<getNumberOfArguments();++j) tmpvalues.push_back( Value( this, getPntrToArgument(j)->getName(), false ) );
589 
590  while(scanOneHill(ifile,tmpvalues,center,sigma,height,multivariate)){;
591  if(welltemp_){height*=(biasf_-1.0)/biasf_;}
592  addGaussian(Gaussian(center,sigma,height,multivariate));
593  if(nhills==n){
594  log.printf(" %u Gaussians read\n",nhills);
595  return true;
596  }
597  nhills++;
598  }
599  log.printf(" %u Gaussians read\n",nhills);
600  return false;
601 }
602 
603 void MetaD::writeGaussian(const Gaussian& hill, OFile&file){
604  unsigned ncv=getNumberOfArguments();
605  file.printField("time",getTimeStep()*getStep());
606  for(unsigned i=0;i<ncv;++i){
607  file.printField(getPntrToArgument(i),hill.center[i]);
608  }
609  if(hill.multivariate){
610  hillsOfile_.printField("multivariate","true");
611  Matrix<double> mymatrix(ncv,ncv);
612  unsigned k=0;
613  for(unsigned i=0;i<ncv;i++){
614  for(unsigned j=i;j<ncv;j++){
615  mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k]; // recompose the full inverse matrix
616  k++;
617  }
618  }
619  // invert it
620  Matrix<double> invmatrix(ncv,ncv);
621  Invert(mymatrix,invmatrix);
622  // enforce symmetry
623  for(unsigned i=0;i<ncv;i++){
624  for(unsigned j=i;j<ncv;j++){
625  invmatrix(i,j)=invmatrix(j,i);
626  }
627  }
628 
629  // do cholesky so to have a "sigma like" number
630  Matrix<double> lower(ncv,ncv);
631  cholesky(invmatrix,lower); // now this , in band form , is similar to the sigmas
632  // loop in band form
633  for (unsigned i=0;i<ncv;i++){
634  for (unsigned j=0;j<ncv-i;j++){
635  file.printField("sigma_"+getPntrToArgument(j+i)->getName()+"_"+getPntrToArgument(j)->getName(),lower(j+i,j));
636  }
637  }
638  } else {
639  hillsOfile_.printField("multivariate","false");
640  for(unsigned i=0;i<ncv;++i)
641  file.printField("sigma_"+getPntrToArgument(i)->getName(),hill.sigma[i]);
642  }
643  double height=hill.height;
644  if(welltemp_){height*=biasf_/(biasf_-1.0);}
645  file.printField("height",height).printField("biasf",biasf_);
646  if(mw_n_>1) file.printField("clock",int(time(0)));
647  file.printField();
648 }
649 
650 void MetaD::addGaussian(const Gaussian& hill)
651 {
652  if(!grid_){hills_.push_back(hill);}
653  else{
654  unsigned ncv=getNumberOfArguments();
655  vector<unsigned> nneighb=getGaussianSupport(hill);
656  vector<unsigned> neighbors=BiasGrid_->getNeighbors(hill.center,nneighb);
657  vector<double> der(ncv);
658  vector<double> xx(ncv);
659  if(comm.Get_size()==1){
660  for(unsigned i=0;i<neighbors.size();++i){
661  unsigned ineigh=neighbors[i];
662  for(unsigned j=0;j<ncv;++j){der[j]=0.0;}
663  BiasGrid_->getPoint(ineigh,xx);
664  double bias=evaluateGaussian(xx,hill,&der[0]);
665  BiasGrid_->addValueAndDerivatives(ineigh,bias,der);
666  }
667  } else {
668  unsigned stride=comm.Get_size();
669  unsigned rank=comm.Get_rank();
670  vector<double> allder(ncv*neighbors.size(),0.0);
671  vector<double> allbias(neighbors.size(),0.0);
672  for(unsigned i=rank;i<neighbors.size();i+=stride){
673  unsigned ineigh=neighbors[i];
674  BiasGrid_->getPoint(ineigh,xx);
675  allbias[i]=evaluateGaussian(xx,hill,&allder[ncv*i]);
676  }
677  comm.Sum(&allbias[0],allbias.size());
678  comm.Sum(&allder[0],allder.size());
679  for(unsigned i=0;i<neighbors.size();++i){
680  unsigned ineigh=neighbors[i];
681  for(unsigned j=0;j<ncv;++j){der[j]=allder[ncv*i+j];}
682  BiasGrid_->addValueAndDerivatives(ineigh,allbias[i],der);
683  }
684  }
685  }
686 }
687 
688 vector<unsigned> MetaD::getGaussianSupport(const Gaussian& hill)
689 {
690 // in this case, we updated the entire grid to avoid problems
691 // it could be optimized reverting to the normal case whenever a hill
692 // is far enough from the boundaries
693  if(doInt_){
694  return BiasGrid_->getNbin();
695  }
696  vector<unsigned> nneigh;
697  // traditional or flexible hill?
698  if(hill.multivariate){
699  unsigned ncv=getNumberOfArguments();
700  unsigned k=0;
701  //log<<"------- GET GAUSSIAN SUPPORT --------\n";
702  Matrix<double> mymatrix(ncv,ncv);
703  for(unsigned i=0;i<ncv;i++){
704  for(unsigned j=i;j<ncv;j++){
705  mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k]; // recompose the full inverse matrix
706  k++;
707  }
708  }
709  //
710  // Reinvert so to have the ellipses
711  //
712  Matrix<double> myinv(ncv,ncv);
713  Invert(mymatrix,myinv);
714  //log<<"INVERSE \n";
715  //matrixOut(log,myinv);
716  // diagonalizes it
717  Matrix<double> myautovec(ncv,ncv);
718  vector<double> myautoval(ncv); //should I take this or their square root?
719  diagMat(myinv,myautoval,myautovec);
720  double maxautoval;maxautoval=0.;
721  unsigned ind_maxautoval;ind_maxautoval=ncv;
722  for (unsigned i=0;i<ncv;i++){
723  if(myautoval[i]>maxautoval){maxautoval=myautoval[i];ind_maxautoval=i;}
724  }
725  for (unsigned i=0;i<ncv;i++){
726  double cutoff=sqrt(2.0*DP2CUTOFF)*abs(sqrt(maxautoval)*myautovec(i,ind_maxautoval));
727  //log<<"AUTOVAL "<<myautoval[0]<<" COMP "<<abs(myautoval[0]*myautovec(i,0)) <<" CUTOFF "<<cutoff<<"\n";
728  nneigh.push_back( static_cast<unsigned>(ceil(cutoff/BiasGrid_->getDx()[i])) );
729  }
730  }else{
731  for(unsigned i=0;i<getNumberOfArguments();++i){
732  double cutoff=sqrt(2.0*DP2CUTOFF)*hill.sigma[i];
733  nneigh.push_back( static_cast<unsigned>(ceil(cutoff/BiasGrid_->getDx()[i])) );
734  }
735  }
736  //log<<"------- END GET GAUSSIAN SUPPORT --------\n";
737  return nneigh;
738 }
739 
740 double MetaD::getBiasAndDerivatives(const vector<double>& cv, double* der)
741 {
742  double bias=0.0;
743  if(!grid_){
744  unsigned stride=comm.Get_size();
745  unsigned rank=comm.Get_rank();
746  for(unsigned i=rank;i<hills_.size();i+=stride){
747  bias+=evaluateGaussian(cv,hills_[i],der);
748  //finite difference test
749  //finiteDifferenceGaussian(cv,hills_[i]);
750  }
751  comm.Sum(&bias,1);
752  if(der) comm.Sum(&der[0],getNumberOfArguments());
753  }else{
754  if(der){
755  vector<double> vder(getNumberOfArguments());
756  bias=BiasGrid_->getValueAndDerivatives(cv,vder);
757  for(unsigned i=0;i<getNumberOfArguments();++i) {der[i]=vder[i];}
758  }else{
759  bias=BiasGrid_->getValue(cv);
760  }
761  }
762  if(hasextgrid_){
763  if(der){
764  vector<double> vder(getNumberOfArguments());
765  bias+=ExtGrid_->getValueAndDerivatives(cv,vder);
766  for(unsigned i=0;i<getNumberOfArguments();++i) {der[i]+=vder[i];}
767  }else{
768  bias+=ExtGrid_->getValue(cv);
769  }
770  }
771  return bias;
772 }
773 
775  (const vector<double>& cv, const Gaussian& hill, double* der)
776 {
777  double dp2=0.0;
778  double bias=0.0;
779 // I use a pointer here because cv is const (and should be const)
780 // but when using doInt it is easier to locally replace cv[0] with
781 // the upper/lower limit in case it is out of range
782  const double *pcv=NULL; // pointer to cv
783  double tmpcv[1]; // tmp array with cv (to be used with doInt_)
784  if(cv.size()>0) pcv=&cv[0];
785  if(doInt_){
786  plumed_assert(cv.size()==1);
787  pcv=&(tmpcv[0]);
788  tmpcv[0]=cv[0];
789  if(cv[0]<lowI_) tmpcv[0]=lowI_;
790  if(cv[0]>uppI_) tmpcv[0]=uppI_;
791  }
792  if(hill.multivariate){
793  unsigned k=0;
794  unsigned ncv=cv.size();
795  // recompose the full sigma from the upper diag cholesky
796  Matrix<double> mymatrix(ncv,ncv);
797  for(unsigned i=0;i<ncv;i++){
798  for(unsigned j=i;j<ncv;j++){
799  mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k]; // recompose the full inverse matrix
800  k++;
801  }
802  }
803 
804  for(unsigned i=0;i<cv.size();++i){
805  double dp_i=difference(i,hill.center[i],pcv[i]);
806  dp_[i]=dp_i;
807  for(unsigned j=i;j<cv.size();++j){
808  if(i==j){
809  dp2+=dp_i*dp_i*mymatrix(i,j)*0.5;
810  }else{
811  double dp_j=difference(j,hill.center[j],pcv[j]);
812  dp2+=dp_i*dp_j*mymatrix(i,j) ;
813  }
814  }
815  }
816  if(dp2<DP2CUTOFF){
817  bias=hill.height*exp(-dp2);
818  if(der){
819  for(unsigned i=0;i<cv.size();++i){
820  double tmp=0.0;
821  k=i;
822  for(unsigned j=0;j<cv.size();++j){
823  tmp+= dp_[j]*mymatrix(i,j)*bias;
824  }
825  der[i]-=tmp;
826  }
827  }
828  }
829  }else{
830  for(unsigned i=0;i<cv.size();++i){
831  double dp=difference(i,hill.center[i],pcv[i])*hill.invsigma[i];
832  dp2+=dp*dp;
833  dp_[i]=dp;
834  }
835  dp2*=0.5;
836  if(dp2<DP2CUTOFF){
837  bias=hill.height*exp(-dp2);
838  if(der){
839  for(unsigned i=0;i<cv.size();++i){der[i]+=-bias*dp_[i]*hill.invsigma[i];}
840  }
841  }
842  }
843  if(doInt_){
844  if((cv[0]<lowI_ || cv[0]>uppI_) && der ) for(unsigned i=0;i<cv.size();++i)der[i]=0;
845  }
846  return bias;
847 }
848 
849 double MetaD::getHeight(const vector<double>& cv)
850 {
851  double height=height0_;
852  if(welltemp_){
853  double vbias=getBiasAndDerivatives(cv);
854  height=height0_*exp(-vbias/(plumed.getAtoms().getKBoltzmann()*temp_*(biasf_-1.0)));
855  }
856  return height;
857 }
858 
860 {
861 
862 // this is because presently there is no way to properly pass information
863 // on adaptive hills (diff) after exchanges:
864  if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) error("ADAPTIVE=DIFF is not compatible with replica exchange");
865 
866  unsigned ncv=getNumberOfArguments();
867  vector<double> cv(ncv);
868  for(unsigned i=0;i<ncv;++i){cv[i]=getArgument(i);}
869 
870  double* der=new double[ncv];
871  for(unsigned i=0;i<ncv;++i){der[i]=0.0;}
872  double ene=getBiasAndDerivatives(cv,der);
873  getPntrToComponent("bias")->set(ene);
874 
875 // set Forces
876  for(unsigned i=0;i<ncv;++i){
877  const double f=-der[i];
878  setOutputForce(i,f);
879  }
880 
881  delete [] der;
882 }
883 
885  vector<double> cv(getNumberOfArguments());
886  vector<double> thissigma;
887  bool multivariate;
888 
889  // adding hills criteria (could be more complex though)
890  bool nowAddAHill;
891  if(getStep()%stride_==0 && !isFirstStep ){nowAddAHill=true;}else{nowAddAHill=false;isFirstStep=false;}
892 
893  for(unsigned i=0;i<cv.size();++i){cv[i]=getArgument(i);}
894 
895  // if you use adaptive, call the FlexibleBin
897  flexbin->update(nowAddAHill);
898  multivariate=true;
899  }else{
900  multivariate=false;
901  };
902 
903  if(nowAddAHill){ // probably this can be substituted with a signal
904  // add a Gaussian
905  double height=getHeight(cv);
906  // use normal sigma or matrix form?
908  thissigma=flexbin->getInverseMatrix(); // returns upper diagonal inverse
909  //cerr<<"ADDING HILLS "<<endl;
910  }else{
911  thissigma=sigma0_; // returns normal sigma
912  }
913  Gaussian newhill=Gaussian(cv,thissigma,height,multivariate);
914  addGaussian(newhill);
915 // print on HILLS file
916  writeGaussian(newhill,hillsOfile_);
917  }
918 // dump grid on file
919  if(wgridstride_>0&&getStep()%wgridstride_==0){
920 // in case old grids are stored, a sequence of grids should appear
921 // this call results in a repetition of the header:
923 // in case only latest grid is stored, file should be rewound
924 // this will overwrite previously written grids
925  else gridfile_.rewind();
927 // if a single grid is stored, it is necessary to flush it, otherwise
928 // the file might stay empty forever (when a single grid is not large enough to
929 // trigger flushing from the operating system).
930 // on the other hand, if grids are stored one after the other this is
931 // no necessary, and we leave the flushing control to the user as usual
932 // (with FLUSH keyword)
934  }
935 
936 // if multiple walkers and time to read Gaussians
937  if(mw_n_>1 && getStep()%mw_rstride_==0){
938  for(int i=0;i<mw_n_;++i){
939  // don't read your own Gaussians
940  if(i==mw_id_) continue;
941  // if the file is not open yet
942  if(!(ifiles[i]->isOpen())){
943  // check if it exists now and open it!
944  if(ifiles[i]->FileExist(ifilesnames[i])) {
945  ifiles[i]->open(ifilesnames[i]);
946  ifiles[i]->reset(false);
947  }
948  // otherwise read the new Gaussians
949  } else {
950  log.printf(" Reading hills from %s:",ifilesnames[i].c_str());
951  readGaussians(ifiles[i]);
952  ifiles[i]->reset(false);
953  }
954  }
955  }
956 }
957 
959  (const vector<double>& cv, const Gaussian& hill)
960 {
961  log<<"--------- finiteDifferenceGaussian: size "<<cv.size() <<"------------\n";
962  // for each cv
963  // first get the bias and the derivative
964  vector<double> oldder(cv.size());
965  vector<double> der(cv.size());
966  vector<double> mycv(cv.size());
967  mycv=cv;
968  double step=1.e-6;
969  Random random;
970  // just displace a tiny bit
971  for(unsigned i=0;i<cv.size();i++)log<<"CV "<<i<<" V "<<mycv[i]<<"\n";
972  for(unsigned i=0;i<cv.size();i++)mycv[i]+=1.e-2*2*(random.RandU01()-0.5);
973  for(unsigned i=0;i<cv.size();i++)log<<"NENEWWCV "<<i<<" V "<<mycv[i]<<"\n";
974  double oldbias=evaluateGaussian(mycv,hill,&oldder[0]);
975  for (unsigned i=0;i<mycv.size();i++){
976  double delta=step*2*(random.RandU01()-0.5);
977  mycv[i]+=delta;
978  double newbias=evaluateGaussian(mycv,hill,&der[0]);
979  log<<"CV "<<i;
980  log<<" ANAL "<<oldder[i]<<" NUM "<<(newbias-oldbias)/delta<<" DIFF "<<(oldder[i]-(newbias-oldbias)/delta)<<"\n";
981  mycv[i]-=delta;
982  }
983  log<<"--------- END finiteDifferenceGaussian ------------\n";
984 }
985 
986 /// takes a pointer to the file and a template string with values v and gives back the next center, sigma and height
987 bool MetaD::scanOneHill(IFile *ifile, vector<Value> &tmpvalues, vector<double> &center, vector<double> &sigma, double &height , bool &multivariate ){
988  double dummy;
989  multivariate=false;
990  if(ifile->scanField("time",dummy)){
991  unsigned ncv; ncv=tmpvalues.size();
992  for(unsigned i=0;i<ncv;++i){
993  ifile->scanField( &tmpvalues[i] );
994  if( tmpvalues[i].isPeriodic() && ! getPntrToArgument(i)->isPeriodic() ){
995  error("in hills file periodicity for variable " + tmpvalues[i].getName() + " does not match periodicity in input");
996  } else if( tmpvalues[i].isPeriodic() ){
997  std::string imin, imax; tmpvalues[i].getDomain( imin, imax );
998  std::string rmin, rmax; getPntrToArgument(i)->getDomain( rmin, rmax );
999  if( imin!=rmin || imax!=rmax ){
1000  error("in hills file periodicity for variable " + tmpvalues[i].getName() + " does not match periodicity in input");
1001  }
1002  }
1003  center[i]=tmpvalues[i].get();
1004  }
1005  // scan for multivariate label: record the actual file position so to eventually rewind
1006  std::string sss;
1007  ifile->scanField("multivariate",sss);
1008  if(sss=="true") multivariate=true;
1009  else if(sss=="false") multivariate=false;
1010  else plumed_merror("cannot parse multivariate = "+ sss);
1011  if(multivariate){
1012  sigma.resize(ncv*(ncv+1)/2);
1013  Matrix<double> upper(ncv,ncv);
1014  Matrix<double> lower(ncv,ncv);
1015  for (unsigned i=0;i<ncv;i++){
1016  for (unsigned j=0;j<ncv-i;j++){
1017  ifile->scanField("sigma_"+getPntrToArgument(j+i)->getName()+"_"+getPntrToArgument(j)->getName(),lower(j+i,j));
1018  upper(j,j+i)=lower(j+i,j);
1019  }
1020  }
1021  Matrix<double> mymult(ncv,ncv);
1022  Matrix<double> invmatrix(ncv,ncv);
1023  //log<<"Lower \n";
1024  //matrixOut(log,lower);
1025  //log<<"Upper \n";
1026  //matrixOut(log,upper);
1027  mult(lower,upper,mymult);
1028  //log<<"Mult \n";
1029  //matrixOut(log,mymult);
1030  // now invert and get the sigmas
1031  Invert(mymult,invmatrix);
1032  //log<<"Invert \n";
1033  //matrixOut(log,invmatrix);
1034  // put the sigmas in the usual order: upper diagonal (this time in normal form and not in band form)
1035  unsigned k=0;
1036  for (unsigned i=0;i<ncv;i++){
1037  for (unsigned j=i;j<ncv;j++){
1038  sigma[k]=invmatrix(i,j);
1039  k++;
1040  }
1041  }
1042  }else{
1043  for(unsigned i=0;i<ncv;++i){
1044  ifile->scanField("sigma_"+getPntrToArgument(i)->getName(),sigma[i]);
1045  }
1046  }
1047 
1048  ifile->scanField("height",height);
1049  ifile->scanField("biasf",dummy);
1050  if(ifile->FieldExist("clock")) ifile->scanField("clock",dummy);
1051  ifile->scanField();
1052  return true;
1053  }else{
1054  return false;
1055  };
1056 }
1057 
1058 }
1059 }
bool FieldExist(const std::string &s)
Check if a field exist.
Definition: IFile.cpp:104
vector< double > sigma
Definition: MetaD.cpp:205
void parseFlag(const std::string &key, bool &t)
Parse one keyword as boolean flag.
Definition: Action.cpp:104
vector< double > center
Definition: MetaD.cpp:204
void calculate()
Calculate an Action.
Definition: MetaD.cpp:859
Log & log
Reference to the log stream.
Definition: Action.h:93
OFile & rewind()
Rewind a file.
Definition: OFile.cpp:284
double height0_
Definition: MetaD.cpp:226
bool storeOldGrids_
Definition: MetaD.cpp:222
int Invert(const Matrix< T > &A, Matrix< double > &inverse)
Definition: Matrix.h:246
double * dp_
Definition: MetaD.cpp:231
vector< unsigned > getGaussianSupport(const Gaussian &)
Definition: MetaD.cpp:688
void componentIsNotPeriodic(const std::string &name)
Set your value component to have no periodicity.
OFile hillsOfile_
Definition: MetaD.cpp:218
A class for holding the value of a function together with its derivatives.
Definition: Value.h:46
void cholesky(const Matrix< T > &A, Matrix< T > &B)
Definition: Matrix.h:282
vector< double > sigma0max_
Definition: MetaD.cpp:216
void error(const std::string &msg) const
Crash calculation and print documentation.
Definition: Action.cpp:195
void addGaussian(const Gaussian &)
Definition: MetaD.cpp:650
virtual double getValueAndDerivatives(unsigned index, std::vector< double > &der) const
get grid value and derivatives
Definition: Grid.cpp:395
unsigned getDimension() const
get grid dimension
Definition: Grid.cpp:163
const std::string & getLabel() const
Returns the label.
Definition: Action.h:263
FileBase & link(FILE *)
Link to an already open filed.
Definition: FileBase.cpp:64
double getTimeStep() const
Return the timestep.
Definition: Action.cpp:177
OFile & fmtField(const std::string &)
Set the format for writing double precision fields.
Definition: OFile.cpp:135
void checkRead()
Check if Action was properly read.
Definition: Action.cpp:161
STL namespace.
Value * getPntrToArgument(const unsigned n)
Return a pointer to specific argument.
Communicator & comm
Definition: Action.h:158
void addComponent(const std::string &name)
Add a value with a name like label.name.
#define DP2CUTOFF
Definition: MetaD.cpp:37
void setHeavyFlush()
Set heavyFlush flag.
Definition: FileBase.h:101
Provides the keyword METAD
Definition: MetaD.cpp:200
void const char const char int * n
Definition: Matrix.h:42
OFile & addConstantField(const std::string &)
Definition: OFile.cpp:120
bool readChunkOfGaussians(IFile *ifile, unsigned n)
Definition: MetaD.cpp:579
Grid * BiasGrid_
Definition: MetaD.cpp:220
FlexibleBin * flexbin
Definition: MetaD.cpp:233
void set(double)
Set the value of the function.
Definition: Value.h:174
string mw_dir_
Definition: MetaD.cpp:235
bool checkNeedsGradients() const
Check if the action needs gradient.
Definition: MetaD.cpp:263
void getDomain(std::string &, std::string &) const
Get the domain of the quantity.
Definition: Value.cpp:99
void parse(const std::string &key, T &t)
Parse one keyword as generic type.
Definition: Action.h:273
This class holds the keywords and their documentation.
Definition: Keywords.h:36
std::string gridreadfilename_
Definition: MetaD.cpp:223
FileBase & flush()
Flushes the file to disk.
Definition: FileBase.cpp:70
int Get_rank() const
Obtain the rank of the present process.
IFile & open(const std::string &name)
Opens the file.
Definition: IFile.cpp:90
This class is used to bring the relevant information to the Action constructor.
Definition: Action.h:41
std::vector< double > getDx() const
get bin size
Definition: Grid.cpp:136
virtual double getValue(unsigned index) const
get grid value
Definition: Grid.cpp:355
std::vector< Value * > & getArguments()
Returns an array of pointers to the arguments.
void mult(const Matrix< T > &A, const Matrix< T > &B, Matrix< T > &C)
Definition: Matrix.h:165
OFile & link(OFile &)
Allows linking this OFile to another one.
Definition: OFile.cpp:71
virtual void addValueAndDerivatives(unsigned index, double value, std::vector< double > &der)
add to grid value and derivatives
Definition: Grid.cpp:489
int printf(const char *fmt,...)
Formatted output with explicit format - a la printf.
Definition: OFile.cpp:82
void close()
Closes the file Should be used only for explicitely opened files.
Definition: FileBase.cpp:140
const std::string & getName() const
Returns the name.
Definition: Action.h:268
Grid * ExtGrid_
Definition: MetaD.cpp:221
double evaluateGaussian(const vector< double > &, const Gaussian &, double *der=NULL)
Definition: MetaD.cpp:775
vector< double > invsigma
Definition: MetaD.cpp:208
bool getExchangeStep() const
Check if we are on an exchange step.
Definition: Action.cpp:217
double getBiasAndDerivatives(const vector< double > &, double *der=NULL)
Definition: MetaD.cpp:740
void parseVector(const std::string &key, std::vector< T > &t)
Parse one keyword as std::vector.
Definition: Action.h:311
double getHeight(const vector< double > &)
Definition: MetaD.cpp:849
std::string fmt
Definition: MetaD.cpp:255
VectorGeneric< n > delta(const VectorGeneric< n > &v1, const VectorGeneric< n > &v2)
Definition: Vector.h:262
vector< double > sigma0_
Definition: MetaD.cpp:214
std::string gridfilename_
Definition: MetaD.cpp:223
Class for input files.
Definition: IFile.h:40
void setOutputForce(int i, double g)
Definition: Bias.h:56
vector< double > sigma0min_
Definition: MetaD.cpp:215
int diagMat(const Matrix< T > &A, std::vector< double > &eigenvals, Matrix< double > &eigenvecs)
Definition: Matrix.h:203
double getArgument(const unsigned n) const
Returns the value of an argument.
void finiteDifferenceGaussian(const vector< double > &, const Gaussian &)
Definition: MetaD.cpp:959
Gaussian(const vector< double > &center, const vector< double > &sigma, double height, bool multivariate)
Definition: MetaD.cpp:209
static int dummy
Definition: Plumed.c:80
virtual void writeToFile(OFile &)
dump grid on file
Definition: Grid.cpp:531
IFile & scanField(const std::string &, double &)
Read a double field.
Definition: IFile.cpp:121
long int getStep() const
Return the present timestep.
Definition: Action.cpp:169
Class for output files.
Definition: OFile.h:84
bool FileExist(const std::string &path)
Check if the file exists.
Definition: FileBase.cpp:118
std::vector< std::string > getMax() const
get upper boundary
Definition: Grid.cpp:132
double RandU01()
Definition: Random.cpp:56
void writeGaussian(const Gaussian &, OFile &)
Definition: MetaD.cpp:603
OFile & printField(const std::string &, double)
Set the value of a double precision field.
Definition: OFile.cpp:145
This is the abstract base class to use for implementing new simulation biases, within it there is inf...
Definition: Bias.h:40
Main plumed object.
Definition: Plumed.h:201
bool isPeriodic() const
Check if the value is periodic.
Definition: Value.cpp:75
std::vector< std::string > getMin() const
get lower boundary
Definition: Grid.cpp:128
std::vector< unsigned > getNbin() const
get number of bins
Definition: Grid.cpp:150
#define PLUMED_BIAS_INIT(ao)
Definition: Bias.h:29
OFile & clearFields()
Resets the list of fields.
Definition: OFile.cpp:128
void readGaussians(IFile *)
Definition: MetaD.cpp:559
std::vector< double > getPoint(unsigned index) const
Definition: Grid.cpp:222
Value * getPntrToComponent(int i)
Return a pointer to the component by index.
std::vector< double > getInverseMatrix() const
Calculate the matrix of (dcv_i/dx)*(dcv_j/dx)^-1 that is needed for the metrics in metadynamics...
void update(bool nowAddAHill)
update the average (always for diffusion) or calculate the geom covariance ( only when do_when_zero i...
Definition: FlexibleBin.cpp:66
int Get_size() const
Obtain the number of processes.
vector< string > ifilesnames
Definition: MetaD.cpp:239
vector< Gaussian > hills_
Definition: MetaD.cpp:217
std::vector< unsigned > getNeighbors(unsigned index, const std::vector< unsigned > &neigh) const
get neighbors
Definition: Grid.cpp:300
unsigned getNumberOfArguments() const
Returns the number of arguments.
OFile & open(const std::string &name)
Opens the file using automatic append/backup.
Definition: OFile.cpp:264
void Sum(T *, int)
Wrapper for MPI_Allreduce with MPI_SUM.
Definition: Communicator.h:124
OFile & setupPrintValue(Value *val)
Used to setup printing of values.
Definition: OFile.cpp:172
vector< IFile * > ifiles
Definition: MetaD.cpp:238
bool scanOneHill(IFile *ifile, vector< Value > &v, vector< double > &center, vector< double > &sigma, double &height, bool &multivariate)
takes a pointer to the file and a template string with values v and gives back the next center...
Definition: MetaD.cpp:987
static Grid * create(const std::string &, std::vector< Value * >, IFile &, bool, bool, bool)
read grid from file
Definition: Grid.cpp:573
void update()
Update.
Definition: MetaD.cpp:884
std::vector< bool > getIsPeriodic() const
get if periodic
Definition: Grid.cpp:146