Line data Source code
1 : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 : Copyright (c) 2016-2021 The VES code team
3 : (see the PEOPLE-VES file at the root of this folder for a list of names)
4 :
5 : See http://www.ves-code.org for more information.
6 :
7 : This file is part of VES code module.
8 :
9 : The VES code module 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 : The VES code module 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 the VES code module. If not, see <http://www.gnu.org/licenses/>.
21 : +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
22 :
23 : #include "bias/Bias.h"
24 : #include "core/PlumedMain.h"
25 : #include "core/ActionRegister.h"
26 : #include "tools/Communicator.h"
27 : #include "tools/Grid.h"
28 : #include "tools/File.h"
29 :
30 : namespace PLMD {
31 : namespace ves {
32 :
33 : //+PLUMEDOC VES_BIAS VES_DELTA_F
34 : /*
35 : Implementation of VES Delta F method
36 :
37 : Implementation of VES$\Delta F$ method discussed in the paper cited below (step two only).
38 :
39 : !!! warning ""
40 :
41 : Notice that this is a stand-alone bias Action, it does not need any of the other VES module components
42 :
43 : First you should create some estimate of the local free energy basins of your system,
44 : using e.g. multiple [METAD](METAD.md) short runs, and combining them with the [sum_hills](sum_hills.md) utility.
45 : Once you have them, you can use this bias Action to perform the VES optimization part of the method.
46 :
47 : These $N+1$ local basins are used to model the global free energy.
48 : In particular, given the conditional probabilities $P(\mathbf{s}|i)\propto e^{-\beta F_i(\mathbf{s})}$
49 : and the probabilities of being in a given basin $P_i$, we can write:
50 :
51 : $$
52 : e^{-\beta F(\mathbf{s})}\propto P(\mathbf{s})=\sum_{i=0}^N P(\mathbf{s}|i)P_i \, .
53 : $$
54 :
55 : We use this free energy model and the chosen bias factor $\gamma$ to build the bias potential:
56 : $V(\mathbf{s})=-(1-1/\gamma)F(\mathbf{s})$.
57 : Or, more explicitly:
58 : $$
59 : V(\mathbf{s})=(1-1/\gamma)\frac{1}{\beta}\log\left[e^{-\beta F_0(\mathbf{s})}
60 : +\sum_{i=1}^{N} e^{-\beta F_i(\mathbf{s})} e^{-\beta \alpha_i}\right] \, ,
61 : $$
62 : where the parameters $\boldsymbol{\alpha}$ are the $N$ free energy differences (see below) from the $F_0$ basin.
63 :
64 : By default the $F_i(\mathbf{s})$ are shifted so that $\min[F_i(\mathbf{s})]=0$ for all $i=\{0,...,N\}$.
65 : In this case the optimization parameters $\alpha_i$ are the difference in height between the minima of the basins.
66 : Using the keyword `NORMALIZE`, you can also decide to normalize the local free energies so that
67 : $\int d\mathbf{s}\, e^{-\beta F_i(\mathbf{s})}=1$.
68 : In this case the parameters will represent not the difference in height (which depends on the chosen CVs),
69 : but the actual free energy difference, $\alpha_i=\Delta F_i$.
70 :
71 : However, as discussed in the paper cited below, a better estimate of $\Delta F_i$ should be obtained through the reweighting procedure.
72 :
73 : ## Examples
74 :
75 : The following performs the optimization of the free energy difference between two metastable basins:
76 :
77 : ```plumed
78 : #SETTINGS INPUTFILES=regtest/ves/rt-VesDeltaF/fesA.data,regtest/ves/rt-VesDeltaF/fesB.data
79 :
80 : cv: TORSION ATOMS=7,9,15,17
81 :
82 : ves: VES_DELTA_F ...
83 : ARG=cv
84 : TEMP=300
85 : FILE_F0=regtest/ves/rt-VesDeltaF/fesA.data
86 : FILE_F1=regtest/ves/rt-VesDeltaF/fesB.data
87 : BIASFACTOR=10.0
88 : M_STEP=0.1
89 : AV_STRIDE=500
90 : PRINT_STRIDE=100
91 : ...
92 : PRINT FMT=%g STRIDE=500 FILE=Colvar.data ARG=cv,ves.bias,ves.rct
93 : ```
94 :
95 : The local FES files can be obtained as described in Sec. 4.2 of the paper cited below, i.e. for example:
96 : - run 4 independent metad runs, all starting from basin A, and kill them as soon as they make the first transition (see e.g. [COMMITTOR](COMMITTOR.md))
97 : - `cat HILLS* > all_HILLS`
98 : - `plumed sum_hills --hills all_HILLS --outfile all_fesA.dat --mintozero --min 0 --max 1 --bin 100`
99 : - `awk -v n_rep=4 '{if($1!="#!" && $1!="") {for(i=1+(NF-1)/2; i<=NF; i++) $i/=n_rep;} print $0}' all_fesA.dat > fesA.data`
100 :
101 : */
102 : //+ENDPLUMEDOC
103 :
104 : class VesDeltaF : public bias::Bias {
105 :
106 : private:
107 : double beta_;
108 : unsigned NumParallel_;
109 : unsigned rank_;
110 : unsigned NumWalkers_;
111 : bool isFirstStep_;
112 : bool afterCalculate_;
113 :
114 : //prob
115 : double tot_prob_;
116 : std::vector<double> prob_;
117 : std::vector< std::vector<double> > der_prob_;
118 :
119 : //local basins
120 : std::vector< std::unique_ptr<Grid> > grid_p_; //pointers because of GridBase::create
121 : std::vector<double> norm_;
122 :
123 : //optimizer-related stuff
124 : long long unsigned mean_counter_;
125 : unsigned mean_weight_tau_;
126 : unsigned alpha_size_;
127 : unsigned sym_alpha_size_;
128 : std::vector<double> mean_alpha_;
129 : std::vector<double> inst_alpha_;
130 : std::vector<double> past_increment2_;
131 : double minimization_step_;
132 : bool damping_off_;
133 : //'tg' -> 'target distribution'
134 : double inv_gamma_;
135 : unsigned tg_counter_;
136 : unsigned tg_stride_;
137 : std::vector<double> tg_dV_dAlpha_;
138 : std::vector<double> tg_d2V_dAlpha2_;
139 : //'av' -> 'ensemble average'
140 : unsigned av_counter_;
141 : unsigned av_stride_;
142 : std::vector<double> av_dV_dAlpha_;
143 : std::vector<double> av_dV_dAlpha_prod_;
144 : std::vector<double> av_d2V_dAlpha2_;
145 : //printing
146 : unsigned print_stride_;
147 : OFile alphaOfile_;
148 : //other
149 : std::vector<double> exp_alpha_;
150 : std::vector<double> prev_exp_alpha_;
151 : double work_;
152 :
153 : //functions
154 : void update_alpha();
155 : void update_tg_and_rct();
156 : inline unsigned get_index(const unsigned, const unsigned) const;
157 :
158 : public:
159 : explicit VesDeltaF(const ActionOptions&);
160 : void calculate() override;
161 : void update() override;
162 : static void registerKeywords(Keywords& keys);
163 : };
164 :
165 : PLUMED_REGISTER_ACTION(VesDeltaF,"VES_DELTA_F")
166 :
167 8 : void VesDeltaF::registerKeywords(Keywords& keys) {
168 8 : Bias::registerKeywords(keys);
169 8 : keys.add("optional","TEMP","temperature is compulsory, but it can be sometimes fetched from the MD engine");
170 : //local free energies
171 8 : keys.add("numbered","FILE_F","names of files containing local free energies and derivatives. "
172 : "The first one, FILE_F0, is used as reference for all the free energy differences.");
173 16 : keys.reset_style("FILE_F","compulsory");
174 8 : keys.addFlag("NORMALIZE",false,"normalize all local free energies so that alpha will be (approx) Delta F");
175 8 : keys.addFlag("NO_MINTOZERO",false,"leave local free energies as provided, without shifting them to zero min");
176 : //target distribution
177 8 : keys.add("compulsory","BIASFACTOR","0","the gamma bias factor used for well-tempered target p(s)."
178 : " Set to 0 for non-tempered flat target");
179 8 : keys.add("optional","TG_STRIDE","( default=1 ) number of AV_STRIDE between updates"
180 : " of target p(s) and reweighing factor c(t)");
181 : //optimization
182 8 : keys.add("compulsory","M_STEP","1.0","the mu step used for the Omega functional minimization");
183 8 : keys.add("compulsory","AV_STRIDE","500","number of simulation steps between alpha updates");
184 8 : keys.add("optional","TAU_MEAN","exponentially decaying average for alpha (rescaled using AV_STRIDE)."
185 : " Should be used only in very specific cases");
186 8 : keys.add("optional","INITIAL_ALPHA","( default=0 ) an initial guess for the bias potential parameter alpha");
187 8 : keys.addFlag("DAMPING_OFF",false,"do not use an AdaGrad-like term to rescale M_STEP");
188 : //output parameters file
189 8 : keys.add("compulsory","ALPHA_FILE","ALPHA","file name for output minimization parameters");
190 8 : keys.add("optional","PRINT_STRIDE","( default=10 ) stride for printing to ALPHA_FILE");
191 8 : keys.add("optional","FMT","specify format for ALPHA_FILE");
192 : //debug flags
193 8 : keys.addFlag("SERIAL",false,"perform the calculation in serial even if multiple tasks are available");
194 8 : keys.addFlag("MULTIPLE_WALKERS",false,"use multiple walkers connected via MPI for the optimization");
195 8 : keys.use("RESTART");
196 :
197 : //output components
198 16 : keys.addOutputComponent("rct","default","scalar","the reweighting factor c(t)");
199 16 : keys.addOutputComponent("work","default","scalar","the work done by the bias in one AV_STRIDE");
200 8 : keys.addDOI("10.1021/acs.jctc.9b00032");
201 8 : }
202 :
203 4 : VesDeltaF::VesDeltaF(const ActionOptions&ao)
204 : : PLUMED_BIAS_INIT(ao)
205 4 : , isFirstStep_(true)
206 4 : , afterCalculate_(false)
207 4 : , mean_counter_(0)
208 4 : , av_counter_(0)
209 4 : , work_(0) {
210 : //set beta
211 4 : const double Kb=getKBoltzmann();
212 4 : double KbT=getkBT();
213 4 : plumed_massert(KbT>0,"your MD engine does not pass the temperature to plumed, you must specify it using TEMP");
214 4 : beta_=1.0/KbT;
215 :
216 : //initialize probability grids using local free energies
217 : bool spline=true;
218 : bool sparsegrid=false;
219 4 : std::string funcl="file.free"; //typical name given by sum_hills
220 :
221 4 : std::vector<std::string> fes_names;
222 8 : for(unsigned n=0;; n++) { //NB: here we start from FILE_F0 not from FILE_F1
223 : std::string filename;
224 24 : if(!parseNumbered("FILE_F",n,filename)) {
225 : break;
226 : }
227 8 : fes_names.push_back(filename);
228 8 : IFile gridfile;
229 8 : gridfile.open(filename);
230 8 : auto g=GridBase::create(funcl,getArguments(),gridfile,sparsegrid,spline,true);
231 : // we assume this cannot be sparse. in case we want it to be sparse, some of the methods
232 : // that are available only in Grid should be ported to GridBase
233 8 : auto gg=dynamic_cast<Grid*>(g.get());
234 : // if this throws, g is deleted
235 8 : plumed_assert(gg);
236 : // release ownership in order to transfer it to emplaced pointer
237 : // cppcheck-suppress ignoredReturnValue
238 : g.release();
239 8 : grid_p_.emplace_back(gg);
240 16 : }
241 4 : plumed_massert(grid_p_.size()>1,"at least 2 basins must be defined, starting from FILE_F0");
242 4 : alpha_size_=grid_p_.size()-1;
243 4 : sym_alpha_size_=alpha_size_*(alpha_size_+1)/2; //useful for symmetric matrix [alpha_size_]x[alpha_size_]
244 : //check for consistency with first local free energy
245 8 : for(unsigned n=1; n<grid_p_.size(); n++) {
246 12 : std::string error_tag="FILE_F"+std::to_string(n)+" '"+fes_names[n]+"' not compatible with reference one, FILE_F0";
247 4 : plumed_massert(grid_p_[n]->getSize()==grid_p_[0]->getSize(),error_tag);
248 4 : plumed_massert(grid_p_[n]->getMin()==grid_p_[0]->getMin(),error_tag);
249 4 : plumed_massert(grid_p_[n]->getMax()==grid_p_[0]->getMax(),error_tag);
250 4 : plumed_massert(grid_p_[n]->getBinVolume()==grid_p_[0]->getBinVolume(),error_tag);
251 : }
252 :
253 4 : bool no_mintozero=false;
254 4 : parseFlag("NO_MINTOZERO",no_mintozero);
255 4 : if(!no_mintozero) {
256 6 : for(unsigned n=0; n<grid_p_.size(); n++) {
257 4 : grid_p_[n]->setMinToZero();
258 : }
259 : }
260 4 : bool normalize=false;
261 4 : parseFlag("NORMALIZE",normalize);
262 4 : norm_.resize(grid_p_.size(),0);
263 4 : std::vector<double> c_norm(grid_p_.size());
264 : //convert the FESs to probability distributions
265 : //NB: the spline interpolation will be done on the probability distributions, not on the given FESs
266 : const unsigned ncv=getNumberOfArguments(); //just for ease
267 12 : for(unsigned n=0; n<grid_p_.size(); n++) {
268 808 : for(Grid::index_t t=0; t<grid_p_[n]->getSize(); t++) {
269 800 : std::vector<double> der(ncv);
270 800 : const double val=std::exp(-beta_*grid_p_[n]->getValueAndDerivatives(t,der));
271 1600 : for(unsigned s=0; s<ncv; s++) {
272 800 : der[s]*=-beta_*val;
273 : }
274 800 : grid_p_[n]->setValueAndDerivatives(t,val,der);
275 800 : norm_[n]+=val;
276 : }
277 8 : c_norm[n]=1./beta_*std::log(norm_[n]);
278 8 : if(normalize) {
279 4 : grid_p_[n]->scaleAllValuesAndDerivatives(1./norm_[n]);
280 4 : norm_[n]=1;
281 : }
282 : }
283 :
284 : //get target
285 4 : double biasfactor=0;
286 4 : parse("BIASFACTOR",biasfactor);
287 4 : plumed_massert(biasfactor==0 || biasfactor>1,"BIASFACTOR must be zero (for uniform target) or greater than one");
288 4 : if(biasfactor==0) {
289 2 : inv_gamma_=0;
290 : } else {
291 2 : inv_gamma_=1./biasfactor;
292 : }
293 4 : tg_counter_=0;
294 4 : tg_stride_=1;
295 4 : parse("TG_STRIDE",tg_stride_);
296 4 : tg_dV_dAlpha_.resize(alpha_size_,0);
297 4 : tg_d2V_dAlpha2_.resize(sym_alpha_size_,0);
298 :
299 : //setup optimization stuff
300 4 : minimization_step_=1;
301 4 : parse("M_STEP",minimization_step_);
302 :
303 4 : av_stride_=500;
304 4 : parse("AV_STRIDE",av_stride_);
305 4 : av_dV_dAlpha_.resize(alpha_size_,0);
306 4 : av_dV_dAlpha_prod_.resize(sym_alpha_size_,0);
307 4 : av_d2V_dAlpha2_.resize(sym_alpha_size_,0);
308 :
309 4 : mean_weight_tau_=0;
310 4 : parse("TAU_MEAN",mean_weight_tau_);
311 4 : if(mean_weight_tau_!=1) { //set it to 1 for basic SGD
312 4 : plumed_massert((mean_weight_tau_==0 || mean_weight_tau_>av_stride_),"TAU_MEAN is rescaled with AV_STRIDE, so it has to be greater");
313 4 : mean_weight_tau_/=av_stride_; //this way you can look at the number of simulation steps to choose TAU_MEAN
314 : }
315 :
316 8 : parseVector("INITIAL_ALPHA",mean_alpha_);
317 4 : if(mean_alpha_.size()>0) {
318 2 : plumed_massert(mean_alpha_.size()==alpha_size_,"provide one INITIAL_ALPHA for each basin beyond the first one");
319 : } else {
320 2 : mean_alpha_.resize(alpha_size_,0);
321 : }
322 4 : inst_alpha_=mean_alpha_;
323 4 : exp_alpha_.resize(alpha_size_);
324 8 : for(unsigned i=0; i<alpha_size_; i++) {
325 4 : exp_alpha_[i]=std::exp(-beta_*mean_alpha_[i]);
326 : }
327 4 : prev_exp_alpha_=exp_alpha_;
328 :
329 4 : damping_off_=false;
330 4 : parseFlag("DAMPING_OFF",damping_off_);
331 4 : if(damping_off_) {
332 2 : past_increment2_.resize(alpha_size_,1);
333 : } else {
334 2 : past_increment2_.resize(alpha_size_,0);
335 : }
336 :
337 : //file printing options
338 4 : std::string alphaFileName("ALPHA");
339 4 : parse("ALPHA_FILE",alphaFileName);
340 4 : print_stride_=10;
341 8 : parse("PRINT_STRIDE",print_stride_);
342 : std::string fmt;
343 4 : parse("FMT",fmt);
344 :
345 : //other flags, mainly for debugging
346 4 : NumParallel_=comm.Get_size();
347 4 : rank_=comm.Get_rank();
348 4 : bool serial=false;
349 4 : parseFlag("SERIAL",serial);
350 4 : if(serial) {
351 2 : log.printf(" -- SERIAL: running without loop parallelization\n");
352 2 : NumParallel_=1;
353 2 : rank_=0;
354 : }
355 :
356 4 : bool multiple_walkers=false;
357 4 : parseFlag("MULTIPLE_WALKERS",multiple_walkers);
358 4 : if(!multiple_walkers) {
359 2 : NumWalkers_=1;
360 : } else {
361 2 : NumWalkers_=getNumberOfReplicas();
362 : }
363 :
364 4 : checkRead();
365 :
366 : //restart if needed
367 4 : if(getRestart()) {
368 2 : IFile ifile;
369 2 : ifile.link(*this);
370 2 : if(NumWalkers_>1) {
371 4 : ifile.enforceSuffix("");
372 : }
373 2 : if(ifile.FileExist(alphaFileName)) {
374 2 : log.printf(" Restarting from: %s\n",alphaFileName.c_str());
375 2 : log.printf(" all options (also PRINT_STRIDE) must be consistent!\n");
376 2 : log.printf(" any INITIAL_ALPHA will be overwritten\n");
377 2 : ifile.open(alphaFileName);
378 : double time;
379 2 : std::vector<double> damping(alpha_size_);
380 20 : while(ifile.scanField("time",time)) { //room for improvements: only last line is important
381 16 : for(unsigned i=0; i<alpha_size_; i++) {
382 8 : const std::string index(std::to_string(i+1));
383 8 : prev_exp_alpha_[i]=std::exp(-beta_*mean_alpha_[i]);
384 16 : ifile.scanField("alpha_"+index,mean_alpha_[i]);
385 16 : ifile.scanField("auxiliary_"+index,inst_alpha_[i]);
386 16 : ifile.scanField("damping_"+index,damping[i]);
387 : }
388 8 : ifile.scanField();
389 8 : mean_counter_+=print_stride_;
390 : }
391 4 : for(unsigned i=0; i<alpha_size_; i++) {
392 2 : exp_alpha_[i]=std::exp(-beta_*mean_alpha_[i]);
393 2 : past_increment2_[i]=damping[i]*damping[i];
394 : }
395 : //sync all walkers and treads. Not sure is mandatory but is no harm
396 2 : comm.Barrier();
397 2 : if(comm.Get_rank()==0) {
398 2 : multi_sim_comm.Barrier();
399 : }
400 : } else {
401 0 : log.printf(" -- WARNING: restart requested, but no '%s' file found!\n",alphaFileName.c_str());
402 : }
403 2 : }
404 :
405 : //setup output file with Alpha values
406 4 : alphaOfile_.link(*this);
407 4 : if(NumWalkers_>1) {
408 2 : if(comm.Get_rank()==0 && multi_sim_comm.Get_rank()>0) {
409 : alphaFileName="/dev/null"; //only first walker writes on file
410 : }
411 4 : alphaOfile_.enforceSuffix("");
412 : }
413 4 : alphaOfile_.open(alphaFileName);
414 4 : if(fmt.length()>0) {
415 8 : alphaOfile_.fmtField(" "+fmt);
416 : }
417 :
418 : //add other output components
419 8 : addComponent("rct");
420 8 : componentIsNotPeriodic("rct");
421 8 : addComponent("work");
422 4 : componentIsNotPeriodic("work");
423 :
424 : //print some info
425 4 : log.printf(" Temperature T: %g\n",1./(Kb*beta_));
426 4 : log.printf(" Beta (1/Kb*T): %g\n",beta_);
427 4 : log.printf(" Local free energy basins files and normalization constants:\n");
428 12 : for(unsigned n=0; n<grid_p_.size(); n++) {
429 8 : log.printf(" F_%d filename: %s c_%d=%g\n",n,fes_names[n].c_str(),n,c_norm[n]);
430 : }
431 4 : if(no_mintozero) {
432 2 : log.printf(" -- NO_MINTOZERO: local free energies are not shifted to be zero at minimum\n");
433 : }
434 4 : if(normalize) {
435 2 : log.printf(" -- NORMALIZE: F_n+=c_n, alpha=DeltaF\n");
436 : }
437 4 : log.printf(" Using target distribution with 1/gamma = %g\n",inv_gamma_);
438 4 : log.printf(" and updated with stride %d\n",tg_stride_);
439 4 : log.printf(" Step for the minimization algorithm: %g\n",minimization_step_);
440 4 : log.printf(" Stride for the ensemble average: %d\n",av_stride_);
441 4 : if(mean_weight_tau_>1) {
442 2 : log.printf(" Exponentially decaying average with weight=tau/av_stride=%d\n",mean_weight_tau_);
443 : }
444 4 : if(mean_weight_tau_==1) {
445 0 : log.printf(" +++ WARNING +++ setting TAU_MEAN=1 is equivalent to use simple SGD, without mean alpha nor hessian contribution\n");
446 : }
447 4 : log.printf(" Initial guess for alpha:\n");
448 8 : for(unsigned i=0; i<alpha_size_; i++) {
449 4 : log.printf(" alpha_%d = %g\n",i+1,mean_alpha_[i]);
450 : }
451 4 : if(damping_off_) {
452 2 : log.printf(" -- DAMPING_OFF: the minimization step will NOT become smaller as the simulation goes on\n");
453 : }
454 4 : log.printf(" Printing on file %s with stride %d\n",alphaFileName.c_str(),print_stride_);
455 4 : if(serial) {
456 2 : log.printf(" -- SERIAL: running without loop parallelization\n");
457 : }
458 4 : if(NumParallel_>1) {
459 2 : log.printf(" Using multiple threads per simulation: %d\n",NumParallel_);
460 : }
461 4 : if(multiple_walkers) {
462 2 : log.printf(" -- MULTIPLE_WALKERS: multiple simulations will combine statistics for the optimization\n");
463 2 : if(NumWalkers_>1) {
464 2 : log.printf(" number of walkers: %d\n",NumWalkers_);
465 2 : log.printf(" walker rank: %d\n",multi_sim_comm.Get_rank()); //only comm.Get_rank()=0 prints, so this is fine
466 : } else {
467 0 : log.printf(" +++ WARNING +++ only one replica found: are you sure you are running MPI-connected simulations?\n");
468 : }
469 : }
470 4 : log.printf(" Bibliography ");
471 4 : log<<plumed.cite("Invernizzi and Parrinello, J. Chem. Theory Comput. 15, 2187-2194 (2019)");
472 4 : log<<plumed.cite("Valsson and Parrinello, Phys. Rev. Lett. 113, 090601 (2014)");
473 4 : if(inv_gamma_>0) {
474 4 : log<<plumed.cite("Valsson and Parrinello, J. Chem. Theory Comput. 11, 1996-2002 (2015)");
475 : }
476 :
477 : //last initializations
478 4 : prob_.resize(grid_p_.size());
479 4 : der_prob_.resize(grid_p_.size(),std::vector<double>(getNumberOfArguments()));
480 4 : update_tg_and_rct();
481 8 : }
482 :
483 804 : void VesDeltaF::calculate() {
484 : //get CVs
485 804 : const unsigned ncv=getNumberOfArguments(); //just for ease
486 804 : std::vector<double> cv(ncv);
487 1608 : for(unsigned s=0; s<ncv; s++) {
488 804 : cv[s]=getArgument(s);
489 : }
490 : //get probabilities for each basin, and total one
491 2412 : for(unsigned n=0; n<grid_p_.size(); n++) {
492 1608 : prob_[n]=grid_p_[n]->getValueAndDerivatives(cv,der_prob_[n]);
493 : }
494 804 : tot_prob_=prob_[0];
495 1608 : for(unsigned i=0; i<alpha_size_; i++) {
496 804 : tot_prob_+=prob_[i+1]*exp_alpha_[i];
497 : }
498 :
499 : //update bias and forces: V=-(1-inv_gamma_)*fes
500 804 : setBias((1-inv_gamma_)/beta_*std::log(tot_prob_));
501 1608 : for(unsigned s=0; s<ncv; s++) {
502 804 : double dProb_dCV_s=der_prob_[0][s];
503 1608 : for(unsigned i=0; i<alpha_size_; i++) {
504 804 : dProb_dCV_s+=der_prob_[i+1][s]*exp_alpha_[i];
505 : }
506 804 : setOutputForce(s,-(1-inv_gamma_)/beta_/tot_prob_*dProb_dCV_s);
507 : }
508 804 : afterCalculate_=true;
509 804 : }
510 :
511 804 : void VesDeltaF::update() {
512 : //skip first step to sync getTime() and av_counter_, as in METAD
513 804 : if(isFirstStep_) {
514 4 : isFirstStep_=false;
515 4 : return;
516 : }
517 800 : plumed_massert(afterCalculate_,"VesDeltaF::update() must be called after VesDeltaF::calculate() to work properly");
518 800 : afterCalculate_=false;
519 :
520 : //calculate derivatives for ensemble averages
521 800 : std::vector<double> dV_dAlpha(alpha_size_);
522 800 : std::vector<double> d2V_dAlpha2(sym_alpha_size_);
523 1600 : for(unsigned i=0; i<alpha_size_; i++) {
524 800 : dV_dAlpha[i]=-(1-inv_gamma_)/tot_prob_*prob_[i+1]*exp_alpha_[i];
525 : }
526 1600 : for(unsigned i=0; i<alpha_size_; i++) {
527 800 : d2V_dAlpha2[get_index(i,i)]=-beta_*dV_dAlpha[i];
528 1600 : for(unsigned j=i; j<alpha_size_; j++) {
529 800 : d2V_dAlpha2[get_index(i,j)]-=beta_/(1-inv_gamma_)*dV_dAlpha[i]*dV_dAlpha[j];
530 : }
531 : }
532 : //update ensemble averages
533 800 : av_counter_++;
534 1600 : for(unsigned i=0; i<alpha_size_; i++) {
535 800 : av_dV_dAlpha_[i]+=(dV_dAlpha[i]-av_dV_dAlpha_[i])/av_counter_;
536 1600 : for(unsigned j=i; j<alpha_size_; j++) {
537 800 : const unsigned ij=get_index(i,j);
538 800 : av_dV_dAlpha_prod_[ij]+=(dV_dAlpha[i]*dV_dAlpha[j]-av_dV_dAlpha_prod_[ij])/av_counter_;
539 800 : av_d2V_dAlpha2_[ij]+=(d2V_dAlpha2[ij]-av_d2V_dAlpha2_[ij])/av_counter_;
540 : }
541 : }
542 : //update work
543 800 : double prev_tot_prob=prob_[0];
544 1600 : for(unsigned i=0; i<alpha_size_; i++) {
545 800 : prev_tot_prob+=prob_[i+1]*prev_exp_alpha_[i];
546 : }
547 800 : work_+=(1-inv_gamma_)/beta_*std::log(tot_prob_/prev_tot_prob);
548 :
549 : //update coefficients
550 800 : if(av_counter_==av_stride_) {
551 16 : update_alpha();
552 16 : tg_counter_++;
553 16 : if(tg_counter_==tg_stride_) {
554 12 : update_tg_and_rct();
555 12 : tg_counter_=0;
556 : }
557 : //reset the ensemble averages
558 16 : av_counter_=0;
559 : std::fill(av_dV_dAlpha_.begin(),av_dV_dAlpha_.end(),0);
560 : std::fill(av_dV_dAlpha_prod_.begin(),av_dV_dAlpha_prod_.end(),0);
561 : std::fill(av_d2V_dAlpha2_.begin(),av_d2V_dAlpha2_.end(),0);
562 : }
563 : }
564 :
565 16 : void VesDeltaF::update_tg_and_rct() {
566 : //calculate target averages
567 16 : double Z_0=norm_[0];
568 32 : for(unsigned i=0; i<alpha_size_; i++) {
569 16 : Z_0+=norm_[i+1]*exp_alpha_[i];
570 : }
571 16 : double Z_tg=0;
572 : std::fill(tg_dV_dAlpha_.begin(),tg_dV_dAlpha_.end(),0);
573 : std::fill(tg_d2V_dAlpha2_.begin(),tg_d2V_dAlpha2_.end(),0);
574 1116 : for(Grid::index_t t=rank_; t<grid_p_[0]->getSize(); t+=NumParallel_) {
575 : //TODO can we recycle some code?
576 1100 : std::vector<double> prob(grid_p_.size());
577 3300 : for(unsigned n=0; n<grid_p_.size(); n++) {
578 2200 : prob[n]=grid_p_[n]->getValue(t);
579 : }
580 1100 : double tot_prob=prob[0];
581 2200 : for(unsigned i=0; i<alpha_size_; i++) {
582 1100 : tot_prob+=prob[i+1]*exp_alpha_[i];
583 : }
584 1100 : std::vector<double> dV_dAlpha(alpha_size_);
585 1100 : std::vector<double> d2V_dAlpha2(sym_alpha_size_);
586 2200 : for(unsigned i=0; i<alpha_size_; i++) {
587 1100 : dV_dAlpha[i]=-(1-inv_gamma_)/tot_prob*prob[i+1]*exp_alpha_[i];
588 : }
589 2200 : for(unsigned i=0; i<alpha_size_; i++) {
590 1100 : d2V_dAlpha2[get_index(i,i)]=-beta_*dV_dAlpha[i];
591 2200 : for(unsigned j=i; j<alpha_size_; j++) {
592 1100 : d2V_dAlpha2[get_index(i,j)]-=beta_/(1-inv_gamma_)*dV_dAlpha[i]*dV_dAlpha[j];
593 : }
594 : }
595 1100 : const double unnorm_tg_p=std::pow(tot_prob,inv_gamma_);
596 1100 : Z_tg+=unnorm_tg_p;
597 2200 : for(unsigned i=0; i<alpha_size_; i++) {
598 1100 : tg_dV_dAlpha_[i]+=unnorm_tg_p*dV_dAlpha[i];
599 : }
600 2200 : for(unsigned ij=0; ij<sym_alpha_size_; ij++) {
601 1100 : tg_d2V_dAlpha2_[ij]+=unnorm_tg_p*d2V_dAlpha2[ij];
602 : }
603 : }
604 16 : if(NumParallel_>1) {
605 10 : comm.Sum(Z_tg);
606 10 : comm.Sum(tg_dV_dAlpha_);
607 10 : comm.Sum(tg_d2V_dAlpha2_);
608 : }
609 32 : for(unsigned i=0; i<alpha_size_; i++) {
610 16 : tg_dV_dAlpha_[i]/=Z_tg;
611 : }
612 32 : for(unsigned ij=0; ij<sym_alpha_size_; ij++) {
613 16 : tg_d2V_dAlpha2_[ij]/=Z_tg;
614 : }
615 16 : getPntrToComponent("rct")->set(-1./beta_*std::log(Z_tg/Z_0)); //Z_tg is the best available estimate of Z_V
616 16 : }
617 :
618 16 : void VesDeltaF::update_alpha() {
619 : //combining the averages of multiple walkers
620 16 : if(NumWalkers_>1) {
621 8 : if(comm.Get_rank()==0) { //sum only once: in the first rank of each walker
622 8 : multi_sim_comm.Sum(av_dV_dAlpha_);
623 8 : multi_sim_comm.Sum(av_dV_dAlpha_prod_);
624 8 : multi_sim_comm.Sum(av_d2V_dAlpha2_);
625 16 : for(unsigned i=0; i<alpha_size_; i++) {
626 8 : av_dV_dAlpha_[i]/=NumWalkers_;
627 : }
628 16 : for(unsigned ij=0; ij<sym_alpha_size_; ij++) {
629 8 : av_dV_dAlpha_prod_[ij]/=NumWalkers_;
630 8 : av_d2V_dAlpha2_[ij]/=NumWalkers_;
631 : }
632 : }
633 8 : if(comm.Get_size()>1) { //if there are more ranks for each walker, everybody has to know
634 0 : comm.Bcast(av_dV_dAlpha_,0);
635 0 : comm.Bcast(av_dV_dAlpha_prod_,0);
636 0 : comm.Bcast(av_d2V_dAlpha2_,0);
637 : }
638 : }
639 : //set work and reset it
640 16 : getPntrToComponent("work")->set(work_);
641 16 : work_=0;
642 :
643 : //build the gradient and the Hessian of the functional
644 16 : std::vector<double> grad_omega(alpha_size_);
645 16 : std::vector<double> hess_omega(sym_alpha_size_);
646 32 : for(unsigned i=0; i<alpha_size_; i++) {
647 16 : grad_omega[i]=tg_dV_dAlpha_[i]-av_dV_dAlpha_[i];
648 32 : for(unsigned j=i; j<alpha_size_; j++) {
649 16 : const unsigned ij=get_index(i,j);
650 16 : hess_omega[ij]=beta_*(av_dV_dAlpha_prod_[ij]-av_dV_dAlpha_[i]*av_dV_dAlpha_[j])+tg_d2V_dAlpha2_[ij]-av_d2V_dAlpha2_[ij];
651 : }
652 : }
653 : //calculate the increment and update alpha
654 16 : mean_counter_++;
655 : long long unsigned mean_weight=mean_counter_;
656 16 : if(mean_weight_tau_>0 && mean_weight_tau_<mean_counter_) {
657 : mean_weight=mean_weight_tau_;
658 : }
659 16 : std::vector<double> damping(alpha_size_);
660 32 : for(unsigned i=0; i<alpha_size_; i++) {
661 16 : double increment_i=grad_omega[i];
662 32 : for(unsigned j=0; j<alpha_size_; j++) {
663 16 : increment_i+=hess_omega[get_index(i,j)]*(inst_alpha_[j]-mean_alpha_[j]);
664 : }
665 16 : if(!damping_off_) {
666 8 : past_increment2_[i]+=increment_i*increment_i;
667 : }
668 16 : damping[i]=std::sqrt(past_increment2_[i]);
669 16 : prev_exp_alpha_[i]=std::exp(-beta_*mean_alpha_[i]);
670 16 : inst_alpha_[i]-=minimization_step_/damping[i]*increment_i;
671 16 : mean_alpha_[i]+=(inst_alpha_[i]-mean_alpha_[i])/mean_weight;
672 16 : exp_alpha_[i]=std::exp(-beta_*mean_alpha_[i]);
673 : }
674 :
675 : //update the Alpha file
676 16 : if(mean_counter_%print_stride_==0) {
677 16 : alphaOfile_.printField("time",getTime());
678 32 : for(unsigned i=0; i<alpha_size_; i++) {
679 16 : const std::string index(std::to_string(i+1));
680 32 : alphaOfile_.printField("alpha_"+index,mean_alpha_[i]);
681 32 : alphaOfile_.printField("auxiliary_"+index,inst_alpha_[i]);
682 32 : alphaOfile_.printField("damping_"+index,damping[i]);
683 : }
684 16 : alphaOfile_.printField();
685 : }
686 16 : }
687 :
688 : //mapping of a [alpha_size_]x[alpha_size_] symmetric matrix into a vector of size sym_alpha_size_, useful for the communicator
689 4632 : inline unsigned VesDeltaF::get_index(const unsigned i, const unsigned j) const {
690 4632 : if(i<=j) {
691 4632 : return j+i*(alpha_size_-1)-i*(i-1)/2;
692 : } else {
693 0 : return get_index(j,i);
694 : }
695 : }
696 :
697 : }
698 : }
|