LCOV - code coverage report
Current view: top level - bias - PBMetaD.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 612 729 84.0 %
Date: 2025-11-25 13:55:50 Functions: 13 15 86.7 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2015-2023 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             : #include "Bias.h"
      23             : #include "core/ActionRegister.h"
      24             : #include "core/ActionSet.h"
      25             : #include "core/PlumedMain.h"
      26             : #include "core/FlexibleBin.h"
      27             : #include "tools/Exception.h"
      28             : #include "tools/Grid.h"
      29             : #include "tools/Matrix.h"
      30             : #include "tools/OpenMP.h"
      31             : #include "tools/Random.h"
      32             : #include "tools/File.h"
      33             : #include "tools/Communicator.h"
      34             : #include <ctime>
      35             : #include <numeric>
      36             : 
      37             : namespace PLMD {
      38             : namespace bias {
      39             : 
      40             : //+PLUMEDOC BIAS PBMETAD
      41             : /*
      42             : Used to performed Parallel Bias metadynamics.
      43             : 
      44             : This action activate Parallel Bias Metadynamics (PBMetaD) \cite pbmetad, a version of metadynamics \cite metad in which
      45             : multiple low-dimensional bias potentials are applied in parallel.
      46             : In the current implementation, these have the form of mono-dimensional metadynamics bias
      47             : potentials:
      48             : 
      49             : \f[
      50             : {V(s_1,t), ..., V(s_N,t)}
      51             : \f]
      52             : 
      53             : where:
      54             : 
      55             : \f[
      56             : V(s_i,t) = \sum_{ k \tau < t} W_i(k \tau)
      57             : \exp\left(
      58             : - \frac{(s_i-s_i^{(0)}(k \tau))^2}{2\sigma_i^2}
      59             : \right).
      60             : \f]
      61             : 
      62             : To ensure the convergence of each mono-dimensional bias potential to the corresponding free energy,
      63             : at each deposition step the Gaussian heights are multiplied by the so-called conditional term:
      64             : 
      65             : \f[
      66             : W_i(k \tau)=W_0 \frac{\exp\left(
      67             : - \frac{V(s_i,k \tau)}{k_B T}
      68             : \right)}{\sum_{i=1}^N
      69             : \exp\left(
      70             : - \frac{V(s_i,k \tau)}{k_B T}
      71             : \right)}
      72             : \f]
      73             : 
      74             : where \f$W_0\f$ is the initial Gaussian height.
      75             : 
      76             : The PBMetaD bias potential is defined by:
      77             : 
      78             : \f[
      79             : V_{PB}(\vec{s},t) = -k_B T \log{\sum_{i=1}^N
      80             : \exp\left(
      81             : - \frac{V(s_i,t)}{k_B T}
      82             : \right)}.
      83             : \f]
      84             : 
      85             : 
      86             : Information on the Gaussian functions that build each bias potential are printed to
      87             : multiple HILLS files, which
      88             : are used both to restart the calculation and to reconstruct the mono-dimensional
      89             : free energies as a function of the corresponding CVs.
      90             : These can be reconstructed using the \ref sum_hills utility because the final bias is given
      91             : by:
      92             : 
      93             : \f[
      94             : V(s_i) = -F(s_i)
      95             : \f]
      96             : 
      97             : Currently, only a subset of the \ref METAD options are available in PBMetaD.
      98             : 
      99             : The bias potentials can be stored on a grid to increase performances of long PBMetaD simulations.
     100             : You should
     101             : provide either the number of bins for every collective variable (GRID_BIN) or
     102             : the desired grid spacing (GRID_SPACING). In case you provide both PLUMED will use
     103             : the most conservative choice (highest number of bins) for each dimension.
     104             : In case you do not provide any information about bin size (neither GRID_BIN nor GRID_SPACING)
     105             : and if Gaussian width is fixed PLUMED will use 1/5 of the Gaussian width as grid spacing.
     106             : This default choice should be reasonable for most applications.
     107             : 
     108             : Another option that is available is well-tempered metadynamics \cite Barducci:2008. In this
     109             : variant of PBMetaD the heights of the Gaussian hills are scaled at each step by the
     110             : additional well-tempered metadynamics term.
     111             : This  ensures that each bias converges more smoothly. It should be noted that, in the case of well-tempered metadynamics, in
     112             : the output printed the Gaussian height is re-scaled using the bias factor.
     113             : Also notice that with well-tempered metadynamics the HILLS files do not contain the bias,
     114             : but the negative of the free-energy estimate. This choice has the advantage that
     115             : one can restart a simulation using a different value for the \f$\Delta T\f$. The applied bias will be scaled accordingly.
     116             : 
     117             : Note that you can use here also the flexible Gaussian approach  \cite Branduardi:2012dl
     118             : in which you can adapt the Gaussian to the extent of Cartesian space covered by a variable or
     119             : to the space in collective variable covered in a given time. In this case the width of the deposited
     120             : Gaussian potential is denoted by one value only that is a Cartesian space (ADAPTIVE=GEOM) or a time
     121             : (ADAPTIVE=DIFF). Note that a specific integration technique for the deposited Gaussian kernels
     122             : should be used in this case. Check the documentation for utility sum_hills.
     123             : 
     124             : With the keyword INTERVAL one changes the metadynamics algorithm setting the bias force equal to zero
     125             : outside boundary \cite baftizadeh2012protein. If, for example, metadynamics is performed on a CV s and one is interested only
     126             : to the free energy for s > boundary, the history dependent potential is still updated according to the above
     127             : equations but the metadynamics force is set to zero for s < boundary. Notice that Gaussian kernels are added also
     128             : if s < boundary, as the tails of these Gaussian kernels influence VG in the relevant region s > boundary. In this way, the
     129             : force on the system in the region s > boundary comes from both metadynamics and the force field, in the region
     130             : s < boundary only from the latter. This approach allows obtaining a history-dependent bias potential VG that
     131             : fluctuates around a stable estimator, equal to the negative of the free energy far enough from the
     132             : boundaries. Note that:
     133             : - It works only for one-dimensional biases;
     134             : - It works both with and without GRID;
     135             : - The interval limit boundary in a region where the free energy derivative is not large;
     136             : - If in the region outside the limit boundary the system has a free energy minimum, the INTERVAL keyword should
     137             :   be used together with a \ref UPPER_WALLS or \ref LOWER_WALLS at boundary.
     138             : 
     139             : For systems with multiple CVs that share identical properties, PBMetaD with partitioned families can be used
     140             : to group them under one bias potential that each contributes to \cite Prakash2018PF. This is done with a list
     141             : of PF keywords, where each PF* argument contains the list of CVs from ARG to be placed in that family. Once
     142             : invoked, each CV in ARG must be placed in exactly one PF, even if it results in families containing only one CV.
     143             : Additionally, in cases where each of SIGMA or GRID entry would correspond to each ARG entry, they now correspond to
     144             : each PF and must be adjusted accordingly.
     145             : 
     146             : Multiple walkers  \cite multiplewalkers can also be used. See below the examples.
     147             : 
     148             : \par Examples
     149             : 
     150             : The following input is for PBMetaD calculation using as
     151             : collective variables the distance between atoms 3 and 5
     152             : and the distance between atoms 2 and 4. The value of the CVs and
     153             : the PBMetaD bias potential are written to the COLVAR file every 100 steps.
     154             : \plumedfile
     155             : DISTANCE ATOMS=3,5 LABEL=d1
     156             : DISTANCE ATOMS=2,4 LABEL=d2
     157             : PBMETAD ARG=d1,d2 SIGMA=0.2,0.2 HEIGHT=0.3 PACE=500 LABEL=pb FILE=HILLS_d1,HILLS_d2
     158             : PRINT ARG=d1,d2,pb.bias STRIDE=100 FILE=COLVAR
     159             : \endplumedfile
     160             : (See also \ref DISTANCE and \ref PRINT).
     161             : 
     162             : \par
     163             : If you use well-tempered metadynamics, you should specify a single bias factor and initial
     164             : Gaussian height.
     165             : \plumedfile
     166             : DISTANCE ATOMS=3,5 LABEL=d1
     167             : DISTANCE ATOMS=2,4 LABEL=d2
     168             : PBMETAD ...
     169             : ARG=d1,d2 SIGMA=0.2,0.2 HEIGHT=0.3
     170             : PACE=500 BIASFACTOR=8 LABEL=pb
     171             : FILE=HILLS_d1,HILLS_d2
     172             : ... PBMETAD
     173             : PRINT ARG=d1,d2,pb.bias STRIDE=100 FILE=COLVAR
     174             : \endplumedfile
     175             : 
     176             : \par
     177             : Using partitioned families, each CV in ARG must be in exactly one family. Here,
     178             : the distance between atoms 1,2 is degenerate with 2,4, but not with the
     179             : distance between 3,5. Note that two SIGMA are provided to match the two PF.
     180             : \plumedfile
     181             : DISTANCE ATOMS=3,5 LABEL=d1
     182             : DISTANCE ATOMS=2,4 LABEL=d2
     183             : DISTANCE ATOMS=1,2 LABEL=d3
     184             : PBMETAD ...
     185             : ARG=d1,d2,d3 SIGMA=0.2,0.2 HEIGHT=0.3
     186             : PF0=d1 PF1=d2,d3
     187             : PACE=500 BIASFACTOR=8 LABEL=pb
     188             : FILE=HILLS_d1,HILLS_d2
     189             : ... PBMETAD
     190             : PRINT ARG=d1,d2,d3,pb.bias STRIDE=100 FILE=COLVAR
     191             : \endplumedfile
     192             : 
     193             : \par
     194             : The following input enables the MPI version of multiple-walkers.
     195             : \plumedfile
     196             : DISTANCE ATOMS=3,5 LABEL=d1
     197             : DISTANCE ATOMS=2,4 LABEL=d2
     198             : PBMETAD ...
     199             : ARG=d1,d2 SIGMA=0.2,0.2 HEIGHT=0.3
     200             : PACE=500 BIASFACTOR=8 LABEL=pb
     201             : FILE=HILLS_d1,HILLS_d2
     202             : WALKERS_MPI
     203             : ... PBMETAD
     204             : PRINT ARG=d1,d2,pb.bias STRIDE=100 FILE=COLVAR
     205             : \endplumedfile
     206             : 
     207             : \par
     208             : The disk version of multiple-walkers can be
     209             : enabled by setting the number of walker used, the id of the
     210             : current walker which interprets the input file, the directory where the
     211             : hills containing files resides, and the frequency to read the other walkers.
     212             : Here is an example
     213             : \plumedfile
     214             : DISTANCE ATOMS=3,5 LABEL=d1
     215             : DISTANCE ATOMS=2,4 LABEL=d2
     216             : PBMETAD ...
     217             : ARG=d1,d2 SIGMA=0.2,0.2 HEIGHT=0.3
     218             : PACE=500 BIASFACTOR=8 LABEL=pb
     219             : FILE=HILLS_d1,HILLS_d2
     220             : WALKERS_N=10
     221             : WALKERS_ID=3
     222             : WALKERS_DIR=../
     223             : WALKERS_RSTRIDE=100
     224             : ... PBMETAD
     225             : PRINT ARG=d1,d2,pb.bias STRIDE=100 FILE=COLVAR
     226             : \endplumedfile
     227             : where  WALKERS_N is the total number of walkers, WALKERS_ID is the
     228             : id of the present walker (starting from 0 ) and the WALKERS_DIR is the directory
     229             : where all the walkers are located. WALKERS_RSTRIDE is the number of step between
     230             : one update and the other.
     231             : 
     232             : */
     233             : //+ENDPLUMEDOC
     234             : 
     235             : class PBMetaD : public Bias {
     236             : 
     237             : private:
     238             :   struct Gaussian {
     239             :     std::vector<double> center;
     240             :     std::vector<double> sigma;
     241             :     double height;
     242             :     bool   multivariate; // this is required to discriminate the one dimensional case
     243             :     std::vector<double> invsigma;
     244        1120 :     Gaussian(const std::vector<double> & center,const std::vector<double> & sigma, double height, bool multivariate):
     245        1120 :       center(center),sigma(sigma),height(height),multivariate(multivariate),invsigma(sigma) {
     246             :       // to avoid troubles from zero element in flexible hills
     247        2240 :       for(unsigned i=0; i<invsigma.size(); ++i)
     248        1120 :         if(std::abs(invsigma[i])>1.e-20) {
     249        1120 :           invsigma[i]=1.0/invsigma[i] ;
     250             :         } else {
     251           0 :           invsigma[i]=0.0;
     252             :         }
     253        1120 :     }
     254             :   };
     255             :   // general setup
     256             :   double kbt_;
     257             :   int stride_;
     258             :   // well-tempered MetaD
     259             :   bool welltemp_;
     260             :   double biasf_;
     261             :   // output files format
     262             :   std::string fmt_;
     263             :   // first step?
     264             :   bool isFirstStep_;
     265             :   // Gaussian starting parameters
     266             :   double height0_;
     267             :   std::vector<double> sigma0_;
     268             :   std::vector<double> sigma0min_;
     269             :   std::vector<double> sigma0max_;
     270             :   // Gaussians
     271             :   std::vector<std::vector<Gaussian> > hills_;
     272             :   std::vector<FlexibleBin> flexbin_;
     273             :   int adaptive_;
     274             :   std::vector<std::unique_ptr<OFile>> hillsOfiles_;
     275             :   std::vector<std::unique_ptr<IFile>> ifiles_;
     276             :   std::vector<std::string> ifilesnames_;
     277             :   // Grids
     278             :   bool grid_;
     279             :   std::vector<std::unique_ptr<GridBase>> BiasGrids_;
     280             :   std::vector<std::unique_ptr<OFile>> gridfiles_;
     281             :   int wgridstride_;
     282             :   // Partitioned Families
     283             :   unsigned int pf_n_; // initialize number of partitioned families
     284             :   std::vector<int> pfs_; //std::vector length of arguments that holds which pf# each cv belongs in
     285             :   std::vector<Value*> pfhold_; // std::vector length of pf_n which stores a pointer to the first argument fed to each family
     286             :   bool do_pf_; // if partitioned families are enabled
     287             :   // multiple walkers
     288             :   int mw_n_;
     289             :   std::string mw_dir_;
     290             :   int mw_id_;
     291             :   int mw_rstride_;
     292             :   bool walkers_mpi_;
     293             :   size_t mpi_nw_;
     294             :   unsigned mpi_id_;
     295             :   std::vector<std::string> hillsfname_;
     296             :   // intervals
     297             :   std::vector<double> uppI_;
     298             :   std::vector<double> lowI_;
     299             :   std::vector<bool>  doInt_;
     300             :   // variable for selector
     301             :   std::string selector_;
     302             :   bool  do_select_;
     303             :   unsigned select_value_;
     304             :   unsigned current_value_;
     305             : 
     306             :   double stretchA=1.0;
     307             :   double stretchB=0.0;
     308             : 
     309             :   bool noStretchWarningDone=false;
     310             : 
     311           0 :   void noStretchWarning() {
     312           0 :     if(!noStretchWarningDone) {
     313           0 :       log<<"\nWARNING: you are using a HILLS file with Gaussian kernels, PLUMED 2.8 uses stretched Gaussians by default\n";
     314             :     }
     315           0 :     noStretchWarningDone=true;
     316           0 :   }
     317             : 
     318             :   void   readGaussians(unsigned iarg, IFile*);
     319             :   void   writeGaussian(unsigned iarg, const Gaussian&, OFile*);
     320             :   void   addGaussian(unsigned iarg, const Gaussian&);
     321             :   double getBiasAndDerivatives(unsigned iarg, const std::vector<double>&, double* der=NULL);
     322             :   double evaluateGaussian(unsigned iarg, const std::vector<double>&, const Gaussian&,double* der=NULL);
     323             :   std::vector<unsigned> getGaussianSupport(unsigned iarg, const Gaussian&);
     324             :   bool   scanOneHill(unsigned iarg, IFile *ifile,  std::vector<Value> &v, std::vector<double> &center, std::vector<double>  &sigma, double &height, bool &multivariate);
     325             : 
     326             : public:
     327             :   explicit PBMetaD(const ActionOptions&);
     328             :   void calculate() override;
     329             :   void update() override;
     330             :   static void registerKeywords(Keywords& keys);
     331             :   bool checkNeedsGradients()const override;
     332             : };
     333             : 
     334             : PLUMED_REGISTER_ACTION(PBMetaD,"PBMETAD")
     335             : 
     336          44 : void PBMetaD::registerKeywords(Keywords& keys) {
     337          44 :   Bias::registerKeywords(keys);
     338          44 :   keys.use("ARG");
     339          88 :   keys.add("compulsory","SIGMA","the widths of the Gaussian hills");
     340          88 :   keys.add("compulsory","PACE","the frequency for hill addition, one for all biases");
     341          88 :   keys.add("optional","FILE","files in which the lists of added hills are stored, default names are assigned using arguments if FILE is not found");
     342          88 :   keys.add("optional","HEIGHT","the height of the Gaussian hills, one for all biases. Compulsory unless TAU, TEMP and BIASFACTOR are given");
     343          88 :   keys.add("optional","FMT","specify format for HILLS files (useful for decrease the number of digits in regtests)");
     344          88 :   keys.add("optional","BIASFACTOR","use well tempered metadynamics with this bias factor, one for all biases.  Please note you must also specify temp");
     345          88 :   keys.add("optional","TEMP","the system temperature - this is only needed if you are doing well-tempered metadynamics");
     346          88 :   keys.add("optional","TAU","in well tempered metadynamics, sets height to (k_B Delta T*pace*timestep)/tau");
     347          88 :   keys.add("optional","GRID_MIN","the lower bounds for the grid");
     348          88 :   keys.add("optional","GRID_MAX","the upper bounds for the grid");
     349          88 :   keys.add("optional","GRID_BIN","the number of bins for the grid");
     350          88 :   keys.add("optional","GRID_SPACING","the approximate grid spacing (to be used as an alternative or together with GRID_BIN)");
     351          88 :   keys.addFlag("GRID_SPARSE",false,"use a sparse grid to store hills");
     352          88 :   keys.addFlag("GRID_NOSPLINE",false,"don't use spline interpolation with grids");
     353          88 :   keys.add("optional","GRID_WSTRIDE", "frequency for dumping the grid");
     354          88 :   keys.add("optional","GRID_WFILES", "dump grid for the bias, default names are used if GRID_WSTRIDE is used without GRID_WFILES.");
     355          88 :   keys.add("optional","GRID_RFILES", "read grid for the bias");
     356          88 :   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");
     357          88 :   keys.add("optional","SIGMA_MAX","the upper bounds for the sigmas (in CV units) when using adaptive hills. Negative number means no bounds ");
     358          88 :   keys.add("optional","SIGMA_MIN","the lower bounds for the sigmas (in CV units) when using adaptive hills. Negative number means no bounds ");
     359          88 :   keys.add("numbered","PF", "specify which CVs belong in a partitioned family. Once a PF is specified, all CVs in ARG must be placed in a PF even if there is one CV per PF”");
     360          88 :   keys.add("optional","SELECTOR", "add forces and do update based on the value of SELECTOR");
     361          88 :   keys.add("optional","SELECTOR_ID", "value of SELECTOR");
     362          88 :   keys.add("optional","WALKERS_ID", "walker id");
     363          88 :   keys.add("optional","WALKERS_N", "number of walkers");
     364          88 :   keys.add("optional","WALKERS_DIR", "shared directory with the hills files from all the walkers");
     365          88 :   keys.add("optional","WALKERS_RSTRIDE","stride for reading hills files");
     366          88 :   keys.addFlag("WALKERS_MPI",false,"Switch on MPI version of multiple walkers - not compatible with WALKERS_* options other than WALKERS_DIR");
     367          88 :   keys.add("optional","INTERVAL_MIN","one dimensional lower limits, outside the limits the system will not feel the biasing force.");
     368          88 :   keys.add("optional","INTERVAL_MAX","one dimensional upper limits, outside the limits the system will not feel the biasing force.");
     369          44 :   keys.use("RESTART");
     370          44 :   keys.use("UPDATE_FROM");
     371          44 :   keys.use("UPDATE_UNTIL");
     372          44 : }
     373             : 
     374          42 : PBMetaD::PBMetaD(const ActionOptions& ao):
     375             :   PLUMED_BIAS_INIT(ao),
     376          42 :   kbt_(0.0),
     377          42 :   stride_(0),
     378          42 :   welltemp_(false),
     379          42 :   biasf_(1.0),
     380          42 :   isFirstStep_(true),
     381          42 :   height0_(std::numeric_limits<double>::max()),
     382          42 :   adaptive_(FlexibleBin::none),
     383          42 :   grid_(false),
     384          42 :   wgridstride_(0),
     385          42 :   pf_n_(0), do_pf_(false),
     386          42 :   mw_n_(1), mw_dir_(""), mw_id_(0), mw_rstride_(1),
     387          42 :   walkers_mpi_(false), mpi_nw_(0),
     388          42 :   do_select_(false) {
     389             : 
     390             :   // parse the flexible hills
     391             :   std::string adaptiveoption;
     392             :   adaptiveoption="NONE";
     393          84 :   parse("ADAPTIVE",adaptiveoption);
     394          42 :   if(adaptiveoption=="GEOM") {
     395           0 :     log.printf("  Uses Geometry-based hills width: sigma must be in distance units and only one sigma is needed\n");
     396           0 :     adaptive_=FlexibleBin::geometry;
     397          42 :   } else if(adaptiveoption=="DIFF") {
     398           4 :     log.printf("  Uses Diffusion-based hills width: sigma must be in time steps and only one sigma is needed\n");
     399           4 :     adaptive_=FlexibleBin::diffusion;
     400          38 :   } else if(adaptiveoption=="NONE") {
     401          38 :     adaptive_=FlexibleBin::none;
     402             :   } else {
     403           0 :     error("I do not know this type of adaptive scheme");
     404             :   }
     405             : 
     406          42 :   parse("FMT",fmt_);
     407             : 
     408             :   // Partitioned Families - fill with -1 to mark as invalid
     409          42 :   pfs_.assign(getNumberOfArguments(), -1);
     410          42 :   pfhold_.resize(getNumberOfArguments());
     411             :   std::vector<Value*> familyargs;
     412          42 :   for(int i = 0;; i++) {
     413         100 :     parseArgumentList("PF", i, familyargs);
     414          50 :     if (familyargs.empty()) {
     415             :       break;
     416             :     }
     417             : 
     418           8 :     do_pf_ = true;
     419           8 :     log << "  Identified Partitioned Family " << i << ":";
     420          20 :     for (unsigned j = 0; j < familyargs.size(); j++) {
     421          12 :       log << " " << familyargs[j]->getName();
     422             :       // loop through the argument list to make sure it exists and assign it
     423             :       bool foundArg = false;
     424          48 :       for (unsigned argnum = 0; argnum < getNumberOfArguments(); argnum++) {
     425          36 :         if (familyargs[j]->getName() == getPntrToArgument(argnum)->getName()) {
     426             :           foundArg = true;
     427          12 :           if (pfs_[argnum] != -1) {
     428           0 :             error(familyargs[j]->getName() + " already present in PF" + std::to_string(pfs_[argnum]));
     429             :           }
     430          12 :           pfs_[argnum] = i;  // store the pf# for each cv
     431          12 :           if (pfhold_[i] == nullptr) {
     432             :             // if this is the first argument in the family, store a pointer for it (this is for HILLS & GRID files)
     433           8 :             pfhold_[i] = getPntrToArgument(argnum);
     434             :           }
     435             :         }
     436             :       }
     437          12 :       if (!foundArg) {
     438           0 :         error(familyargs[j]->getName() + " in PF" + std::to_string(i) + " not found in ARG");
     439             :       }
     440             :     }
     441           8 :     log << "\n";
     442           8 :     pf_n_++;
     443           8 :   }
     444             : 
     445             :   // if PF were specified, every argument gets treated as its own PF
     446          42 :   if (!do_pf_) {
     447          38 :     pf_n_ = getNumberOfArguments();
     448         114 :     for(unsigned i=0; i < pf_n_; i++) {
     449          76 :       pfhold_[i] = getPntrToArgument(i);
     450          76 :       pfs_[i] = i;
     451             :     }
     452             :   } else {
     453             :     // If we are doing PF, make sure each argument got assigned to a family.
     454          16 :     for (unsigned i = 0; i < getNumberOfArguments(); i++) {
     455          12 :       if (pfs_[i] == -1) {
     456           0 :         error(getPntrToArgument(i)->getName() + " was not assigned a PF");
     457             :       }
     458             :     }
     459             :   }
     460             : 
     461             :   // parse the sigma
     462          42 :   parseVector("SIGMA",sigma0_);
     463          42 :   if(adaptive_==FlexibleBin::none) {
     464             :     // if you use normal sigma you need one sigma per argument
     465          38 :     if( sigma0_.size()!=pf_n_ ) {
     466           0 :       std::string fields = do_pf_ ? "PFs" : "arguments";
     467           0 :       error("number of " + fields + " does not match number of SIGMA parameters");
     468             :     }
     469             :   } else {
     470             :     // if you use flexible hills you need one sigma
     471           4 :     if(sigma0_.size()!=1) {
     472           0 :       error("If you choose ADAPTIVE you need only one sigma according to your choice of type (GEOM/DIFF)");
     473             :     }
     474             :     // if adaptive then the number must be an integer
     475           4 :     if(adaptive_==FlexibleBin::diffusion) {
     476           4 :       if(int(sigma0_[0])-sigma0_[0]>1.e-9 || int(sigma0_[0])-sigma0_[0] <-1.e-9 || int(sigma0_[0])<1 ) {
     477           0 :         error("In case of adaptive hills with diffusion, the sigma must be an integer which is the number of time steps\n");
     478             :       }
     479             :     }
     480             :     // here evtl parse the sigma min and max values
     481           8 :     parseVector("SIGMA_MIN",sigma0min_);
     482           4 :     if(sigma0min_.size()>0 && sigma0min_.size()!=pf_n_) {
     483           0 :       error("the number of SIGMA_MIN values be the same of the number of the arguments/PF");
     484           4 :     } else if(sigma0min_.size()==0) {
     485           0 :       sigma0min_.resize(pf_n_);
     486           0 :       for(unsigned i=0; i<pf_n_; i++) {
     487           0 :         sigma0min_[i]=-1.;
     488             :       }
     489             :     }
     490             : 
     491           8 :     parseVector("SIGMA_MAX",sigma0max_);
     492           4 :     if(sigma0max_.size()>0 && sigma0max_.size()!=pf_n_) {
     493           0 :       error("the number of SIGMA_MAX values be the same of the number of the arguments/PF");
     494           4 :     } else if(sigma0max_.size()==0) {
     495           4 :       sigma0max_.resize(pf_n_);
     496          12 :       for(unsigned i=0; i<pf_n_; i++) {
     497           8 :         sigma0max_[i]=-1.;
     498             :       }
     499             :     }
     500             : 
     501          12 :     for(unsigned i=0; i<pf_n_; i++) {
     502             :       std::vector<double> tmp_smin, tmp_smax;
     503           8 :       tmp_smin.resize(1,sigma0min_[i]);
     504           8 :       tmp_smax.resize(1,sigma0max_[i]);
     505          16 :       flexbin_.push_back(FlexibleBin(adaptive_,this,i,sigma0_[0],tmp_smin,tmp_smax));
     506             :     }
     507             :   }
     508             : 
     509             :   // note: HEIGHT is not compulsory, since one could use the TAU keyword, see below
     510          42 :   parse("HEIGHT",height0_);
     511          42 :   parse("PACE",stride_);
     512          42 :   if(stride_<=0) {
     513           0 :     error("frequency for hill addition is nonsensical");
     514             :   }
     515             : 
     516             : 
     517          84 :   parseVector("FILE",hillsfname_);
     518          42 :   if(hillsfname_.size()==0) {
     519          30 :     for(unsigned i=0; i< pf_n_; i++) {
     520          20 :       std::string name = do_pf_ ? "HILLS.PF"+std::to_string(i) : "HILLS."+getPntrToArgument(i)->getName();
     521          20 :       hillsfname_.push_back(name);
     522             :     }
     523             :   }
     524          42 :   if( hillsfname_.size()!=pf_n_ ) {
     525           0 :     error("number of FILE arguments does not match number of HILLS files");
     526             :   }
     527             : 
     528          42 :   parse("BIASFACTOR",biasf_);
     529          42 :   if( biasf_<1.0 ) {
     530           0 :     error("well tempered bias factor is nonsensical");
     531             :   }
     532          42 :   kbt_=getkBT();
     533          42 :   if(biasf_>1.0) {
     534          41 :     if(kbt_==0.0) {
     535           0 :       error("Unless the MD engine passes the temperature to plumed, with well-tempered metad you must specify it using TEMP");
     536             :     }
     537          41 :     welltemp_=true;
     538             :   }
     539          42 :   double tau=0.0;
     540          42 :   parse("TAU",tau);
     541          42 :   if(tau==0.0) {
     542          42 :     if(height0_==std::numeric_limits<double>::max()) {
     543           0 :       error("At least one between HEIGHT and TAU should be specified");
     544             :     }
     545             :     // if tau is not set, we compute it here from the other input parameters
     546          42 :     if(welltemp_) {
     547          41 :       tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_;
     548             :     }
     549             :   } else {
     550           0 :     if(!welltemp_) {
     551           0 :       error("TAU only makes sense in well-tempered metadynamics");
     552             :     }
     553           0 :     if(height0_!=std::numeric_limits<double>::max()) {
     554           0 :       error("At most one between HEIGHT and TAU should be specified");
     555             :     }
     556           0 :     height0_=(kbt_*(biasf_-1.0))/tau*getTimeStep()*stride_;
     557             :   }
     558             : 
     559             : 
     560             :   // Multiple walkers
     561          42 :   parse("WALKERS_N",mw_n_);
     562          42 :   parse("WALKERS_ID",mw_id_);
     563          42 :   if(mw_n_<=mw_id_) {
     564           0 :     error("walker ID should be a numerical value less than the total number of walkers");
     565             :   }
     566          42 :   parse("WALKERS_DIR",mw_dir_);
     567          42 :   parse("WALKERS_RSTRIDE",mw_rstride_);
     568             : 
     569             :   // MPI version
     570          42 :   parseFlag("WALKERS_MPI",walkers_mpi_);
     571             : 
     572             :   // Grid file
     573          84 :   parse("GRID_WSTRIDE",wgridstride_);
     574             :   std::vector<std::string> gridfilenames_;
     575          42 :   parseVector("GRID_WFILES",gridfilenames_);
     576          42 :   if (wgridstride_ == 0 && gridfilenames_.size() > 0) {
     577           0 :     error("frequency with which to output grid not specified use GRID_WSTRIDE");
     578             :   }
     579          42 :   if(gridfilenames_.size()==0 && wgridstride_ > 0) {
     580          12 :     for(unsigned i=0; i<pf_n_; i++) {
     581           8 :       std::string name = do_pf_ ? "GRID.PF"+std::to_string(i) : "GRID."+getPntrToArgument(i)->getName();
     582           8 :       gridfilenames_.push_back(name);
     583             :     }
     584             :   }
     585          42 :   if(gridfilenames_.size() > 0 && hillsfname_.size() > 0 && gridfilenames_.size() != hillsfname_.size()) {
     586           0 :     error("number of GRID_WFILES arguments does not match number of HILLS files");
     587             :   }
     588             : 
     589             :   // Read grid
     590             :   std::vector<std::string> gridreadfilenames_;
     591          42 :   parseVector("GRID_RFILES",gridreadfilenames_);
     592             : 
     593             :   // Grid Stuff
     594          42 :   std::vector<std::string> gmin(pf_n_);
     595          84 :   parseVector("GRID_MIN",gmin);
     596          42 :   if(gmin.size()!=pf_n_ && gmin.size()!=0) {
     597           0 :     error("not enough values for GRID_MIN");
     598             :   }
     599          42 :   std::vector<std::string> gmax(pf_n_);
     600          84 :   parseVector("GRID_MAX",gmax);
     601          42 :   if(gmax.size()!=pf_n_ && gmax.size()!=0) {
     602           0 :     error("not enough values for GRID_MAX");
     603             :   }
     604          42 :   std::vector<unsigned> gbin(pf_n_);
     605             :   std::vector<double>   gspacing;
     606          84 :   parseVector("GRID_BIN",gbin);
     607          42 :   if(gbin.size()!=pf_n_ && gbin.size()!=0) {
     608           0 :     error("not enough values for GRID_BIN");
     609             :   }
     610          84 :   parseVector("GRID_SPACING",gspacing);
     611          42 :   if(gspacing.size()!=pf_n_ && gspacing.size()!=0) {
     612           0 :     error("not enough values for GRID_SPACING");
     613             :   }
     614          42 :   if(gmin.size()!=gmax.size()) {
     615           0 :     error("GRID_MAX and GRID_MIN should be either present or absent");
     616             :   }
     617          42 :   if(gspacing.size()!=0 && gmin.size()==0) {
     618           0 :     error("If GRID_SPACING is present also GRID_MIN and GRID_MAX should be present");
     619             :   }
     620          42 :   if(gbin.size()!=0     && gmin.size()==0) {
     621           0 :     error("If GRID_BIN is present also GRID_MIN and GRID_MAX should be present");
     622             :   }
     623          42 :   if(gmin.size()!=0) {
     624          10 :     if(gbin.size()==0 && gspacing.size()==0) {
     625          10 :       if(adaptive_==FlexibleBin::none) {
     626           6 :         log<<"  Binsize not specified, 1/5 of sigma will be be used\n";
     627           6 :         plumed_assert(sigma0_.size()==pf_n_);
     628           6 :         gspacing.resize(pf_n_);
     629          18 :         for(unsigned i=0; i<gspacing.size(); i++) {
     630          12 :           gspacing[i]=0.2*sigma0_[i];
     631             :         }
     632             :       } else {
     633             :         // with adaptive hills and grid a sigma min must be specified
     634          12 :         for(unsigned i=0; i<sigma0min_.size(); i++)
     635           8 :           if(sigma0min_[i]<=0) {
     636           0 :             error("When using ADAPTIVE Gaussians on a grid SIGMA_MIN must be specified");
     637             :           }
     638           4 :         log<<"  Binsize not specified, 1/5 of sigma_min will be be used\n";
     639           4 :         gspacing.resize(pf_n_);
     640          12 :         for(unsigned i=0; i<gspacing.size(); i++) {
     641           8 :           gspacing[i]=0.2*sigma0min_[i];
     642             :         }
     643             :       }
     644           0 :     } else if(gspacing.size()!=0 && gbin.size()==0) {
     645           0 :       log<<"  The number of bins will be estimated from GRID_SPACING\n";
     646           0 :     } else if(gspacing.size()!=0 && gbin.size()!=0) {
     647           0 :       log<<"  You specified both GRID_BIN and GRID_SPACING\n";
     648           0 :       log<<"  The more conservative (highest) number of bins will be used for each variable\n";
     649             :     }
     650          10 :     if(gbin.size()==0) {
     651          10 :       gbin.assign(pf_n_,1);
     652             :     }
     653          10 :     if(gspacing.size()!=0)
     654          30 :       for(unsigned i=0; i<pf_n_; i++) {
     655             :         double a,b;
     656          20 :         Tools::convert(gmin[i],a);
     657          20 :         Tools::convert(gmax[i],b);
     658          20 :         unsigned n=std::ceil(((b-a)/gspacing[i]));
     659          20 :         if(gbin[i]<n) {
     660          20 :           gbin[i]=n;
     661             :         }
     662             :       }
     663             :   }
     664          42 :   if(gbin.size()>0) {
     665          10 :     grid_=true;
     666             :   }
     667             : 
     668          42 :   bool sparsegrid=false;
     669          42 :   parseFlag("GRID_SPARSE",sparsegrid);
     670          42 :   bool nospline=false;
     671          42 :   parseFlag("GRID_NOSPLINE",nospline);
     672          42 :   bool spline=!nospline;
     673          42 :   if(!grid_&&gridfilenames_.size() > 0) {
     674           0 :     error("To write a grid you need first to define it!");
     675             :   }
     676          42 :   if(!grid_&&gridreadfilenames_.size() > 0) {
     677           0 :     error("To read a grid you need first to define it!");
     678             :   }
     679             : 
     680          42 :   doInt_.resize(pf_n_,false);
     681             :   // Interval keyword
     682          42 :   parseVector("INTERVAL_MIN",lowI_);
     683          84 :   parseVector("INTERVAL_MAX",uppI_);
     684             :   // various checks
     685          42 :   if(lowI_.size()!=uppI_.size()) {
     686           0 :     error("both a lower and an upper limits must be provided with INTERVAL");
     687             :   }
     688          42 :   if(lowI_.size()!=0 && lowI_.size()!=pf_n_) {
     689           0 :     error("check number of argument of INTERVAL");
     690             :   }
     691          50 :   for(unsigned i=0; i<lowI_.size(); ++i) {
     692           8 :     if(uppI_[i]<lowI_[i]) {
     693           0 :       error("The Upper limit must be greater than the Lower limit!");
     694             :     }
     695           8 :     if(pfhold_[i]->isPeriodic()) {
     696           0 :       warning("INTERVAL is not used for periodic variables");
     697             :     } else {
     698             :       doInt_[i]=true;
     699             :     }
     700             :   }
     701             : 
     702             :   // parse selector stuff
     703          84 :   parse("SELECTOR", selector_);
     704          42 :   if(selector_.length()>0) {
     705           1 :     do_select_ = true;
     706           1 :     select_value_ = 0; // set defalt value or it might be not initialized if the user does not pass SELECTOR_ID
     707           2 :     parse("SELECTOR_ID", select_value_);
     708             :   }
     709             : 
     710          42 :   checkRead();
     711             : 
     712          42 :   log.printf("  Gaussian width ");
     713          42 :   if (adaptive_==FlexibleBin::diffusion) {
     714           4 :     log.printf(" (Note: The units of sigma are in timesteps) ");
     715             :   }
     716          42 :   if (adaptive_==FlexibleBin::geometry) {
     717           0 :     log.printf(" (Note: The units of sigma are in dist units) ");
     718             :   }
     719         122 :   for(unsigned i=0; i<sigma0_.size(); ++i) {
     720          80 :     log.printf(" %f",sigma0_[i]);
     721             :   }
     722          42 :   log.printf("  Gaussian height %f\n",height0_);
     723          42 :   log.printf("  Gaussian deposition pace %d\n",stride_);
     724          42 :   log.printf("  Gaussian files ");
     725         126 :   for(unsigned i=0; i<hillsfname_.size(); ++i) {
     726          84 :     log.printf("%s ",hillsfname_[i].c_str());
     727             :   }
     728          42 :   log.printf("\n");
     729          42 :   if(welltemp_) {
     730          41 :     log.printf("  Well-Tempered Bias Factor %f\n",biasf_);
     731          41 :     log.printf("  Hills relaxation time (tau) %f\n",tau);
     732          41 :     log.printf("  KbT %f\n",kbt_);
     733             :   }
     734             : 
     735          42 :   if(do_select_) {
     736           1 :     log.printf("  Add forces and update bias based on the value of SELECTOR %s\n",selector_.c_str());
     737           1 :     log.printf("  Id of the SELECTOR for this action %u\n", select_value_);
     738             :   }
     739             : 
     740          42 :   if(mw_n_>1) {
     741           0 :     if(walkers_mpi_) {
     742           0 :       error("MPI version of multiple walkers is not compatible with filesystem version of multiple walkers");
     743             :     }
     744           0 :     log.printf("  %d multiple walkers active\n",mw_n_);
     745           0 :     log.printf("  walker id %d\n",mw_id_);
     746           0 :     log.printf("  reading stride %d\n",mw_rstride_);
     747           0 :     if(mw_dir_!="") {
     748           0 :       log.printf("  directory with hills files %s\n",mw_dir_.c_str());
     749             :     }
     750             :   } else {
     751          42 :     if(walkers_mpi_) {
     752          34 :       log.printf("  Multiple walkers active using MPI communnication\n");
     753          34 :       if(mw_dir_!="") {
     754           0 :         log.printf("  directory with hills files %s\n",mw_dir_.c_str());
     755             :       }
     756          34 :       if(comm.Get_rank()==0) {
     757             :         // Only root of group can communicate with other walkers
     758          18 :         mpi_nw_ = multi_sim_comm.Get_size();
     759          18 :         mpi_id_ = multi_sim_comm.Get_rank();
     760             :       }
     761             :       // Communicate to the other members of the same group
     762             :       // info abount number of walkers and walker index
     763          34 :       comm.Bcast(mpi_nw_,0);
     764          34 :       comm.Bcast(mpi_id_,0);
     765             :     }
     766             :   }
     767             : 
     768         126 :   for(unsigned i=0; i<doInt_.size(); i++) {
     769          84 :     if(doInt_[i]) {
     770           8 :       log.printf("  Upper and Lower limits boundaries for the bias of CV %u are activated\n", i);
     771             :     }
     772             :   }
     773          42 :   if(grid_) {
     774          10 :     log.printf("  Grid min");
     775          30 :     for(unsigned i=0; i<gmin.size(); ++i) {
     776          20 :       log.printf(" %s",gmin[i].c_str() );
     777             :     }
     778          10 :     log.printf("\n");
     779          10 :     log.printf("  Grid max");
     780          30 :     for(unsigned i=0; i<gmax.size(); ++i) {
     781          20 :       log.printf(" %s",gmax[i].c_str() );
     782             :     }
     783          10 :     log.printf("\n");
     784          10 :     log.printf("  Grid bin");
     785          30 :     for(unsigned i=0; i<gbin.size(); ++i) {
     786          20 :       log.printf(" %u",gbin[i]);
     787             :     }
     788          10 :     log.printf("\n");
     789          10 :     if(spline) {
     790          10 :       log.printf("  Grid uses spline interpolation\n");
     791             :     }
     792          10 :     if(sparsegrid) {
     793           0 :       log.printf("  Grid uses sparse grid\n");
     794             :     }
     795          10 :     if(wgridstride_>0) {
     796          18 :       for(unsigned i=0; i<gridfilenames_.size(); ++i) {
     797          12 :         log.printf("  Grid is written on file %s with stride %d\n",gridfilenames_[i].c_str(),wgridstride_);
     798             :       }
     799             :     }
     800          10 :     if(gridreadfilenames_.size()>0) {
     801           3 :       for(unsigned i=0; i<gridreadfilenames_.size(); ++i) {
     802           2 :         log.printf("  Reading bias from grid in file %s \n",gridreadfilenames_[i].c_str());
     803             :       }
     804             :     }
     805             :   }
     806             : 
     807             :   // initializing vector of hills
     808          42 :   hills_.resize(pf_n_);
     809             : 
     810             :   // restart from external grid
     811             :   bool restartedFromGrid=false;
     812             : 
     813             :   // initializing and checking grid
     814          42 :   if(grid_) {
     815             :     // check for mesh and sigma size
     816          30 :     for(unsigned i=0; i<pf_n_; i++) {
     817             :       double a,b;
     818          20 :       int family = pfs_[i]; // point to families instead of arguments
     819          20 :       Tools::convert(gmin[family],a);
     820          20 :       Tools::convert(gmax[family],b);
     821          20 :       double mesh=(b-a)/((double)gbin[family]);
     822          20 :       if(adaptive_==FlexibleBin::none) {
     823          12 :         if(mesh>0.5*sigma0_[i]) {
     824           0 :           log<<"  WARNING: Using a PBMETAD with a Grid Spacing larger than half of the Gaussians width can produce artifacts\n";
     825             :         }
     826             :       } else {
     827           8 :         if(mesh>0.5*sigma0min_[i]||sigma0min_[i]<0.) {
     828           0 :           log<<"  WARNING: to use a PBMETAD with a GRID and ADAPTIVE you need to set a Grid Spacing larger than half of the Gaussians \n";
     829             :         }
     830             :       }
     831             :     }
     832          10 :     std::string funcl=getLabel() + ".bias";
     833          30 :     for(unsigned i=0; i<pf_n_; ++i) {
     834          20 :       std::vector<Value*> args(1);
     835          20 :       args[0] = pfhold_[i];  //Use first argument in family for interactions.
     836          20 :       std::vector<std::string> gmin_t(1);
     837          20 :       std::vector<std::string> gmax_t(1);
     838          20 :       std::vector<unsigned>    gbin_t(1);
     839             :       gmin_t[0] = gmin[i];
     840             :       gmax_t[0] = gmax[i];
     841          20 :       gbin_t[0] = gbin[i];
     842          20 :       std::unique_ptr<GridBase> BiasGrid_;
     843             :       // Read grid from file
     844          20 :       if(gridreadfilenames_.size()>0) {
     845           2 :         IFile gridfile;
     846           2 :         gridfile.link(*this);
     847           2 :         if(gridfile.FileExist(gridreadfilenames_[i])) {
     848           2 :           gridfile.open(gridreadfilenames_[i]);
     849             :         } else {
     850           0 :           error("The GRID file you want to read: " + gridreadfilenames_[i] + ", cannot be found!");
     851             :         }
     852           2 :         std::string funcl = getLabel() + ".bias";
     853           4 :         BiasGrid_=GridBase::create(funcl, args, gridfile, gmin_t, gmax_t, gbin_t, sparsegrid, spline, true);
     854           2 :         if(BiasGrid_->getDimension() != args.size()) {
     855           0 :           error("mismatch between dimensionality of input grid and number of arguments");
     856             :         }
     857           4 :         if(pfhold_[i]->isPeriodic() != BiasGrid_->getIsPeriodic()[0]) {
     858           0 :           error("periodicity mismatch between arguments and input bias");
     859             :         }
     860           2 :         log.printf("  Restarting from %s:\n",gridreadfilenames_[i].c_str());
     861           2 :         if(getRestart()) {
     862             :           restartedFromGrid=true;
     863             :         }
     864           2 :       } else {
     865          18 :         if(!sparsegrid) {
     866          18 :           BiasGrid_=Tools::make_unique<Grid>(funcl,args,gmin_t,gmax_t,gbin_t,spline,true);
     867             :         } else           {
     868           0 :           BiasGrid_=Tools::make_unique<SparseGrid>(funcl,args,gmin_t,gmax_t,gbin_t,spline,true);
     869             :         }
     870          18 :         std::vector<std::string> actualmin=BiasGrid_->getMin();
     871          18 :         std::vector<std::string> actualmax=BiasGrid_->getMax();
     872             :         std::string is;
     873          18 :         Tools::convert(i,is);
     874          18 :         if(gmin_t[0]!=actualmin[0]) {
     875           0 :           error("GRID_MIN["+is+"] must be adjusted to "+actualmin[0]+" to fit periodicity");
     876             :         }
     877          18 :         if(gmax_t[0]!=actualmax[0]) {
     878           0 :           error("GRID_MAX["+is+"] must be adjusted to "+actualmax[0]+" to fit periodicity");
     879             :         }
     880          18 :       }
     881          20 :       BiasGrids_.emplace_back(std::move(BiasGrid_));
     882          40 :     }
     883             :   }
     884             : 
     885             : 
     886             : 
     887             : // creating vector of ifile* for hills reading
     888             : // open all files at the beginning and read Gaussians if restarting
     889             : 
     890          84 :   for(int j=0; j<mw_n_; ++j) {
     891         126 :     for(unsigned i=0; i<hillsfname_.size(); ++i) {
     892          84 :       unsigned k=j*hillsfname_.size()+i;
     893             :       std::string fname;
     894          84 :       if(mw_dir_!="") {
     895           0 :         if(mw_n_>1) {
     896           0 :           std::stringstream out;
     897           0 :           out << j;
     898           0 :           fname = mw_dir_+"/"+hillsfname_[i]+"."+out.str();
     899           0 :         } else if(walkers_mpi_) {
     900           0 :           fname = mw_dir_+"/"+hillsfname_[i];
     901             :         } else {
     902             :           fname = hillsfname_[i];
     903             :         }
     904             :       } else {
     905          84 :         if(mw_n_>1) {
     906           0 :           std::stringstream out;
     907           0 :           out << j;
     908           0 :           fname = hillsfname_[i]+"."+out.str();
     909           0 :         } else {
     910             :           fname = hillsfname_[i];
     911             :         }
     912             :       }
     913          84 :       ifiles_.emplace_back(Tools::make_unique<IFile>());
     914             :       // this is just a shortcut pointer to the last element:
     915             :       IFile *ifile = ifiles_.back().get();
     916          84 :       ifile->link(*this);
     917          84 :       ifilesnames_.push_back(fname);
     918          84 :       if(ifile->FileExist(fname)) {
     919          18 :         ifile->open(fname);
     920          18 :         if(getRestart()&&!restartedFromGrid) {
     921           2 :           log.printf("  Restarting from %s:",ifilesnames_[k].c_str());
     922           2 :           readGaussians(i,ifiles_[k].get());
     923             :         }
     924          18 :         ifiles_[k]->reset(false);
     925             :         // close only the walker own hills file for later writing
     926          18 :         if(j==mw_id_) {
     927          18 :           ifiles_[k]->close();
     928             :         }
     929             :       } else {
     930             :         // in case a file does not exist and we are restarting, complain that the file was not found
     931          66 :         if(getRestart()) {
     932           2 :           log<<"  WARNING: restart file "<<fname<<" not found\n";
     933             :         }
     934             :       }
     935             :     }
     936             :   }
     937             : 
     938          42 :   comm.Barrier();
     939          42 :   if(comm.Get_rank()==0 && walkers_mpi_) {
     940          18 :     multi_sim_comm.Barrier();
     941             :   }
     942             : 
     943             :   // open hills files for writing
     944         126 :   for(unsigned i=0; i<hillsfname_.size(); ++i) {
     945             :     auto ofile=Tools::make_unique<OFile>();
     946          84 :     ofile->link(*this);
     947             :     // if MPI multiple walkers, only rank 0 will write to file
     948          84 :     if(walkers_mpi_) {
     949          68 :       int r=0;
     950          68 :       if(comm.Get_rank()==0) {
     951          36 :         r=multi_sim_comm.Get_rank();
     952             :       }
     953          68 :       comm.Bcast(r,0);
     954          68 :       if(r>0) {
     955          34 :         ifilesnames_[mw_id_*hillsfname_.size()+i]="/dev/null";
     956             :       }
     957         136 :       ofile->enforceSuffix("");
     958             :     }
     959          84 :     if(mw_n_>1) {
     960           0 :       ofile->enforceSuffix("");
     961             :     }
     962          84 :     ofile->open(ifilesnames_[mw_id_*hillsfname_.size()+i]);
     963          84 :     if(fmt_.length()>0) {
     964          24 :       ofile->fmtField(fmt_);
     965             :     }
     966         168 :     ofile->addConstantField("multivariate");
     967         168 :     ofile->addConstantField("kerneltype");
     968          84 :     if(doInt_[i]) {
     969          16 :       ofile->addConstantField("lower_int").printField("lower_int",lowI_[i]);
     970          16 :       ofile->addConstantField("upper_int").printField("upper_int",uppI_[i]);
     971             :     }
     972          84 :     ofile->setHeavyFlush();
     973             :     // output periodicities of variables
     974          84 :     ofile->setupPrintValue( pfhold_[i] );  //assuming cvs in the same family have the same periodicity and boundaries.
     975             :     // push back
     976          84 :     hillsOfiles_.emplace_back(std::move(ofile));
     977          84 :   }
     978             : 
     979             :   // Dump grid to files
     980          42 :   if(wgridstride_ > 0) {
     981          18 :     for(unsigned i = 0; i < gridfilenames_.size(); ++i) {
     982             :       auto ofile=Tools::make_unique<OFile>();
     983          12 :       ofile->link(*this);
     984          12 :       std::string gridfname_tmp = gridfilenames_[i];
     985          12 :       if(walkers_mpi_) {
     986           8 :         int r = 0;
     987           8 :         if(comm.Get_rank() == 0) {
     988           4 :           r = multi_sim_comm.Get_rank();
     989             :         }
     990           8 :         comm.Bcast(r, 0);
     991           8 :         if(r>0) {
     992             :           gridfname_tmp = "/dev/null";
     993             :         }
     994          16 :         ofile->enforceSuffix("");
     995             :       }
     996          12 :       if(mw_n_>1) {
     997           0 :         ofile->enforceSuffix("");
     998             :       }
     999          12 :       ofile->open(gridfname_tmp);
    1000          12 :       ofile->setHeavyFlush();
    1001          12 :       gridfiles_.emplace_back(std::move(ofile));
    1002          12 :     }
    1003             :   }
    1004             : 
    1005          84 :   log<<"  Bibliography "<<plumed.cite("Pfaendtner and Bonomi. J. Chem. Theory Comput. 11, 5062 (2015)");
    1006          42 :   if(doInt_[0])
    1007           8 :     log<<plumed.cite(
    1008           8 :          "Baftizadeh, Cossio, Pietrucci, and Laio, Curr. Phys. Chem. 2, 79 (2012)");
    1009          42 :   if(mw_n_>1||walkers_mpi_)
    1010          68 :     log<<plumed.cite(
    1011          68 :          "Raiteri, Laio, Gervasio, Micheletti, and Parrinello, J. Phys. Chem. B 110, 3533 (2006)");
    1012          42 :   if(adaptive_!=FlexibleBin::none)
    1013           8 :     log<<plumed.cite(
    1014           8 :          "Branduardi, Bussi, and Parrinello, J. Chem. Theory Comput. 8, 2247 (2012)");
    1015          42 :   if (do_pf_) {
    1016           8 :     log<<plumed.cite("Prakash, Fu, Bonomi, and Pfaendtner, J. Chem. Theory Comput. 14, 4985 (2018)");
    1017             :   }
    1018          42 :   log<<"\n";
    1019             : 
    1020             : 
    1021          84 : }
    1022             : 
    1023           2 : void PBMetaD::readGaussians(unsigned iarg, IFile *ifile) {
    1024           2 :   std::vector<double> center(1);
    1025           2 :   std::vector<double> sigma(1);
    1026             :   double height;
    1027             :   int nhills=0;
    1028           2 :   bool multivariate=false;
    1029           2 :   int family=pfs_[iarg];
    1030             : 
    1031             :   std::vector<Value> tmpvalues;
    1032           4 :   tmpvalues.push_back( Value( this, pfhold_[family]->getName(), false ) );
    1033             : 
    1034          10 :   while(scanOneHill(iarg,ifile,tmpvalues,center,sigma,height,multivariate)) {
    1035             :     ;
    1036           8 :     nhills++;
    1037           8 :     if(welltemp_) {
    1038           8 :       height*=(biasf_-1.0)/biasf_;
    1039             :     }
    1040           8 :     addGaussian(family, Gaussian(center,sigma,height,multivariate));
    1041             :   }
    1042           2 :   log.printf("      %d Gaussians read\n",nhills);
    1043           4 : }
    1044             : 
    1045        1112 : void PBMetaD::writeGaussian(unsigned iarg, const Gaussian& hill, OFile *ofile) {
    1046        2224 :   int family=pfs_[iarg];
    1047        2224 :   ofile->printField("time",getTimeStep()*getStep());
    1048        1112 :   ofile->printField(pfhold_[family],hill.center[0]);
    1049             : 
    1050        2224 :   ofile->printField("kerneltype","stretched-gaussian");
    1051        1112 :   if(hill.multivariate) {
    1052         288 :     ofile->printField("multivariate","true");
    1053         144 :     double lower = std::sqrt(1./hill.sigma[0]);
    1054         288 :     ofile->printField("sigma_"+pfhold_[family]->getName()+"_"+
    1055         144 :                       pfhold_[family]->getName(),lower);
    1056             :   } else {
    1057        1936 :     ofile->printField("multivariate","false");
    1058        1936 :     ofile->printField("sigma_"+pfhold_[family]->getName(),hill.sigma[0]);
    1059             :   }
    1060        1112 :   double height=hill.height;
    1061        1112 :   if(welltemp_) {
    1062        1104 :     height *= biasf_/(biasf_-1.0);
    1063             :   }
    1064        1112 :   ofile->printField("height",height);
    1065        1112 :   ofile->printField("biasf",biasf_);
    1066        1112 :   if(mw_n_>1) {
    1067           0 :     ofile->printField("clock",int(std::time(0)));
    1068             :   }
    1069        1112 :   ofile->printField();
    1070        1112 : }
    1071             : 
    1072        1120 : void PBMetaD::addGaussian(unsigned iarg, const Gaussian& hill) {
    1073        1120 :   if(!grid_) {
    1074         912 :     hills_[iarg].push_back(hill);
    1075             :   } else {
    1076         208 :     std::vector<unsigned> nneighb=getGaussianSupport(iarg, hill);
    1077         208 :     std::vector<Grid::index_t> neighbors=BiasGrids_[iarg]->getNeighbors(hill.center,nneighb);
    1078         208 :     std::vector<double> der(1);
    1079         208 :     std::vector<double> xx(1);
    1080         208 :     if(comm.Get_size()==1) {
    1081        1520 :       for(unsigned i=0; i<neighbors.size(); ++i) {
    1082        1480 :         Grid::index_t ineigh=neighbors[i];
    1083        1480 :         der[0]=0.0;
    1084        1480 :         BiasGrids_[iarg]->getPoint(ineigh,xx);
    1085        1480 :         double bias=evaluateGaussian(iarg,xx,hill,&der[0]);
    1086        1480 :         BiasGrids_[iarg]->addValueAndDerivatives(ineigh,bias,der);
    1087             :       }
    1088             :     } else {
    1089         168 :       unsigned stride=comm.Get_size();
    1090         168 :       unsigned rank=comm.Get_rank();
    1091         168 :       std::vector<double> allder(neighbors.size(),0.0);
    1092         168 :       std::vector<double> allbias(neighbors.size(),0.0);
    1093        3276 :       for(unsigned i=rank; i<neighbors.size(); i+=stride) {
    1094        3108 :         Grid::index_t ineigh=neighbors[i];
    1095        3108 :         BiasGrids_[iarg]->getPoint(ineigh,xx);
    1096        3108 :         allbias[i]=evaluateGaussian(iarg,xx,hill,&allder[i]);
    1097             :       }
    1098         168 :       comm.Sum(allbias);
    1099         168 :       comm.Sum(allder);
    1100        6384 :       for(unsigned i=0; i<neighbors.size(); ++i) {
    1101        6216 :         Grid::index_t ineigh=neighbors[i];
    1102        6216 :         der[0]=allder[i];
    1103        6216 :         BiasGrids_[iarg]->addValueAndDerivatives(ineigh,allbias[i],der);
    1104             :       }
    1105             :     }
    1106             :   }
    1107        1120 : }
    1108             : 
    1109         208 : std::vector<unsigned> PBMetaD::getGaussianSupport(unsigned iarg, const Gaussian& hill) {
    1110             :   std::vector<unsigned> nneigh;
    1111             :   double cutoff;
    1112         208 :   if(hill.multivariate) {
    1113         144 :     double maxautoval=1./hill.sigma[0];
    1114         144 :     cutoff=std::sqrt(2.0*dp2cutoff*maxautoval);
    1115             :   } else {
    1116          64 :     cutoff=std::sqrt(2.0*dp2cutoff)*hill.sigma[0];
    1117             :   }
    1118             : 
    1119         208 :   if(doInt_[iarg]) {
    1120         144 :     if(hill.center[0]+cutoff > uppI_[iarg] || hill.center[0]-cutoff < lowI_[iarg]) {
    1121             :       // in this case, we updated the entire grid to avoid problems
    1122           0 :       return BiasGrids_[iarg]->getNbin();
    1123             :     } else {
    1124         144 :       nneigh.push_back( static_cast<unsigned>(ceil(cutoff/BiasGrids_[iarg]->getDx()[0])));
    1125             :       return nneigh;
    1126             :     }
    1127             :   }
    1128             : 
    1129          64 :   nneigh.push_back( static_cast<unsigned>(ceil(cutoff/BiasGrids_[iarg]->getDx()[0])) );
    1130             : 
    1131             :   return nneigh;
    1132             : }
    1133             : 
    1134        1296 : double PBMetaD::getBiasAndDerivatives(unsigned iarg, const std::vector<double>& cv, double* der) {
    1135        1296 :   double bias=0.0;
    1136        1296 :   int family = pfs_[iarg];
    1137        1296 :   if(!grid_) {
    1138        1000 :     unsigned stride=comm.Get_size();
    1139        1000 :     unsigned rank=comm.Get_rank();
    1140        5520 :     for(unsigned i=rank; i<hills_[family].size(); i+=stride) {
    1141        4520 :       bias += evaluateGaussian(iarg,cv,hills_[family][i],der);
    1142             :     }
    1143        1000 :     comm.Sum(bias);
    1144        1000 :     if(der) {
    1145         540 :       comm.Sum(der,1);
    1146             :     }
    1147             :   } else {
    1148         296 :     if(der) {
    1149         160 :       std::vector<double> vder(1);
    1150         160 :       bias = BiasGrids_[family]->getValueAndDerivatives(cv,vder);
    1151         160 :       der[0] = vder[0];
    1152             :     } else {
    1153         136 :       bias = BiasGrids_[family]->getValue(cv);
    1154             :     }
    1155             :   }
    1156             : 
    1157        1296 :   return bias;
    1158             : }
    1159             : 
    1160        9108 : double PBMetaD::evaluateGaussian(unsigned iarg, const std::vector<double>& cv, const Gaussian& hill, double* der) {
    1161             :   double bias=0.0;
    1162             : // I use a pointer here because cv is const (and should be const)
    1163             : // but when using doInt it is easier to locally replace cv[0] with
    1164             : // the upper/lower limit in case it is out of range
    1165             :   const double *pcv=NULL;
    1166             :   double tmpcv[1]; // tmp array with cv (to be used with doInt_)
    1167        9108 :   tmpcv[0]=cv[0];
    1168             :   bool isOutOfInt = false;
    1169        9108 :   if(doInt_[iarg]) {
    1170        2664 :     if(cv[0]<lowI_[iarg]) {
    1171             :       tmpcv[0]=lowI_[iarg];
    1172             :       isOutOfInt = true;
    1173        2664 :     } else if(cv[0]>uppI_[iarg]) {
    1174             :       tmpcv[0]=uppI_[iarg];
    1175             :       isOutOfInt = true;
    1176             :     }
    1177             :   }
    1178             :   pcv=&(tmpcv[0]);
    1179             : 
    1180        9108 :   if(hill.multivariate) {
    1181        2664 :     double dp  = difference(iarg, hill.center[0], pcv[0]);
    1182        2664 :     double dp2 = 0.5 * dp * dp * hill.sigma[0];
    1183        2664 :     if(dp2<dp2cutoff) {
    1184        2534 :       bias = hill.height*std::exp(-dp2);
    1185        2534 :       if(der && !isOutOfInt) {
    1186        2534 :         der[0] += -bias * dp * hill.sigma[0] * stretchA;
    1187             :       }
    1188        2534 :       bias=stretchA*bias+hill.height*stretchB;
    1189             :     }
    1190             :   } else {
    1191        6444 :     double dp  = difference(iarg, hill.center[0], pcv[0]) * hill.invsigma[0];
    1192        6444 :     double dp2 = 0.5 * dp * dp;
    1193        6444 :     if(dp2<dp2cutoff) {
    1194        6363 :       bias = hill.height*std::exp(-dp2);
    1195        6363 :       if(der && !isOutOfInt) {
    1196        4107 :         der[0] += -bias * dp * hill.invsigma[0] * stretchA;
    1197             :       }
    1198        6363 :       bias=stretchA*bias+hill.height*stretchB;
    1199             :     }
    1200             :   }
    1201             : 
    1202        9108 :   return bias;
    1203             : }
    1204             : 
    1205         340 : void PBMetaD::calculate() {
    1206             :   // this is because presently there is no way to properly pass information
    1207             :   // on adaptive hills (diff) after exchanges:
    1208         340 :   if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) {
    1209           0 :     error("ADAPTIVE=DIFF is not compatible with replica exchange");
    1210             :   }
    1211             : 
    1212         340 :   std::vector<double> cv(1);
    1213             :   double der[1];
    1214         340 :   std::vector<double> bias(getNumberOfArguments());
    1215         340 :   std::vector<double> deriv(getNumberOfArguments());
    1216             : 
    1217         340 :   double ncv = (double) getNumberOfArguments();
    1218             :   double bmin = 1.0e+19;
    1219        1040 :   for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1220         700 :     cv[0]    = getArgument(i);
    1221         700 :     der[0]   = 0.0;
    1222         700 :     bias[i]  = getBiasAndDerivatives(i, cv, der);
    1223         700 :     deriv[i] = der[0];
    1224         700 :     if(bias[i] < bmin) {
    1225             :       bmin = bias[i];
    1226             :     }
    1227             :   }
    1228             :   double ene = 0.;
    1229        1040 :   for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1230         700 :     ene += std::exp((-bias[i]+bmin)/kbt_);
    1231             :   }
    1232             : 
    1233             :   // set Forces - set them to zero if SELECTOR is active
    1234         340 :   if(do_select_) {
    1235           5 :     current_value_ = static_cast<unsigned>(plumed.passMap[selector_]);
    1236             :   }
    1237             : 
    1238         340 :   if(!do_select_ || select_value_==current_value_) {
    1239        1040 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1240         700 :       const double f = - std::exp((-bias[i]+bmin)/kbt_) / (ene) * deriv[i];
    1241         700 :       setOutputForce(i, f);
    1242             :     }
    1243             :   }
    1244             : 
    1245         340 :   if(do_select_ && select_value_!=current_value_) {
    1246           0 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1247           0 :       setOutputForce(i, 0.0);
    1248             :     }
    1249             :   }
    1250             : 
    1251             :   // set bias
    1252         340 :   ene = -kbt_ * (std::log(ene) - std::log(ncv)) + bmin;
    1253         340 :   setBias(ene);
    1254         340 : }
    1255             : 
    1256         340 : void PBMetaD::update() {
    1257             :   bool multivariate;
    1258             :   // adding hills criteria
    1259             :   bool nowAddAHill;
    1260         340 :   if(getStep()%stride_==0 && !isFirstStep_) {
    1261             :     nowAddAHill=true;
    1262             :   } else {
    1263             :     nowAddAHill=false;
    1264          50 :     isFirstStep_=false;
    1265             :   }
    1266             : 
    1267             :   // if you use adaptive, call the FlexibleBin
    1268         340 :   if(adaptive_!=FlexibleBin::none) {
    1269         120 :     for(unsigned i=0; i<getNumberOfArguments(); i++) {
    1270          80 :       flexbin_[i].update(nowAddAHill,i);
    1271             :     }
    1272             :     multivariate=true;
    1273             :   } else {
    1274             :     multivariate=false;
    1275             :   }
    1276             : 
    1277         340 :   if(nowAddAHill && (!do_select_ || select_value_==current_value_)) {
    1278             :     // get all biases and heights
    1279         290 :     std::vector<double> cv(getNumberOfArguments());
    1280         290 :     std::vector<double> bias(getNumberOfArguments());
    1281         290 :     std::vector<double> thissigma(getNumberOfArguments());
    1282         290 :     std::vector<double> height(getNumberOfArguments());
    1283         290 :     std::vector<double> cv_tmp(1);
    1284         290 :     std::vector<double> sigma_tmp(1);
    1285             :     double norm = 0.0;
    1286             :     double bmin = 1.0e+19;
    1287         886 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1288         596 :       int family=pfs_[i];
    1289             :       // get flex/sigmas for each family and assign them to this args sigma
    1290         596 :       if(adaptive_!=FlexibleBin::none) {
    1291          72 :         thissigma[i]=flexbin_[family].getInverseMatrix(i)[0];
    1292             :       } else {
    1293         524 :         thissigma[i]=sigma0_[family];
    1294             :       }
    1295         596 :       cv[i]     = getArgument(i);
    1296         596 :       cv_tmp[0] = getArgument(i);
    1297         596 :       bias[i] = getBiasAndDerivatives(i, cv_tmp);
    1298         596 :       if(bias[i] < bmin) {
    1299             :         bmin = bias[i];
    1300             :       }
    1301             :     }
    1302             :     // calculate heights and norm
    1303         886 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1304         596 :       double h = std::exp((-bias[i]+bmin)/kbt_);
    1305         596 :       norm += h;
    1306         596 :       height[i] = h;
    1307             :     }
    1308             :     // normalize and apply welltemp correction
    1309         886 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1310         596 :       height[i] *=  height0_ / norm;
    1311         596 :       if(welltemp_) {
    1312         588 :         height[i] *= std::exp(-bias[i]/(kbt_*(biasf_-1.0)));
    1313             :       }
    1314             :     }
    1315             : 
    1316             :     // MPI Multiple walkers: share hills and add them all
    1317         290 :     if(walkers_mpi_) {
    1318             :       // Allocate arrays to store all walkers hills
    1319         258 :       std::vector<double> all_cv(mpi_nw_*cv.size(), 0.0);
    1320         258 :       std::vector<double> all_sigma(mpi_nw_*getNumberOfArguments(), 0.0);
    1321         258 :       std::vector<double> all_height(mpi_nw_*height.size(), 0.0);
    1322         258 :       if(comm.Get_rank()==0) {
    1323             :         // fill in value
    1324         390 :         for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1325         260 :           unsigned j = mpi_id_ * getNumberOfArguments() + i;
    1326         260 :           all_cv[j] = cv[i];
    1327         260 :           all_sigma[j]  = thissigma[i];
    1328         260 :           all_height[j] = height[i];
    1329             :         }
    1330             :         // Communicate (only root)
    1331         130 :         multi_sim_comm.Sum(&all_cv[0], all_cv.size());
    1332         130 :         multi_sim_comm.Sum(&all_sigma[0], all_sigma.size());
    1333         130 :         multi_sim_comm.Sum(&all_height[0], all_height.size());
    1334             :       }
    1335             :       // Share info with group members
    1336         258 :       comm.Sum(&all_cv[0], all_cv.size());
    1337         258 :       comm.Sum(&all_sigma[0], all_sigma.size());
    1338         258 :       comm.Sum(&all_height[0], all_height.size());
    1339             :       // now add hills one by one
    1340         774 :       for(unsigned j=0; j<mpi_nw_; ++j) {
    1341        1548 :         for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1342             :           // Add CVs of same family together and write to same file
    1343        1032 :           int family = pfs_[i];
    1344        1032 :           cv_tmp[0]    = all_cv[j*cv.size()+i];
    1345        1032 :           double height_tmp = all_height[j*cv.size()+i];
    1346        1032 :           sigma_tmp[0] = all_sigma[j*cv.size()+i];
    1347        1032 :           Gaussian newhill = Gaussian(cv_tmp, sigma_tmp, height_tmp, multivariate);
    1348        1032 :           addGaussian(family, newhill);
    1349        1032 :           writeGaussian(i, newhill, hillsOfiles_[family].get());
    1350        1032 :         }
    1351             :       }
    1352             :       // just add your own hills
    1353             :     } else {
    1354         112 :       for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1355             :         // Add CVs of same family together and write to same file
    1356          80 :         int family = pfs_[i];
    1357          80 :         cv_tmp[0] = cv[i];
    1358          80 :         if(adaptive_!=FlexibleBin::none) {
    1359           0 :           sigma_tmp[0]=thissigma[i];
    1360             :         } else {
    1361          80 :           sigma_tmp[0] = sigma0_[family];
    1362             :         }
    1363          80 :         Gaussian newhill = Gaussian(cv_tmp, sigma_tmp, height[i], multivariate);
    1364          80 :         addGaussian(family, newhill);
    1365          80 :         writeGaussian(i, newhill, hillsOfiles_[family].get());
    1366          80 :       }
    1367             :     }
    1368             :   }
    1369             : 
    1370             :   // write grid files
    1371         340 :   if(wgridstride_>0 && (getStep()%wgridstride_==0 || getCPT())) {
    1372          14 :     int r = 0;
    1373          14 :     if(walkers_mpi_) {
    1374           4 :       if(comm.Get_rank()==0) {
    1375           2 :         r=multi_sim_comm.Get_rank();
    1376             :       }
    1377           4 :       comm.Bcast(r,0);
    1378             :     }
    1379          14 :     if(r==0) {
    1380          36 :       for(unsigned i=0; i<gridfiles_.size(); ++i) {
    1381          24 :         gridfiles_[i]->rewind();
    1382          24 :         BiasGrids_[i]->writeToFile(*gridfiles_[i]);
    1383          24 :         gridfiles_[i]->flush();
    1384             :       }
    1385             :     }
    1386             :   }
    1387             : 
    1388             :   // if multiple walkers and time to read Gaussians
    1389         340 :   if(mw_n_>1 && getStep()%mw_rstride_==0) {
    1390           0 :     for(int j=0; j<mw_n_; ++j) {
    1391           0 :       for(unsigned i=0; i<hillsfname_.size(); ++i) {
    1392           0 :         unsigned k=j*hillsfname_.size()+i;
    1393             :         // don't read your own Gaussians
    1394           0 :         if(j==mw_id_) {
    1395           0 :           continue;
    1396             :         }
    1397             :         // if the file is not open yet
    1398           0 :         if(!(ifiles_[k]->isOpen())) {
    1399             :           // check if it exists now and open it!
    1400           0 :           if(ifiles_[k]->FileExist(ifilesnames_[k])) {
    1401           0 :             ifiles_[k]->open(ifilesnames_[k]);
    1402           0 :             ifiles_[k]->reset(false);
    1403             :           }
    1404             :           // otherwise read the new Gaussians
    1405             :         } else {
    1406           0 :           log.printf("  Reading hills from %s:",ifilesnames_[k].c_str());
    1407           0 :           readGaussians(i,ifiles_[k].get());
    1408           0 :           ifiles_[k]->reset(false);
    1409             :         }
    1410             :       }
    1411             :     }
    1412             :   }
    1413             : 
    1414         340 : }
    1415             : 
    1416             : /// takes a pointer to the file and a template string with values v and gives back the next center, sigma and height
    1417          10 : bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector<Value> &tmpvalues, std::vector<double> &center, std::vector<double> &sigma, double &height, bool &multivariate) {
    1418             :   double dummy;
    1419          10 :   multivariate=false;
    1420          10 :   Value* argPtr = pfhold_[pfs_[iarg]];
    1421          20 :   if(ifile->scanField("time",dummy)) {
    1422           8 :     ifile->scanField( &tmpvalues[0] );
    1423           8 :     if( tmpvalues[0].isPeriodic() && ! argPtr->isPeriodic() ) {
    1424           0 :       error("in hills file periodicity for variable " + tmpvalues[0].getName() + " does not match periodicity in input");
    1425           8 :     } else if( tmpvalues[0].isPeriodic() ) {
    1426             :       std::string imin, imax;
    1427           0 :       tmpvalues[0].getDomain( imin, imax );
    1428             :       std::string rmin, rmax;
    1429           0 :       argPtr->getDomain( rmin, rmax );
    1430           0 :       if( imin!=rmin || imax!=rmax ) {
    1431           0 :         error("in hills file periodicity for variable " + tmpvalues[0].getName() + " does not match periodicity in input");
    1432             :       }
    1433             :     }
    1434           8 :     center[0]=tmpvalues[0].get();
    1435           8 :     std::string ktype="stretched-gaussian";
    1436          16 :     if( ifile->FieldExist("kerneltype") ) {
    1437          16 :       ifile->scanField("kerneltype",ktype);
    1438             :     }
    1439             : 
    1440           8 :     if( ktype=="gaussian" ) {
    1441           0 :       noStretchWarning();
    1442           8 :     } else if( ktype!="stretched-gaussian") {
    1443           0 :       error("non Gaussian kernels are not supported in MetaD");
    1444             :     }
    1445             : 
    1446             :     std::string sss;
    1447          16 :     ifile->scanField("multivariate",sss);
    1448           8 :     if(sss=="true") {
    1449           0 :       multivariate=true;
    1450           8 :     } else if(sss=="false") {
    1451           8 :       multivariate=false;
    1452             :     } else {
    1453           0 :       plumed_merror("cannot parse multivariate = "+ sss);
    1454             :     }
    1455           8 :     if(multivariate) {
    1456           0 :       ifile->scanField("sigma_"+argPtr->getName()+"_"+
    1457             :                        argPtr->getName(),sigma[0]);
    1458           0 :       sigma[0] = 1./(sigma[0]*sigma[0]);
    1459             :     } else {
    1460          16 :       ifile->scanField("sigma_"+argPtr->getName(),sigma[0]);
    1461             :     }
    1462           8 :     ifile->scanField("height",height);
    1463           8 :     ifile->scanField("biasf",dummy);
    1464          16 :     if(ifile->FieldExist("clock")) {
    1465           0 :       ifile->scanField("clock",dummy);
    1466             :     }
    1467          16 :     if(ifile->FieldExist("lower_int")) {
    1468           0 :       ifile->scanField("lower_int",dummy);
    1469             :     }
    1470          16 :     if(ifile->FieldExist("upper_int")) {
    1471           0 :       ifile->scanField("upper_int",dummy);
    1472             :     }
    1473           8 :     ifile->scanField();
    1474             :     return true;
    1475             :   } else {
    1476             :     return false;
    1477             :   }
    1478             : 
    1479             : }
    1480             : 
    1481         340 : bool PBMetaD::checkNeedsGradients()const {
    1482         340 :   if(adaptive_==FlexibleBin::geometry) {
    1483           0 :     if(getStep()%stride_==0 && !isFirstStep_) {
    1484             :       return true;
    1485             :     } else {
    1486           0 :       return false;
    1487             :     }
    1488             :   } else {
    1489             :     return false;
    1490             :   }
    1491             : }
    1492             : 
    1493             : }
    1494             : }
    1495             : 

Generated by: LCOV version 1.16