Line data Source code
1 : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 : Copyright (c) 2017-2019 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.org for more information.
6 :
7 : This file is part of plumed, version 2.
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 : /*
23 :
24 : */
25 : #include "bias/Bias.h"
26 : #include "bias/ActionRegister.h"
27 : #include "core/PlumedMain.h"
28 : #include "core/Atoms.h"
29 : #include "core/Value.h"
30 : #include "tools/File.h"
31 : #include "tools/Random.h"
32 : #include <cmath>
33 : #include <ctime>
34 :
35 : using namespace std;
36 :
37 : namespace PLMD {
38 : namespace isdb {
39 :
40 : //+PLUMEDOC ISDB_BIAS RESCALE
41 : /*
42 : Rescales the value of an another action, being a Collective Variable or a Bias.
43 :
44 : The rescaling factor is determined by a parameter defined on a logarithmic grid of dimension NBIN in the range
45 : from 1 to MAX_RESCALE. The current value of the rescaling parameter is stored and shared across
46 : other actions using a \ref SELECTOR. A Monte Carlo procedure is used to update the value
47 : of the rescaling factor every MC_STRIDE steps of molecular dynamics. Well-tempered metadynamics, defined by the
48 : parameters W0 and BIASFACTOR, is used to enhance the sampling in the space of the rescaling factor.
49 : The well-tempered metadynamics bias potential is written to the file BFILE every BSTRIDE steps and read
50 : when restarting the simulation using the directive \ref RESTART.
51 :
52 : \note
53 : Additional arguments not to be rescaled, one for each bin in the rescaling parameter ladder, can be
54 : provided at the end of the ARG list. The number of such arguments is specified by the option NOT_RESCALED.
55 : These arguments will be not be rescaled, but they will be
56 : considered as bias potentials and used in the computation of the Metropolis
57 : acceptance probability when proposing a move in the rescaling parameter. See example below.
58 :
59 : \note
60 : If PLUMED is running in a multiple-replica framework (for example using the -multi option in GROMACS),
61 : the arguments will be summed across replicas, unless the NOT_SHARED option is used. Also, the value of the
62 : \ref SELECTOR will be shared and thus will be the same in all replicas.
63 :
64 : \par Examples
65 :
66 : In this example we use \ref RESCALE to implement a simulated-tempering like approach.
67 : The total potential energy of the system is rescaled by a parameter defined on a logarithmic grid
68 : of 5 bins in the range from 1 to 1.5.
69 : A well-tempered metadynamics bias potential is used to ensure diffusion in the space of the rescaling
70 : parameter.
71 :
72 : \plumedfile
73 : ene: ENERGY
74 :
75 : SELECTOR NAME=GAMMA VALUE=0
76 :
77 : RESCALE ...
78 : LABEL=res ARG=ene TEMP=300
79 : SELECTOR=GAMMA MAX_RESCALE=1.5 NBIN=5
80 : W0=1000 BIASFACTOR=100.0 BSTRIDE=2000 BFILE=bias.dat
81 : ...
82 :
83 : PRINT FILE=COLVAR ARG=* STRIDE=100
84 : \endplumedfile
85 :
86 : In this second example, we add to the simulated-tempering approach introduced above
87 : one Parallel Bias metadynamics simulation (see \ref PBMETAD) for each value of the rescaling parameter.
88 : At each moment of the simulation, only one of the \ref PBMETAD
89 : actions is activated, based on the current value of the associated \ref SELECTOR.
90 : The \ref PBMETAD bias potentials are not rescaled, but just used in the calculation of
91 : the Metropolis acceptance probability when proposing a move in the rescaling parameter.
92 :
93 : \plumedfile
94 : ene: ENERGY
95 : d: DISTANCE ATOMS=1,2
96 :
97 : SELECTOR NAME=GAMMA VALUE=0
98 :
99 : pbmetad0: PBMETAD ARG=d SELECTOR=GAMMA SELECTOR_ID=0 SIGMA=0.1 PACE=500 HEIGHT=1 BIASFACTOR=8 FILE=HILLS.0
100 : pbmetad1: PBMETAD ARG=d SELECTOR=GAMMA SELECTOR_ID=1 SIGMA=0.1 PACE=500 HEIGHT=1 BIASFACTOR=8 FILE=HILLS.1
101 : pbmetad2: PBMETAD ARG=d SELECTOR=GAMMA SELECTOR_ID=2 SIGMA=0.1 PACE=500 HEIGHT=1 BIASFACTOR=8 FILE=HILLS.2
102 : pbmetad3: PBMETAD ARG=d SELECTOR=GAMMA SELECTOR_ID=3 SIGMA=0.1 PACE=500 HEIGHT=1 BIASFACTOR=8 FILE=HILLS.3
103 : pbmetad4: PBMETAD ARG=d SELECTOR=GAMMA SELECTOR_ID=4 SIGMA=0.1 PACE=500 HEIGHT=1 BIASFACTOR=8 FILE=HILLS.4
104 :
105 : RESCALE ...
106 : LABEL=res TEMP=300
107 : ARG=ene,pbmetad0.bias,pbmetad1.bias,pbmetad2.bias,pbmetad3.bias,pbmetad4.bias
108 : SELECTOR=GAMMA MAX_RESCALE=1.5 NOT_RESCALED=5 NBIN=5
109 : W0=1000 BIASFACTOR=100.0 BSTRIDE=2000 BFILE=bias.dat
110 : ...
111 :
112 : PRINT FILE=COLVAR ARG=* STRIDE=100
113 : \endplumedfile
114 :
115 :
116 :
117 : */
118 : //+ENDPLUMEDOC
119 :
120 : class Rescale : public bias::Bias
121 : {
122 : // gamma parameter
123 : vector<double> gamma_;
124 : double w0_;
125 : double biasf_;
126 : vector<double> bias_;
127 : vector<double> expo_;
128 : vector<unsigned> shared_;
129 : unsigned nores_;
130 : // bias
131 : unsigned int Biasstride_;
132 : unsigned int Biaspace_;
133 : string Biasfilename_;
134 : bool first_bias_;
135 : OFile Biasfile_;
136 : // temperature in kbt
137 : double kbt_;
138 : // Monte Carlo stuff
139 : unsigned MCsteps_;
140 : unsigned MCstride_;
141 : long int MCfirst_;
142 : long unsigned MCaccgamma_;
143 : // replica stuff
144 : unsigned nrep_;
145 : unsigned replica_;
146 : // selector
147 : string selector_;
148 :
149 : // Monte Carlo
150 : void doMonteCarlo(unsigned igamma, double oldE, vector<double> args, vector<double> bargs);
151 : unsigned proposeMove(unsigned x, unsigned xmin, unsigned xmax);
152 : bool doAccept(double oldE, double newE);
153 : // read and print bias
154 : void read_bias();
155 : void print_bias(long int step);
156 :
157 : public:
158 : explicit Rescale(const ActionOptions&);
159 : ~Rescale();
160 : void calculate();
161 : static void registerKeywords(Keywords& keys);
162 : };
163 :
164 :
165 6452 : PLUMED_REGISTER_ACTION(Rescale,"RESCALE")
166 :
167 1 : void Rescale::registerKeywords(Keywords& keys) {
168 1 : Bias::registerKeywords(keys);
169 2 : keys.use("ARG");
170 4 : keys.add("compulsory","TEMP","temperature");
171 4 : keys.add("compulsory","SELECTOR", "name of the SELECTOR used for rescaling");
172 4 : keys.add("compulsory","MAX_RESCALE","maximum values for rescaling");
173 4 : keys.add("compulsory","NBIN","number of bins for gamma grid");
174 4 : keys.add("compulsory","W0", "initial bias height");
175 4 : keys.add("compulsory","BIASFACTOR", "bias factor");
176 4 : keys.add("compulsory","BSTRIDE", "stride for writing bias");
177 4 : keys.add("compulsory","BFILE", "file name for bias");
178 4 : keys.add("optional","NOT_SHARED", "list of arguments (from 1 to N) not summed across replicas");
179 4 : keys.add("optional","NOT_RESCALED", "these last N arguments will not be rescaled");
180 4 : keys.add("optional","MC_STEPS","number of MC steps");
181 4 : keys.add("optional","MC_STRIDE","MC stride");
182 4 : keys.add("optional","PACE", "Pace for adding bias, in MC stride unit");
183 1 : componentsAreNotOptional(keys);
184 4 : keys.addOutputComponent("igamma", "default","gamma parameter");
185 4 : keys.addOutputComponent("accgamma","default","MC acceptance for gamma");
186 4 : keys.addOutputComponent("wtbias", "default","well-tempered bias");
187 1 : }
188 :
189 0 : Rescale::Rescale(const ActionOptions&ao):
190 : PLUMED_BIAS_INIT(ao),
191 : nores_(0), Biaspace_(1), first_bias_(true),
192 0 : MCsteps_(1), MCstride_(1), MCfirst_(-1), MCaccgamma_(0)
193 : {
194 : // set up replica stuff
195 0 : if(comm.Get_rank()==0) {
196 0 : nrep_ = multi_sim_comm.Get_size();
197 0 : replica_ = multi_sim_comm.Get_rank();
198 : } else {
199 0 : nrep_ = 0;
200 0 : replica_ = 0;
201 : }
202 0 : comm.Sum(&nrep_,1);
203 0 : comm.Sum(&replica_,1);
204 :
205 : // wt-parameters
206 0 : parse("W0", w0_);
207 0 : parse("BIASFACTOR", biasf_);
208 :
209 : // selector name
210 0 : parse("SELECTOR", selector_);
211 :
212 : // number of bins for gamma ladder
213 : unsigned nbin;
214 0 : parse("NBIN", nbin);
215 :
216 : // number of bias
217 0 : parse("NOT_RESCALED", nores_);
218 0 : if(nores_>0 && nores_!=nbin) error("The number of non rescaled arguments must be equal to either 0 or the number of bins");
219 :
220 : // maximum value of rescale
221 : vector<double> max_rescale;
222 0 : parseVector("MAX_RESCALE", max_rescale);
223 : // check dimension of max_rescale
224 0 : if(max_rescale.size()!=(getNumberOfArguments()-nores_))
225 0 : error("Size of MAX_RESCALE array must be equal to the number of arguments that will to be rescaled");
226 :
227 : // calculate exponents
228 0 : double igamma_max = static_cast<double>(nbin);
229 0 : for(unsigned i=0; i<max_rescale.size(); ++i)
230 0 : expo_.push_back(std::log(max_rescale[i])/std::log(igamma_max));
231 :
232 : // allocate gamma grid and set bias to zero
233 0 : for(unsigned i=0; i<nbin; ++i) {
234 : // bias grid
235 0 : bias_.push_back(0.0);
236 : // gamma ladder
237 0 : double gamma = exp( static_cast<double>(i) / static_cast<double>(nbin-1) * std::log(igamma_max) );
238 0 : gamma_.push_back(gamma);
239 : }
240 : // print bias to file
241 0 : parse("BSTRIDE", Biasstride_);
242 0 : parse("BFILE", Biasfilename_);
243 :
244 : // create vectors of shared arguments
245 : // by default they are all shared
246 0 : for(unsigned i=0; i<getNumberOfArguments(); ++i) shared_.push_back(1);
247 : // share across replicas or not
248 : vector<unsigned> not_shared;
249 0 : parseVector("NOT_SHARED", not_shared);
250 : // and change the non-shared
251 0 : for(unsigned i=0; i<not_shared.size(); ++i) {
252 0 : if((not_shared[i]-1)>=(getNumberOfArguments()-nores_) && nrep_>1)
253 0 : error("NOT_RESCALED args must always be shared when using multiple replicas");
254 0 : if((not_shared[i]-1)>=getNumberOfArguments())
255 0 : error("NOT_SHARED args should be lower than total number of arguments");
256 0 : shared_[not_shared[i]-1] = 0;
257 : }
258 :
259 : // monte carlo stuff
260 0 : parse("MC_STEPS",MCsteps_);
261 0 : parse("MC_STRIDE",MCstride_);
262 : // adjust for multiple-time steps
263 0 : MCstride_ *= getStride();
264 : // read bias deposition pace
265 0 : parse("PACE", Biaspace_);
266 : // multiply by MCstride
267 0 : Biaspace_ *= MCstride_;
268 :
269 : // get temperature
270 0 : double temp=0.0;
271 0 : parse("TEMP",temp);
272 0 : if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp;
273 0 : else kbt_=plumed.getAtoms().getKbT();
274 :
275 0 : checkRead();
276 :
277 0 : log.printf(" temperature of the system in energy unit %f\n",kbt_);
278 0 : log.printf(" name of the SELECTOR use for this action %s\n",selector_.c_str());
279 0 : log.printf(" number of bins in grid %u\n",nbin);
280 0 : log.printf(" number of arguments that will not be rescaled %u\n",nores_);
281 0 : if(nrep_>1) log.printf(" number of arguments that will not be summed across replicas %u\n",not_shared.size());
282 0 : log.printf(" biasfactor %f\n",biasf_);
283 0 : log.printf(" initial hills height %f\n",w0_);
284 0 : log.printf(" stride to write bias to file %u\n",Biasstride_);
285 0 : log.printf(" write bias to file : %s\n",Biasfilename_.c_str());
286 0 : log.printf(" number of replicas %u\n",nrep_);
287 0 : log.printf(" number of MC steps %d\n",MCsteps_);
288 0 : log.printf(" do MC every %d steps\n", MCstride_);
289 0 : log.printf("\n");
290 :
291 0 : log << " Bibliography" << plumed.cite("Bonomi, Camilloni, Bioinformatics, 33, 3999 (2017)") << "\n";
292 :
293 :
294 : // add components
295 0 : addComponent("igamma"); componentIsNotPeriodic("igamma");
296 0 : addComponent("accgamma"); componentIsNotPeriodic("accgamma");
297 0 : addComponent("wtbias"); componentIsNotPeriodic("wtbias");
298 :
299 : // initialize random seed
300 0 : srand (time(NULL));
301 :
302 : // read bias if restarting
303 0 : if(getRestart()) read_bias();
304 0 : }
305 :
306 0 : Rescale::~Rescale()
307 : {
308 0 : Biasfile_.close();
309 0 : }
310 :
311 0 : void Rescale::read_bias()
312 : {
313 : // open file
314 0 : IFile *ifile = new IFile();
315 0 : ifile->link(*this);
316 0 : if(ifile->FileExist(Biasfilename_)) {
317 0 : ifile->open(Biasfilename_);
318 : // read all the lines, store last value of bias
319 : double MDtime;
320 0 : while(ifile->scanField("MD_time",MDtime)) {
321 0 : for(unsigned i=0; i<bias_.size(); ++i) {
322 : // convert i to string
323 0 : stringstream ss;
324 : ss << i;
325 : // label
326 0 : string label = "b" + ss.str();
327 : // read entry
328 0 : ifile->scanField(label, bias_[i]);
329 : }
330 : // new line
331 0 : ifile->scanField();
332 : }
333 0 : ifile->close();
334 : } else {
335 0 : error("Cannot find bias file "+Biasfilename_+"\n");
336 : }
337 0 : delete ifile;
338 0 : }
339 :
340 0 : unsigned Rescale::proposeMove(unsigned x, unsigned xmin, unsigned xmax)
341 : {
342 0 : int xmin_i = static_cast<int>(xmin);
343 0 : int xmax_i = static_cast<int>(xmax);
344 : int dx;
345 0 : int r = rand() % 2;
346 0 : if( r % 2 == 0 ) dx = +1;
347 : else dx = -1;
348 : // new index, integer
349 0 : int x_new = static_cast<int>(x) + dx;
350 : // check boundaries
351 0 : if(x_new >= xmax_i) x_new = xmax_i-1;
352 0 : if(x_new < xmin_i) x_new = xmin_i;
353 0 : return static_cast<unsigned>(x_new);
354 : }
355 :
356 0 : bool Rescale::doAccept(double oldE, double newE)
357 : {
358 : bool accept = false;
359 : // calculate delta energy
360 0 : double delta = ( newE - oldE ) / kbt_;
361 : // if delta is negative always accept move
362 0 : if( delta < 0.0 ) {
363 : accept = true;
364 : } else {
365 : // otherwise extract random number
366 0 : double s = static_cast<double>(rand()) / RAND_MAX;
367 0 : if( s < exp(-delta) ) { accept = true; }
368 : }
369 0 : return accept;
370 : }
371 :
372 0 : void Rescale::doMonteCarlo(unsigned igamma, double oldE,
373 : vector<double> args, vector<double> bargs)
374 : {
375 : double oldB, newB;
376 :
377 : // cycle on MC steps
378 0 : for(unsigned i=0; i<MCsteps_; ++i) {
379 : // propose move in igamma
380 0 : unsigned new_igamma = proposeMove(igamma, 0, gamma_.size());
381 : // calculate new energy
382 : double newE = 0.0;
383 0 : for(unsigned j=0; j<args.size(); ++j) {
384 : // calculate energy term
385 0 : double fact = 1.0/pow(gamma_[new_igamma], expo_[j]) - 1.0;
386 0 : newE += args[j] * fact;
387 : }
388 : // calculate contributions from non-rescaled terms
389 0 : if(bargs.size()>0) {
390 0 : oldB = bias_[igamma]+bargs[igamma];
391 0 : newB = bias_[new_igamma]+bargs[new_igamma];
392 : } else {
393 0 : oldB = bias_[igamma];
394 0 : newB = bias_[new_igamma];
395 : }
396 : // accept or reject
397 0 : bool accept = doAccept(oldE+oldB, newE+newB);
398 0 : if(accept) {
399 0 : igamma = new_igamma;
400 : oldE = newE;
401 0 : MCaccgamma_++;
402 : }
403 : }
404 : // send values of gamma to all replicas
405 0 : if(comm.Get_rank()==0) {
406 0 : if(multi_sim_comm.Get_rank()!=0) igamma = 0;
407 0 : multi_sim_comm.Sum(&igamma, 1);
408 : } else {
409 0 : igamma = 0;
410 : }
411 : // local communication
412 0 : comm.Sum(&igamma, 1);
413 :
414 : // set the value of gamma into passMap
415 0 : plumed.passMap[selector_]=static_cast<double>(igamma);
416 0 : }
417 :
418 0 : void Rescale::print_bias(long int step)
419 : {
420 : // if first time open the file
421 0 : if(first_bias_) {
422 0 : first_bias_ = false;
423 0 : Biasfile_.link(*this);
424 0 : Biasfile_.open(Biasfilename_);
425 : Biasfile_.setHeavyFlush();
426 0 : Biasfile_.fmtField("%30.5f");
427 : }
428 :
429 : // write fields
430 0 : double MDtime = static_cast<double>(step)*getTimeStep();
431 0 : Biasfile_.printField("MD_time", MDtime);
432 0 : for(unsigned i=0; i<bias_.size(); ++i) {
433 : // convert i to string
434 0 : stringstream ss;
435 : ss << i;
436 : // label
437 0 : string label = "b" + ss.str();
438 : // print entry
439 0 : Biasfile_.printField(label, bias_[i]);
440 : }
441 0 : Biasfile_.printField();
442 0 : }
443 :
444 0 : void Rescale::calculate()
445 : {
446 : // get the current value of the selector
447 0 : unsigned igamma = static_cast<unsigned>(plumed.passMap[selector_]);
448 :
449 : // collect data from other replicas
450 0 : vector<double> all_args(getNumberOfArguments(), 0.0);
451 : // first calculate arguments
452 0 : for(unsigned i=0; i<all_args.size(); ++i) {
453 0 : double arg = getArgument(i);
454 : // sum shared arguments across replicas
455 0 : if(shared_[i]==1) {
456 0 : if(comm.Get_rank()==0) multi_sim_comm.Sum(arg);
457 0 : else arg = 0.0;
458 0 : if(comm.Get_size()>1) comm.Sum(arg);
459 : }
460 : // put into all_args
461 0 : all_args[i] = arg;
462 : }
463 :
464 : // now separate terms that should be rescaled
465 : vector<double> args;
466 0 : if(getNumberOfArguments()-nores_>0) args.resize(getNumberOfArguments()-nores_);
467 0 : for(unsigned i=0; i<args.size(); ++i) args[i] = all_args[i];
468 : // and terms that should not
469 : vector<double> bargs;
470 0 : if(nores_>0) bargs.resize(nores_);
471 0 : for(unsigned i=0; i<bargs.size(); ++i) bargs[i] = all_args[i+args.size()];
472 :
473 : // calculate energy and forces, only on rescaled terms
474 : double ene = 0.0;
475 0 : for(unsigned i=0; i<args.size(); ++i) {
476 : // calculate energy term
477 0 : double fact = 1.0/pow(gamma_[igamma], expo_[i]) - 1.0;
478 0 : ene += args[i] * fact;
479 : // add force
480 0 : setOutputForce(i, -fact);
481 : }
482 :
483 : // set to zero on the others
484 0 : for(unsigned i=0; i<bargs.size(); ++i) setOutputForce(i+args.size(), 0.0);
485 :
486 : // set value of the bias
487 : setBias(ene);
488 : // set value of the wt-bias
489 0 : getPntrToComponent("wtbias")->set(bias_[igamma]);
490 : // set values of gamma
491 0 : getPntrToComponent("igamma")->set(igamma);
492 : // get time step
493 0 : long int step = getStep();
494 0 : if(MCfirst_==-1) MCfirst_=step;
495 : // calculate gamma acceptance
496 0 : double MCtrials = std::floor(static_cast<double>(step-MCfirst_) / static_cast<double>(MCstride_))+1.0;
497 0 : double accgamma = static_cast<double>(MCaccgamma_) / static_cast<double>(MCsteps_) / MCtrials;
498 0 : getPntrToComponent("accgamma")->set(accgamma);
499 :
500 : // do MC at the right time step
501 0 : if(step%MCstride_==0&&!getExchangeStep()) doMonteCarlo(igamma, ene, args, bargs);
502 :
503 : // add well-tempered like bias
504 0 : if(step%Biaspace_==0) {
505 : // get updated igamma
506 0 : unsigned igamma = static_cast<unsigned>(plumed.passMap[selector_]);
507 : // add "Gaussian"
508 0 : double kbDT = kbt_ * ( biasf_ - 1.0 );
509 0 : bias_[igamma] += w0_ * exp(-bias_[igamma] / kbDT);
510 : }
511 :
512 : // print bias
513 0 : if(step%Biasstride_==0) print_bias(step);
514 :
515 0 : }
516 :
517 :
518 : }
519 4839 : }
520 :
|