LCOV - code coverage report
Current view: top level - bias - MetaD.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 951 1079 88.1 %
Date: 2024-10-11 08:09:47 Functions: 29 31 93.5 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2011-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 "ActionRegister.h"
      24             : #include "core/ActionSet.h"
      25             : #include "core/PlumedMain.h"
      26             : #include "core/Atoms.h"
      27             : #include "core/FlexibleBin.h"
      28             : #include "tools/Exception.h"
      29             : #include "tools/Grid.h"
      30             : #include "tools/Matrix.h"
      31             : #include "tools/OpenMP.h"
      32             : #include "tools/Random.h"
      33             : #include "tools/File.h"
      34             : #include <ctime>
      35             : #include <numeric>
      36             : #if defined(__PLUMED_HAS_GETCWD)
      37             : #include <unistd.h>
      38             : #endif
      39             : 
      40             : namespace PLMD {
      41             : namespace bias {
      42             : 
      43             : //+PLUMEDOC BIAS METAD
      44             : /*
      45             : Used to performed metadynamics on one or more collective variables.
      46             : 
      47             : In a metadynamics simulations a history dependent bias composed of
      48             : intermittently added Gaussian functions is added to the potential \cite metad.
      49             : 
      50             : \f[
      51             : V(\vec{s},t) = \sum_{ k \tau < t} W(k \tau)
      52             : \exp\left(
      53             : -\sum_{i=1}^{d} \frac{(s_i-s_i^{(0)}(k \tau))^2}{2\sigma_i^2}
      54             : \right).
      55             : \f]
      56             : 
      57             : This potential forces the system away from the kinetic traps in the potential energy surface
      58             : and out into the unexplored parts of the energy landscape. Information on the Gaussian
      59             : functions from which this potential is composed is output to a file called HILLS, which
      60             : is used both the restart the calculation and to reconstruct the free energy as a function of the CVs.
      61             : The free energy can be reconstructed from a metadynamics calculation because the final bias is given
      62             : by:
      63             : 
      64             : \f[
      65             : V(\vec{s}) = -F(\vec{s})
      66             : \f]
      67             : 
      68             : During post processing the free energy can be calculated in this way using the \ref sum_hills
      69             : utility.
      70             : 
      71             : In the simplest possible implementation of a metadynamics calculation the expense of a metadynamics
      72             : calculation increases with the length of the simulation as one has to, at every step, evaluate
      73             : the values of a larger and larger number of Gaussian kernels. To avoid this issue you can
      74             : store the bias on a grid.  This approach is similar to that proposed in \cite babi08jcp but has the
      75             : advantage that the grid spacing is independent on the Gaussian width.
      76             : Notice that you should provide the grid boundaries (GRID_MIN and GRID_MAX) and either the number of bins
      77             : for every collective variable (GRID_BIN) or the desired grid spacing (GRID_SPACING).
      78             : In case you provide both PLUMED will use the most conservative choice (highest number of bins) for each dimension.
      79             : In case you do not provide any information about bin size (neither GRID_BIN nor GRID_SPACING)
      80             : PLUMED will use 1/5 of the Gaussian width (SIGMA) as grid spacing if the width is fixed or 1/5 of the minimum
      81             : Gaussian width (SIGMA_MIN) if the width is variable. This default choice should be reasonable for most applications.
      82             : 
      83             : Alternatively to the use of grids, it is possible to use a neighbor list to decrease the cost of evaluating the bias,
      84             : this can be enabled using NLIST. NLIST can be beneficial with more than 2 collective variables, where GRID becomes
      85             : expensive and memory consuming. The neighbor list will be updated everytime the CVs go farther than a cut-off value
      86             : from the position they were at last neighbor list update. Gaussians are added to the neigbhor list if their center
      87             : is within 6.*DP2CUTOFF*sigma*sigma. While the list is updated if the CVs are farther from the center than 0.5 of the
      88             : standard deviation of the Gaussian center distribution of the list. These parameters (6 and 0.5) can be modified using
      89             : NLIST_PARAMETERS. Note that the use of neighbor list does not provide the exact bias.
      90             : 
      91             : Metadynamics can be restarted either from a HILLS file as well as from a GRID, in this second
      92             : case one can first save a GRID using GRID_WFILE (and GRID_WSTRIDE) and at a later stage read
      93             : it using GRID_RFILE.
      94             : 
      95             : The work performed by the METAD bias can be calculated using CALC_WORK, note that this is expensive when not using grids.
      96             : 
      97             : Another option that is available in plumed is well-tempered metadynamics \cite Barducci:2008. In this
      98             : variant of metadynamics the heights of the Gaussian hills are scaled at each step so the bias is now
      99             : given by:
     100             : 
     101             : \f[
     102             : V({s},t)= \sum_{t'=0,\tau_G,2\tau_G,\dots}^{t'<t} W e^{-V({s}({q}(t'),t')/\Delta T} \exp\left(
     103             : -\sum_{i=1}^{d} \frac{(s_i({q})-s_i({q}(t'))^2}{2\sigma_i^2}
     104             : \right),
     105             : \f]
     106             : 
     107             : This method ensures that the bias converges more smoothly. It should be noted that, in the case of well-tempered metadynamics, in
     108             : the output printed the Gaussian height is re-scaled using the bias factor.
     109             : Also notice that with well-tempered metadynamics the HILLS file does not contain the bias,
     110             : but the negative of the free-energy estimate. This choice has the advantage that
     111             : one can restart a simulation using a different value for the \f$\Delta T\f$. The applied bias will be scaled accordingly.
     112             : 
     113             : Note that you can use here also the flexible Gaussian approach  \cite Branduardi:2012dl
     114             : in which you can adapt the Gaussian to the extent of Cartesian space covered by a variable or
     115             : to the space in collective variable covered in a given time. In this case the width of the deposited
     116             : Gaussian potential is denoted by one value only that is a Cartesian space (ADAPTIVE=GEOM) or a time
     117             : (ADAPTIVE=DIFF). Note that a specific integration technique for the deposited Gaussian kernels
     118             : should be used in this case. Check the documentation for utility sum_hills.
     119             : 
     120             : With the keyword INTERVAL one changes the metadynamics algorithm setting the bias force equal to zero
     121             : outside boundary \cite baftizadeh2012protein. If, for example, metadynamics is performed on a CV s and one is interested only
     122             : to the free energy for s > boundary, the history dependent potential is still updated according to the above
     123             : equations but the metadynamics force is set to zero for s < boundary. Notice that Gaussian kernels are added also
     124             : if s < boundary, as the tails of these Gaussian kernels influence VG in the relevant region s > boundary. In this way, the
     125             : force on the system in the region s > boundary comes from both metadynamics and the force field, in the region
     126             : s < boundary only from the latter. This approach allows obtaining a history-dependent bias potential VG that
     127             : fluctuates around a stable estimator, equal to the negative of the free energy far enough from the
     128             : boundaries. Note that:
     129             : - It works only for one-dimensional biases;
     130             : - It works both with and without GRID;
     131             : - The interval limit boundary in a region where the free energy derivative is not large;
     132             : - If in the region outside the limit boundary the system has a free energy minimum, the INTERVAL keyword should
     133             :   be used together with a \ref UPPER_WALLS or \ref LOWER_WALLS at boundary.
     134             : 
     135             : As a final note, since version 2.0.2 when the system is outside of the selected interval the force
     136             : is set to zero and the bias value to the value at the corresponding boundary. This allows acceptances
     137             : for replica exchange methods to be computed correctly.
     138             : 
     139             : Multiple walkers  \cite multiplewalkers can also be used. See below the examples.
     140             : 
     141             : 
     142             : The \f$c(t)\f$ reweighting factor can also be calculated on the fly using the equations
     143             : presented in \cite Tiwary_jp504920s.
     144             : The expression used to calculate \f$c(t)\f$ follows directly from Eq. 3 in \cite Tiwary_jp504920s,
     145             : where \f$F(\vec{s})=-\gamma/(\gamma-1) V(\vec{s})\f$.
     146             : This gives smoother results than equivalent Eqs. 13 and Eqs. 14 in that paper.
     147             : The \f$c(t)\f$ is given by the rct component while the bias
     148             : normalized by \f$c(t)\f$ is given by the rbias component (rbias=bias-rct) which can be used
     149             : to obtain a reweighted histogram.
     150             : The calculation of \f$c(t)\f$ is enabled by using the keyword CALC_RCT.
     151             : By default \f$c(t)\f$ is updated every time the bias changes, but if this slows down the simulation
     152             : the keyword RCT_USTRIDE can be set to a value higher than 1.
     153             : This option requires that a grid is used.
     154             : 
     155             : Additional material and examples can be also found in the tutorials:
     156             : 
     157             : - \ref lugano-3
     158             : 
     159             : Concurrent metadynamics
     160             : as done e.g. in Ref. \cite gil2015enhanced . This indeed can be obtained by using the METAD
     161             : action multiple times in the same input file.
     162             : 
     163             : \par Examples
     164             : 
     165             : The following input is for a standard metadynamics calculation using as
     166             : collective variables the distance between atoms 3 and 5
     167             : and the distance between atoms 2 and 4. The value of the CVs and
     168             : the metadynamics bias potential are written to the COLVAR file every 100 steps.
     169             : \plumedfile
     170             : DISTANCE ATOMS=3,5 LABEL=d1
     171             : DISTANCE ATOMS=2,4 LABEL=d2
     172             : METAD ARG=d1,d2 SIGMA=0.2,0.2 HEIGHT=0.3 PACE=500 LABEL=restraint
     173             : PRINT ARG=d1,d2,restraint.bias STRIDE=100  FILE=COLVAR
     174             : \endplumedfile
     175             : (See also \ref DISTANCE \ref PRINT).
     176             : 
     177             : \par
     178             : If you use adaptive Gaussian kernels, with diffusion scheme where you use
     179             : a Gaussian that should cover the space of 20 time steps in collective variables.
     180             : Note that in this case the histogram correction is needed when summing up hills.
     181             : \plumedfile
     182             : DISTANCE ATOMS=3,5 LABEL=d1
     183             : DISTANCE ATOMS=2,4 LABEL=d2
     184             : METAD ARG=d1,d2 SIGMA=20 HEIGHT=0.3 PACE=500 LABEL=restraint ADAPTIVE=DIFF
     185             : PRINT ARG=d1,d2,restraint.bias STRIDE=100  FILE=COLVAR
     186             : \endplumedfile
     187             : 
     188             : \par
     189             : If you use adaptive Gaussian kernels, with geometrical scheme where you use
     190             : a Gaussian that should cover the space of 0.05 nm in Cartesian space.
     191             : Note that in this case the histogram correction is needed when summing up hills.
     192             : \plumedfile
     193             : DISTANCE ATOMS=3,5 LABEL=d1
     194             : DISTANCE ATOMS=2,4 LABEL=d2
     195             : METAD ARG=d1,d2 SIGMA=0.05 HEIGHT=0.3 PACE=500 LABEL=restraint ADAPTIVE=GEOM
     196             : PRINT ARG=d1,d2,restraint.bias STRIDE=100  FILE=COLVAR
     197             : \endplumedfile
     198             : 
     199             : \par
     200             : When using adaptive Gaussian kernels you might want to limit how the hills width can change.
     201             : You can use SIGMA_MIN and SIGMA_MAX keywords.
     202             : The sigmas should specified in terms of CV so you should use the CV units.
     203             : Note that if you use a negative number, this means that the limit is not set.
     204             : Note also that in this case the histogram correction is needed when summing up hills.
     205             : \plumedfile
     206             : DISTANCE ATOMS=3,5 LABEL=d1
     207             : DISTANCE ATOMS=2,4 LABEL=d2
     208             : METAD ...
     209             :   ARG=d1,d2 SIGMA=0.05 HEIGHT=0.3 PACE=500 LABEL=restraint ADAPTIVE=GEOM
     210             :   SIGMA_MIN=0.2,0.1 SIGMA_MAX=0.5,1.0
     211             : ... METAD
     212             : PRINT ARG=d1,d2,restraint.bias STRIDE=100  FILE=COLVAR
     213             : \endplumedfile
     214             : 
     215             : \par
     216             : Multiple walkers can be also use as in  \cite multiplewalkers
     217             : These are enabled by setting the number of walker used, the id of the
     218             : current walker which interprets the input file, the directory where the
     219             : hills containing files resides, and the frequency to read the other walkers.
     220             : Here is an example
     221             : \plumedfile
     222             : DISTANCE ATOMS=3,5 LABEL=d1
     223             : METAD ...
     224             :    ARG=d1 SIGMA=0.05 HEIGHT=0.3 PACE=500 LABEL=restraint
     225             :    WALKERS_N=10
     226             :    WALKERS_ID=3
     227             :    WALKERS_DIR=../
     228             :    WALKERS_RSTRIDE=100
     229             : ... METAD
     230             : \endplumedfile
     231             : where  WALKERS_N is the total number of walkers, WALKERS_ID is the
     232             : id of the present walker (starting from 0 ) and the WALKERS_DIR is the directory
     233             : where all the walkers are located. WALKERS_RSTRIDE is the number of step between
     234             : one update and the other. Since version 2.2.5, hills files are automatically
     235             : flushed every WALKERS_RSTRIDE steps.
     236             : 
     237             : \par
     238             : The \f$c(t)\f$ reweighting factor can be calculated on the fly using the equations
     239             : presented in \cite Tiwary_jp504920s as described above.
     240             : This is enabled by using the keyword CALC_RCT,
     241             : and can be done only if the bias is defined on a grid.
     242             : \plumedfile
     243             : phi: TORSION ATOMS=1,2,3,4
     244             : psi: TORSION ATOMS=5,6,7,8
     245             : 
     246             : METAD ...
     247             :  LABEL=metad
     248             :  ARG=phi,psi SIGMA=0.20,0.20 HEIGHT=1.20 BIASFACTOR=5 TEMP=300.0 PACE=500
     249             :  GRID_MIN=-pi,-pi GRID_MAX=pi,pi GRID_BIN=150,150
     250             :  CALC_RCT
     251             :  RCT_USTRIDE=10
     252             : ... METAD
     253             : \endplumedfile
     254             : Here we have asked that the calculation is performed every 10 hills deposition by using
     255             : RCT_USTRIDE keyword. If this keyword is not given, the calculation will
     256             : by default be performed every time the bias changes. The \f$c(t)\f$ reweighting factor will be given
     257             : in the rct component while the instantaneous value of the bias potential
     258             : normalized using the \f$c(t)\f$ reweighting factor is given in the rbias component
     259             : [rbias=bias-rct] which can be used to obtain a reweighted histogram or
     260             : free energy surface using the \ref HISTOGRAM analysis.
     261             : 
     262             : \par
     263             : The kinetics of the transitions between basins can also be analyzed on the fly as
     264             : in \cite PRL230602. The flag ACCELERATION turn on accumulation of the acceleration
     265             : factor that can then be used to determine the rate. This method can be used together
     266             : with \ref COMMITTOR analysis to stop the simulation when the system get to the target basin.
     267             : It must be used together with Well-Tempered Metadynamics. If restarting from a previous
     268             : metadynamics you need to use the ACCELERATION_RFILE keyword to give the name of the
     269             : data file from which the previous value of the acceleration factor should be read, otherwise the
     270             : calculation of the acceleration factor will be wrong.
     271             : 
     272             : \par
     273             : By using the flag FREQUENCY_ADAPTIVE the frequency adaptive scheme introduced in \cite Wang-JCP-2018
     274             : is turned on. The frequency for hill addition then changes dynamically based on the acceleration factor
     275             : according to the following equation
     276             : \f[
     277             : \tau_{\mathrm{dep}}(t) =
     278             : \min\left[
     279             : \tau_0 \cdot
     280             : \max\left[\frac{\alpha(t)}{\theta},1\right]
     281             : ,\tau_{c}
     282             : \right]
     283             : \f]
     284             : where \f$\tau_0\f$ is the initial hill addition frequency given by the PACE keyword,
     285             : \f$\tau_{c}\f$ is the maximum allowed frequency given by the FA_MAX_PACE keyword,
     286             : \f$\alpha(t)\f$ is the instantaneous acceleration factor at time \f$t\f$,
     287             : and \f$\theta\f$ is a threshold value that acceleration factor has to reach before
     288             : triggering a change in the hill addition frequency given by the FA_MIN_ACCELERATION keyword.
     289             : The frequency for updating the hill addition frequency according to this equation is
     290             : given by the FA_UPDATE_FREQUENCY keyword, by default it is the same as the value given
     291             : in PACE. The hill hill addition frequency increase monotonously such that if the
     292             : instantaneous acceleration factor is lower than in the previous updating step the
     293             : previous \f$\tau_{\mathrm{dep}}\f$ is kept rather than updating it to a lower value.
     294             : The instantaneous hill addition frequency \f$\tau_{\mathrm{dep}}(t)\f$ is outputted
     295             : to pace component. Note that if restarting from a previous metadynamics run you need to
     296             : use the ACCELERATION_RFILE keyword to read in the acceleration factors from the
     297             : previous run, otherwise the hill addition frequency will start from the initial
     298             : frequency.
     299             : 
     300             : 
     301             : \par
     302             : You can also provide a target distribution using the keyword TARGET
     303             : \cite white2015designing
     304             : \cite marinelli2015ensemble
     305             : \cite gil2016empirical
     306             : The TARGET should be a grid containing a free-energy (i.e. the -\f$k_B\f$T*log of the desired target distribution).
     307             : Gaussian kernels will then be scaled by a factor
     308             : \f[
     309             : e^{\beta(\tilde{F}(s)-\tilde{F}_{max})}
     310             : \f]
     311             : Here \f$\tilde{F}(s)\f$ is the free energy defined on the grid and \f$\tilde{F}_{max}\f$ its maximum value.
     312             : Notice that we here used the maximum value as in ref \cite gil2016empirical
     313             : This choice allows to avoid exceedingly large Gaussian kernels to be added. However,
     314             : it could make the Gaussian too small. You should always choose carefully the HEIGHT parameter
     315             : in this case.
     316             : The grid file should be similar to other PLUMED grid files in that it should contain
     317             : both the target free-energy and its derivatives.
     318             : 
     319             : Notice that if you wish your simulation to converge to the target free energy you should use
     320             : the DAMPFACTOR command to provide a global tempering \cite dama2014well
     321             : Alternatively, if you use a BIASFACTOR your simulation will converge to a free
     322             : energy that is a linear combination of the target free energy and of the intrinsic free energy
     323             : determined by the original force field.
     324             : 
     325             : \plumedfile
     326             : DISTANCE ATOMS=3,5 LABEL=d1
     327             : METAD ...
     328             :  LABEL=t1
     329             :  ARG=d1 SIGMA=0.05 TAU=200 DAMPFACTOR=100 PACE=250
     330             :  GRID_MIN=1.14 GRID_MAX=1.32 GRID_BIN=6
     331             :  TARGET=dist.grid
     332             : ... METAD
     333             : 
     334             : PRINT ARG=d1,t1.bias STRIDE=100 FILE=COLVAR
     335             : \endplumedfile
     336             : 
     337             : The file dist.dat for this calculation would read:
     338             : 
     339             : \auxfile{dist.grid}
     340             : #! FIELDS d1 t1.target der_d1
     341             : #! SET min_d1 1.14
     342             : #! SET max_d1 1.32
     343             : #! SET nbins_d1  6
     344             : #! SET periodic_d1 false
     345             :    1.1400   0.0031   0.1101
     346             :    1.1700   0.0086   0.2842
     347             :    1.2000   0.0222   0.6648
     348             :    1.2300   0.0521   1.4068
     349             :    1.2600   0.1120   2.6873
     350             :    1.2900   0.2199   4.6183
     351             :    1.3200   0.3948   7.1055
     352             : \endauxfile
     353             : 
     354             : Notice that BIASFACTOR can also be chosen as equal to 1. In this case one will perform
     355             : unbiased sampling. Instead of using HEIGHT, one should provide the TAU parameter.
     356             : \plumedfile
     357             : d: DISTANCE ATOMS=3,5
     358             : METAD ARG=d SIGMA=0.1 TAU=4.0 TEMP=300 PACE=100 BIASFACTOR=1.0
     359             : \endplumedfile
     360             : The HILLS file obtained will still work with `plumed sum_hills` so as to plot a free-energy.
     361             : The case where this makes sense is probably that of RECT simulations.
     362             : 
     363             : Regarding RECT simulations, you can also use the RECT keyword so as to avoid using multiple input files.
     364             : For instance, a single input file will be
     365             : \plumedfile
     366             : d: DISTANCE ATOMS=3,5
     367             : METAD ARG=d SIGMA=0.1 TAU=4.0 TEMP=300 PACE=100 RECT=1.0,1.5,2.0,3.0
     368             : \endplumedfile
     369             : The number of elements in the RECT array should be equal to the number of replicas.
     370             : 
     371             : */
     372             : //+ENDPLUMEDOC
     373             : 
     374             : class MetaD : public Bias {
     375             : 
     376             : private:
     377             :   struct Gaussian {
     378             :     bool   multivariate; // this is required to discriminate the one dimensional case
     379             :     double height;
     380             :     std::vector<double> center;
     381             :     std::vector<double> sigma;
     382             :     std::vector<double> invsigma;
     383        5200 :     Gaussian(const bool m, const double h, const std::vector<double>& c, const std::vector<double>& s):
     384        5200 :       multivariate(m),height(h),center(c),sigma(s),invsigma(s) {
     385             :       // to avoid troubles from zero element in flexible hills
     386       15137 :       for(unsigned i=0; i<invsigma.size(); ++i) {
     387        9937 :         if(std::abs(invsigma[i])>1.e-20) invsigma[i]=1.0/invsigma[i] ;
     388           0 :         else invsigma[i]=0.0;
     389             :       }
     390        5200 :     }
     391             :   };
     392             :   struct TemperingSpecs {
     393             :     bool is_active;
     394             :     std::string name_stem;
     395             :     std::string name;
     396             :     double biasf;
     397             :     double threshold;
     398             :     double alpha;
     399         154 :     inline TemperingSpecs(bool is_active, const std::string &name_stem, const std::string &name, double biasf, double threshold, double alpha) :
     400         154 :       is_active(is_active), name_stem(name_stem), name(name), biasf(biasf), threshold(threshold), alpha(alpha)
     401         154 :     {}
     402             :   };
     403             :   // general setup
     404             :   double kbt_;
     405             :   int stride_;
     406             :   bool calc_work_;
     407             :   // well-tempered MetaD
     408             :   bool welltemp_;
     409             :   double biasf_;
     410             :   // output files format
     411             :   std::string fmt_;
     412             :   // first step?
     413             :   bool isFirstStep_;
     414             :   // Gaussian starting parameters
     415             :   double height0_;
     416             :   std::vector<double> sigma0_;
     417             :   std::vector<double> sigma0min_;
     418             :   std::vector<double> sigma0max_;
     419             :   // Gaussians
     420             :   std::vector<Gaussian> hills_;
     421             :   std::unique_ptr<FlexibleBin> flexbin_;
     422             :   int adaptive_;
     423             :   OFile hillsOfile_;
     424             :   std::vector<std::unique_ptr<IFile>> ifiles_;
     425             :   std::vector<std::string> ifilesnames_;
     426             :   // Grids
     427             :   bool grid_;
     428             :   std::unique_ptr<GridBase> BiasGrid_;
     429             :   OFile gridfile_;
     430             :   bool storeOldGrids_;
     431             :   int wgridstride_;
     432             :   // multiple walkers
     433             :   int mw_n_;
     434             :   std::string mw_dir_;
     435             :   int mw_id_;
     436             :   int mw_rstride_;
     437             :   bool walkers_mpi_;
     438             :   unsigned mpi_nw_;
     439             :   // flying gaussians
     440             :   bool flying_;
     441             :   // kinetics from metadynamics
     442             :   bool acceleration_;
     443             :   double acc_;
     444             :   double acc_restart_mean_;
     445             :   // transition-tempering metadynamics
     446             :   bool calc_max_bias_;
     447             :   double max_bias_;
     448             :   bool calc_transition_bias_;
     449             :   double transition_bias_;
     450             :   std::vector<std::vector<double> > transitionwells_;
     451             :   static const size_t n_tempering_options_ = 1;
     452             :   static const std::string tempering_names_[1][2];
     453             :   double dampfactor_;
     454             :   struct TemperingSpecs tt_specs_;
     455             :   std::string targetfilename_;
     456             :   std::unique_ptr<GridBase> TargetGrid_;
     457             :   // frequency adaptive metadynamics
     458             :   int current_stride_;
     459             :   bool freq_adaptive_;
     460             :   int fa_update_frequency_;
     461             :   int fa_max_stride_;
     462             :   double fa_min_acceleration_;
     463             :   // intervals
     464             :   double uppI_;
     465             :   double lowI_;
     466             :   bool doInt_;
     467             :   // reweighting
     468             :   bool calc_rct_;
     469             :   double reweight_factor_;
     470             :   unsigned rct_ustride_;
     471             :   // work
     472             :   double work_;
     473             :   // neighbour list stuff
     474             :   bool nlist_;
     475             :   bool nlist_update_;
     476             :   unsigned nlist_steps_;
     477             :   std::array<double,2> nlist_param_;
     478             :   std::vector<Gaussian> nlist_hills_;
     479             :   std::vector<double> nlist_center_;
     480             :   std::vector<double> nlist_dev2_;
     481             : 
     482             :   double stretchA=1.0;
     483             :   double stretchB=0.0;
     484             : 
     485             :   bool noStretchWarningDone=false;
     486             : 
     487          12 :   void noStretchWarning() {
     488          12 :     if(!noStretchWarningDone) {
     489           3 :       log<<"\nWARNING: you are using a HILLS file with Gaussian kernels, PLUMED 2.8 uses stretched Gaussians by default\n";
     490             :     }
     491          12 :     noStretchWarningDone=true;
     492          12 :   }
     493             : 
     494             :   static void registerTemperingKeywords(const std::string &name_stem, const std::string &name, Keywords &keys);
     495             :   void   readTemperingSpecs(TemperingSpecs &t_specs);
     496             :   void   logTemperingSpecs(const TemperingSpecs &t_specs);
     497             :   void   readGaussians(IFile*);
     498             :   void   writeGaussian(const Gaussian&,OFile&);
     499             :   void   addGaussian(const Gaussian&);
     500             :   double getHeight(const std::vector<double>&);
     501             :   void   temperHeight(double &height, const TemperingSpecs &t_specs, const double tempering_bias);
     502             :   double getBias(const std::vector<double>&);
     503             :   double getBiasAndDerivatives(const std::vector<double>&, std::vector<double>&);
     504             :   double evaluateGaussian(const std::vector<double>&, const Gaussian&);
     505             :   double evaluateGaussianAndDerivatives(const std::vector<double>&, const Gaussian&,std::vector<double>&,std::vector<double>&);
     506             :   double getGaussianNormalization(const Gaussian&);
     507             :   std::vector<unsigned> getGaussianSupport(const Gaussian&);
     508             :   bool   scanOneHill(IFile* ifile, std::vector<Value>& v, std::vector<double>& center, std::vector<double>& sigma, double& height, bool& multivariate);
     509             :   void   computeReweightingFactor();
     510             :   double getTransitionBarrierBias();
     511             :   void   updateFrequencyAdaptiveStride();
     512             :   void   updateNlist();
     513             : 
     514             : public:
     515             :   explicit MetaD(const ActionOptions&);
     516             :   void calculate() override;
     517             :   void update() override;
     518             :   static void registerKeywords(Keywords& keys);
     519             :   bool checkNeedsGradients()const override;
     520             : };
     521             : 
     522       10721 : PLUMED_REGISTER_ACTION(MetaD,"METAD")
     523             : 
     524         156 : void MetaD::registerKeywords(Keywords& keys) {
     525         156 :   Bias::registerKeywords(keys);
     526         312 :   keys.addOutputComponent("rbias","CALC_RCT","the instantaneous value of the bias normalized using the \\f$c(t)\\f$ reweighting factor [rbias=bias-rct]."
     527             :                           "This component can be used to obtain a reweighted histogram.");
     528         312 :   keys.addOutputComponent("rct","CALC_RCT","the reweighting factor \\f$c(t)\\f$.");
     529         312 :   keys.addOutputComponent("work","CALC_WORK","accumulator for work");
     530         312 :   keys.addOutputComponent("acc","ACCELERATION","the metadynamics acceleration factor");
     531         312 :   keys.addOutputComponent("maxbias", "CALC_MAX_BIAS", "the maximum of the metadynamics V(s, t)");
     532         468 :   keys.addOutputComponent("transbias", "CALC_TRANSITION_BIAS", "the metadynamics transition bias V*(t)");
     533         468 :   keys.addOutputComponent("pace","FREQUENCY_ADAPTIVE","the hill addition frequency when employing frequency adaptive metadynamics");
     534         312 :   keys.addOutputComponent("nlker","NLIST","number of hills in the neighbor list");
     535         312 :   keys.addOutputComponent("nlsteps","NLIST","number of steps from last neighbor list update");
     536         156 :   keys.use("ARG");
     537         312 :   keys.add("compulsory","SIGMA","the widths of the Gaussian hills");
     538         312 :   keys.add("compulsory","PACE","the frequency for hill addition");
     539         312 :   keys.add("compulsory","FILE","HILLS","a file in which the list of added hills is stored");
     540         312 :   keys.add("optional","HEIGHT","the heights of the Gaussian hills. Compulsory unless TAU and either BIASFACTOR or DAMPFACTOR are given");
     541         312 :   keys.add("optional","FMT","specify format for HILLS files (useful for decrease the number of digits in regtests)");
     542         312 :   keys.add("optional","BIASFACTOR","use well tempered metadynamics and use this bias factor.  Please note you must also specify temp");
     543         312 :   keys.addFlag("CALC_WORK",false,"calculate the total accumulated work done by the bias since last restart");
     544         312 :   keys.add("optional","RECT","list of bias factors for all the replicas");
     545         312 :   keys.add("optional","DAMPFACTOR","damp hills with exp(-max(V)/(\\f$k_B\\f$T*DAMPFACTOR)");
     546         312 :   for (size_t i = 0; i < n_tempering_options_; i++) {
     547         156 :     registerTemperingKeywords(tempering_names_[i][0], tempering_names_[i][1], keys);
     548             :   }
     549         312 :   keys.add("optional","TARGET","target to a predefined distribution");
     550         312 :   keys.add("optional","TEMP","the system temperature - this is only needed if you are doing well-tempered metadynamics");
     551         312 :   keys.add("optional","TAU","in well tempered metadynamics, sets height to (\\f$k_B \\Delta T\\f$*pace*timestep)/tau");
     552         312 :   keys.addFlag("CALC_RCT",false,"calculate the \\f$c(t)\\f$ reweighting factor and use that to obtain the normalized bias [rbias=bias-rct]."
     553             :                "This method is not compatible with metadynamics not on a grid.");
     554         312 :   keys.add("optional","RCT_USTRIDE","the update stride for calculating the \\f$c(t)\\f$ reweighting factor."
     555             :            "The default 1, so \\f$c(t)\\f$ is updated every time the bias is updated.");
     556         312 :   keys.add("optional","GRID_MIN","the lower bounds for the grid");
     557         312 :   keys.add("optional","GRID_MAX","the upper bounds for the grid");
     558         312 :   keys.add("optional","GRID_BIN","the number of bins for the grid");
     559         312 :   keys.add("optional","GRID_SPACING","the approximate grid spacing (to be used as an alternative or together with GRID_BIN)");
     560         312 :   keys.addFlag("GRID_SPARSE",false,"use a sparse grid to store hills");
     561         312 :   keys.addFlag("GRID_NOSPLINE",false,"don't use spline interpolation with grids");
     562         312 :   keys.add("optional","GRID_WSTRIDE","write the grid to a file every N steps");
     563         312 :   keys.add("optional","GRID_WFILE","the file on which to write the grid");
     564         312 :   keys.add("optional","GRID_RFILE","a grid file from which the bias should be read at the initial step of the simulation");
     565         312 :   keys.addFlag("STORE_GRIDS",false,"store all the grid files the calculation generates. They will be deleted if this keyword is not present");
     566         312 :   keys.addFlag("NLIST",false,"Use neighbor list for kernels summation, faster but experimental");
     567         468 :   keys.add("optional", "NLIST_PARAMETERS","(default=6.,0.5) the two cutoff parameters for the Gaussians neighbor list");
     568         312 :   keys.add("optional","ADAPTIVE","use a geometric (=GEOM) or diffusion (=DIFF) based hills width scheme. Sigma is one number that has distance units or time step dimensions");
     569         312 :   keys.add("optional","SIGMA_MAX","the upper bounds for the sigmas (in CV units) when using adaptive hills. Negative number means no bounds ");
     570         312 :   keys.add("optional","SIGMA_MIN","the lower bounds for the sigmas (in CV units) when using adaptive hills. Negative number means no bounds ");
     571         312 :   keys.add("optional","WALKERS_ID", "walker id");
     572         312 :   keys.add("optional","WALKERS_N", "number of walkers");
     573         312 :   keys.add("optional","WALKERS_DIR", "shared directory with the hills files from all the walkers");
     574         312 :   keys.add("optional","WALKERS_RSTRIDE","stride for reading hills files");
     575         312 :   keys.addFlag("WALKERS_MPI",false,"Switch on MPI version of multiple walkers - not compatible with WALKERS_* options other than WALKERS_DIR");
     576         312 :   keys.add("optional","INTERVAL","one dimensional lower and upper limits, outside the limits the system will not feel the biasing force.");
     577         312 :   keys.addFlag("FLYING_GAUSSIAN",false,"Switch on flying Gaussian method, must be used with WALKERS_MPI");
     578         312 :   keys.addFlag("ACCELERATION",false,"Set to TRUE if you want to compute the metadynamics acceleration factor.");
     579         468 :   keys.add("optional","ACCELERATION_RFILE","a data file from which the acceleration should be read at the initial step of the simulation");
     580         312 :   keys.addFlag("CALC_MAX_BIAS", false, "Set to TRUE if you want to compute the maximum of the metadynamics V(s, t)");
     581         312 :   keys.addFlag("CALC_TRANSITION_BIAS", false, "Set to TRUE if you want to compute a metadynamics transition bias V*(t)");
     582         312 :   keys.add("numbered", "TRANSITIONWELL", "This keyword appears multiple times as TRANSITIONWELL followed by an integer. Each specifies the coordinates for one well as in transition-tempered metadynamics. At least one must be provided.");
     583         312 :   keys.addFlag("FREQUENCY_ADAPTIVE",false,"Set to TRUE if you want to enable frequency adaptive metadynamics such that the frequency for hill addition to change dynamically based on the acceleration factor.");
     584         468 :   keys.add("optional","FA_UPDATE_FREQUENCY","the frequency for updating the hill addition pace in frequency adaptive metadynamics, by default this is equal to the value given in PACE");
     585         312 :   keys.add("optional","FA_MAX_PACE","the maximum hill addition frequency allowed in frequency adaptive metadynamics. By default there is no maximum value.");
     586         468 :   keys.add("optional","FA_MIN_ACCELERATION","only update the hill addition pace in frequency adaptive metadynamics after reaching the minimum acceleration factor given here. By default it is 1.0.");
     587         156 :   keys.use("RESTART");
     588         156 :   keys.use("UPDATE_FROM");
     589         156 :   keys.use("UPDATE_UNTIL");
     590         156 : }
     591             : 
     592             : const std::string MetaD::tempering_names_[1][2] = {{"TT", "transition tempered"}};
     593             : 
     594         156 : void MetaD::registerTemperingKeywords(const std::string &name_stem, const std::string &name, Keywords &keys) {
     595         468 :   keys.add("optional", name_stem + "BIASFACTOR", "use " + name + " metadynamics with this bias factor.  Please note you must also specify temp");
     596         468 :   keys.add("optional", name_stem + "BIASTHRESHOLD", "use " + name + " metadynamics with this bias threshold.  Please note you must also specify " + name_stem + "BIASFACTOR");
     597         468 :   keys.add("optional", name_stem + "ALPHA", "use " + name + " metadynamics with this hill size decay exponent parameter.  Please note you must also specify " + name_stem + "BIASFACTOR");
     598         156 : }
     599             : 
     600         155 : MetaD::MetaD(const ActionOptions& ao):
     601             :   PLUMED_BIAS_INIT(ao),
     602         154 :   kbt_(0.0),
     603         154 :   stride_(0),
     604         154 :   calc_work_(false),
     605         154 :   welltemp_(false),
     606         154 :   biasf_(-1.0),
     607         154 :   isFirstStep_(true),
     608         154 :   height0_(std::numeric_limits<double>::max()),
     609         154 :   adaptive_(FlexibleBin::none),
     610         154 :   grid_(false),
     611         154 :   wgridstride_(0),
     612         154 :   mw_n_(1), mw_dir_(""), mw_id_(0), mw_rstride_(1),
     613         154 :   walkers_mpi_(false), mpi_nw_(0),
     614         154 :   flying_(false),
     615         154 :   acceleration_(false), acc_(0.0), acc_restart_mean_(0.0),
     616         154 :   calc_max_bias_(false), max_bias_(0.0),
     617         154 :   calc_transition_bias_(false), transition_bias_(0.0),
     618         154 :   dampfactor_(0.0),
     619         308 :   tt_specs_(false, "TT", "Transition Tempered", -1.0, 0.0, 1.0),
     620         154 :   current_stride_(0),
     621         154 :   freq_adaptive_(false),
     622         154 :   fa_update_frequency_(0),
     623         154 :   fa_max_stride_(0),
     624         154 :   fa_min_acceleration_(1.0),
     625         154 :   uppI_(-1), lowI_(-1), doInt_(false),
     626         154 :   calc_rct_(false),
     627         154 :   reweight_factor_(0.0),
     628         154 :   rct_ustride_(1),
     629         154 :   work_(0),
     630         154 :   nlist_(false),
     631         154 :   nlist_update_(false),
     632         463 :   nlist_steps_(0)
     633             : {
     634         154 :   if(!dp2cutoffNoStretch()) {
     635         154 :     stretchA=dp2cutoffA;
     636         154 :     stretchB=dp2cutoffB;
     637             :   }
     638             :   // parse the flexible hills
     639             :   std::string adaptiveoption;
     640             :   adaptiveoption="NONE";
     641         308 :   parse("ADAPTIVE",adaptiveoption);
     642         154 :   if(adaptiveoption=="GEOM") {
     643          22 :     log.printf("  Uses Geometry-based hills width: sigma must be in distance units and only one sigma is needed\n");
     644          22 :     adaptive_=FlexibleBin::geometry;
     645         132 :   } else if(adaptiveoption=="DIFF") {
     646           3 :     log.printf("  Uses Diffusion-based hills width: sigma must be in time steps and only one sigma is needed\n");
     647           3 :     adaptive_=FlexibleBin::diffusion;
     648         129 :   } else if(adaptiveoption=="NONE") {
     649         128 :     adaptive_=FlexibleBin::none;
     650             :   } else {
     651           1 :     error("I do not know this type of adaptive scheme");
     652             :   }
     653             : 
     654         153 :   parse("FMT",fmt_);
     655             : 
     656             :   // parse the sigma
     657         153 :   parseVector("SIGMA",sigma0_);
     658         153 :   if(adaptive_==FlexibleBin::none) {
     659             :     // if you use normal sigma you need one sigma per argument
     660         128 :     if( sigma0_.size()!=getNumberOfArguments() ) error("number of arguments does not match number of SIGMA parameters");
     661             :   } else {
     662             :     // if you use flexible hills you need one sigma
     663          25 :     if(sigma0_.size()!=1) {
     664           1 :       error("If you choose ADAPTIVE you need only one sigma according to your choice of type (GEOM/DIFF)");
     665             :     }
     666             :     // if adaptive then the number must be an integer
     667          24 :     if(adaptive_==FlexibleBin::diffusion) {
     668           3 :       if(int(sigma0_[0])-sigma0_[0]>1.e-9 || int(sigma0_[0])-sigma0_[0] <-1.e-9 || int(sigma0_[0])<1 ) {
     669           0 :         error("In case of adaptive hills with diffusion, the sigma must be an integer which is the number of time steps\n");
     670             :       }
     671             :     }
     672             :     // here evtl parse the sigma min and max values
     673          48 :     parseVector("SIGMA_MIN",sigma0min_);
     674          24 :     if(sigma0min_.size()>0 && sigma0min_.size()!=getNumberOfArguments()) {
     675           1 :       error("the number of SIGMA_MIN values be the same of the number of the arguments");
     676          23 :     } else if(sigma0min_.size()==0) {
     677          23 :       sigma0min_.resize(getNumberOfArguments());
     678          67 :       for(unsigned i=0; i<getNumberOfArguments(); i++) {sigma0min_[i]=-1.;}
     679             :     }
     680             : 
     681          46 :     parseVector("SIGMA_MAX",sigma0max_);
     682          23 :     if(sigma0max_.size()>0 && sigma0max_.size()!=getNumberOfArguments()) {
     683           1 :       error("the number of SIGMA_MAX values be the same of the number of the arguments");
     684          22 :     } else if(sigma0max_.size()==0) {
     685          22 :       sigma0max_.resize(getNumberOfArguments());
     686          64 :       for(unsigned i=0; i<getNumberOfArguments(); i++) {sigma0max_[i]=-1.;}
     687             :     }
     688             : 
     689          44 :     flexbin_=Tools::make_unique<FlexibleBin>(adaptive_,this,sigma0_[0],sigma0min_,sigma0max_);
     690             :   }
     691             : 
     692             :   // note: HEIGHT is not compulsory, since one could use the TAU keyword, see below
     693         150 :   parse("HEIGHT",height0_);
     694         150 :   parse("PACE",stride_);
     695         149 :   if(stride_<=0) error("frequency for hill addition is nonsensical");
     696         149 :   current_stride_ = stride_;
     697         156 :   std::string hillsfname="HILLS";
     698         149 :   parse("FILE",hillsfname);
     699             : 
     700             :   // Manually set to calculate special bias quantities
     701             :   // throughout the course of simulation. (These are chosen due to
     702             :   // relevance for tempering and event-driven logic as well.)
     703         149 :   parseFlag("CALC_MAX_BIAS", calc_max_bias_);
     704         300 :   parseFlag("CALC_TRANSITION_BIAS", calc_transition_bias_);
     705             : 
     706             :   std::vector<double> rect_biasf_;
     707         298 :   parseVector("RECT",rect_biasf_);
     708         149 :   if(rect_biasf_.size()>0) {
     709          18 :     int r=0;
     710          18 :     if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank();
     711          18 :     comm.Bcast(r,0);
     712          18 :     biasf_=rect_biasf_[r];
     713          18 :     log<<"  You are using RECT\n";
     714             :   } else {
     715         262 :     parse("BIASFACTOR",biasf_);
     716             :   }
     717         149 :   if( biasf_<1.0  && biasf_!=-1.0) error("well tempered bias factor is nonsensical");
     718         149 :   parse("DAMPFACTOR",dampfactor_);
     719         149 :   double temp=0.0;
     720         149 :   parse("TEMP",temp);
     721         149 :   if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp;
     722          94 :   else kbt_=plumed.getAtoms().getKbT();
     723         149 :   if(biasf_>=1.0) {
     724          37 :     if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, with well-tempered metad you must specify it using TEMP");
     725          37 :     welltemp_=true;
     726             :   }
     727         149 :   if(dampfactor_>0.0) {
     728           2 :     if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, with damped metad you must specify it using TEMP");
     729             :   }
     730             : 
     731         149 :   parseFlag("CALC_WORK",calc_work_);
     732             : 
     733             :   // Set transition tempering parameters.
     734             :   // Transition wells are read later via calc_transition_bias_.
     735         149 :   readTemperingSpecs(tt_specs_);
     736         149 :   if (tt_specs_.is_active) calc_transition_bias_ = true;
     737             : 
     738             :   // If any previous option specified to calculate a transition bias,
     739             :   // now read the transition wells for that quantity.
     740         149 :   if (calc_transition_bias_) {
     741          13 :     std::vector<double> tempcoords(getNumberOfArguments());
     742          26 :     for (unsigned i = 0; ; i++) {
     743          78 :       if (!parseNumberedVector("TRANSITIONWELL", i, tempcoords) ) break;
     744          26 :       if (tempcoords.size() != getNumberOfArguments()) {
     745           0 :         error("incorrect number of coordinates for transition tempering well");
     746             :       }
     747          26 :       transitionwells_.push_back(tempcoords);
     748             :     }
     749             :   }
     750             : 
     751         298 :   parse("TARGET",targetfilename_);
     752         149 :   if(targetfilename_.length()>0 && kbt_==0.0)  error("with TARGET temperature must be specified");
     753         149 :   double tau=0.0;
     754         149 :   parse("TAU",tau);
     755         149 :   if(tau==0.0) {
     756         127 :     if(height0_==std::numeric_limits<double>::max()) error("At least one between HEIGHT and TAU should be specified");
     757             :     // if tau is not set, we compute it here from the other input parameters
     758         127 :     if(welltemp_) tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_;
     759         109 :     else if(dampfactor_>0.0) tau=(kbt_*dampfactor_)/height0_*getTimeStep()*stride_;
     760             :   } else {
     761          22 :     if(height0_!=std::numeric_limits<double>::max()) error("At most one between HEIGHT and TAU should be specified");
     762          22 :     if(welltemp_) {
     763          19 :       if(biasf_!=1.0) height0_=(kbt_*(biasf_-1.0))/tau*getTimeStep()*stride_;
     764           4 :       else           height0_=kbt_/tau*getTimeStep()*stride_; // special case for gamma=1
     765             :     }
     766           3 :     else if(dampfactor_>0.0) height0_=(kbt_*dampfactor_)/tau*getTimeStep()*stride_;
     767           1 :     else error("TAU only makes sense in well-tempered or damped metadynamics");
     768             :   }
     769             : 
     770             :   // Grid Stuff
     771         150 :   std::vector<std::string> gmin(getNumberOfArguments());
     772         296 :   parseVector("GRID_MIN",gmin);
     773         148 :   if(gmin.size()!=getNumberOfArguments() && gmin.size()!=0) error("not enough values for GRID_MIN");
     774         148 :   std::vector<std::string> gmax(getNumberOfArguments());
     775         296 :   parseVector("GRID_MAX",gmax);
     776         148 :   if(gmax.size()!=getNumberOfArguments() && gmax.size()!=0) error("not enough values for GRID_MAX");
     777         148 :   std::vector<unsigned> gbin(getNumberOfArguments());
     778             :   std::vector<double>   gspacing;
     779         296 :   parseVector("GRID_BIN",gbin);
     780         148 :   if(gbin.size()!=getNumberOfArguments() && gbin.size()!=0) error("not enough values for GRID_BIN");
     781         296 :   parseVector("GRID_SPACING",gspacing);
     782         148 :   if(gspacing.size()!=getNumberOfArguments() && gspacing.size()!=0) error("not enough values for GRID_SPACING");
     783         148 :   if(gmin.size()!=gmax.size()) error("GRID_MAX and GRID_MIN should be either present or absent");
     784         148 :   if(gspacing.size()!=0 && gmin.size()==0) error("If GRID_SPACING is present also GRID_MIN and GRID_MAX should be present");
     785         148 :   if(gbin.size()!=0     && gmin.size()==0) error("If GRID_BIN is present also GRID_MIN and GRID_MAX should be present");
     786         148 :   if(gmin.size()!=0) {
     787          60 :     if(gbin.size()==0 && gspacing.size()==0) {
     788           6 :       if(adaptive_==FlexibleBin::none) {
     789           6 :         log<<"  Binsize not specified, 1/5 of sigma will be be used\n";
     790           6 :         plumed_assert(sigma0_.size()==getNumberOfArguments());
     791           6 :         gspacing.resize(getNumberOfArguments());
     792          13 :         for(unsigned i=0; i<gspacing.size(); i++) gspacing[i]=0.2*sigma0_[i];
     793             :       } else {
     794             :         // with adaptive hills and grid a sigma min must be specified
     795           0 :         for(unsigned i=0; i<sigma0min_.size(); i++) if(sigma0min_[i]<=0) error("When using ADAPTIVE Gaussians on a grid SIGMA_MIN must be specified");
     796           0 :         log<<"  Binsize not specified, 1/5 of sigma_min will be be used\n";
     797           0 :         gspacing.resize(getNumberOfArguments());
     798           0 :         for(unsigned i=0; i<gspacing.size(); i++) gspacing[i]=0.2*sigma0min_[i];
     799             :       }
     800          54 :     } else if(gspacing.size()!=0 && gbin.size()==0) {
     801           1 :       log<<"  The number of bins will be estimated from GRID_SPACING\n";
     802          53 :     } else if(gspacing.size()!=0 && gbin.size()!=0) {
     803           1 :       log<<"  You specified both GRID_BIN and GRID_SPACING\n";
     804           1 :       log<<"  The more conservative (highest) number of bins will be used for each variable\n";
     805             :     }
     806          60 :     if(gbin.size()==0) gbin.assign(getNumberOfArguments(),1);
     807          70 :     if(gspacing.size()!=0) for(unsigned i=0; i<getNumberOfArguments(); i++) {
     808             :         double a,b;
     809          11 :         Tools::convert(gmin[i],a);
     810          10 :         Tools::convert(gmax[i],b);
     811          10 :         unsigned n=((b-a)/gspacing[i])+1;
     812          10 :         if(gbin[i]<n) gbin[i]=n;
     813             :       }
     814             :   }
     815         147 :   if(gbin.size()>0) grid_=true;
     816             : 
     817         147 :   bool sparsegrid=false;
     818         147 :   parseFlag("GRID_SPARSE",sparsegrid);
     819         147 :   bool nospline=false;
     820         147 :   parseFlag("GRID_NOSPLINE",nospline);
     821         147 :   bool spline=!nospline;
     822         295 :   parse("GRID_WSTRIDE",wgridstride_);
     823             :   std::string gridfilename_;
     824         147 :   parse("GRID_WFILE",gridfilename_);
     825         147 :   parseFlag("STORE_GRIDS",storeOldGrids_);
     826         147 :   if(grid_ && gridfilename_.length()>0) {
     827          18 :     if(wgridstride_==0 ) error("frequency with which to output grid not specified use GRID_WSTRIDE");
     828             :   }
     829         147 :   if(grid_ && wgridstride_>0) {
     830          18 :     if(gridfilename_.length()==0) error("grid filename not specified use GRID_WFILE");
     831             :   }
     832             : 
     833             :   std::string gridreadfilename_;
     834         147 :   parse("GRID_RFILE",gridreadfilename_);
     835             : 
     836         147 :   if(!grid_&&gridfilename_.length()> 0) error("To write a grid you need first to define it!");
     837         147 :   if(!grid_&&gridreadfilename_.length()>0) error("To read a grid you need first to define it!");
     838             : 
     839             :   /*setup neighbor list stuff*/
     840         294 :   parseFlag("NLIST", nlist_);
     841         147 :   nlist_center_.resize(getNumberOfArguments());
     842         147 :   nlist_dev2_.resize(getNumberOfArguments());
     843         147 :   if(nlist_&&grid_) error("NLIST and GRID cannot be combined!");
     844             :   std::vector<double> nlist_param;
     845         294 :   parseVector("NLIST_PARAMETERS",nlist_param);
     846         147 :   if(nlist_param.size()==0)
     847             :   {
     848         147 :     nlist_param_[0]=6.0;//*DP2CUTOFF -> max distance of neighbors
     849         147 :     nlist_param_[1]=0.5;//*nlist_dev2_[i] -> condition for rebuilding
     850             :   }
     851             :   else
     852             :   {
     853           0 :     plumed_massert(nlist_param.size()==2,"two cutoff parameters are needed for the neighbor list");
     854           0 :     plumed_massert(nlist_param[0]>1.0,"the first of NLIST_PARAMETERS must be greater than 1. The smaller the first, the smaller should be the second as well");
     855           0 :     const double min_PARAM_1=(1.-1./std::sqrt(nlist_param[0]/2))+0.16;
     856           0 :     plumed_massert(nlist_param[1]>0,"the second of NLIST_PARAMETERS must be greater than 0");
     857           0 :     plumed_massert(nlist_param[1]<=min_PARAM_1,"the second of NLIST_PARAMETERS must be smaller to avoid systematic errors. Largest suggested value is: 1.16-1/sqrt(PARAM_0/2) = "+std::to_string(min_PARAM_1));
     858           0 :     nlist_param_[0]=nlist_param[0];
     859           0 :     nlist_param_[1]=nlist_param[1];
     860             :   }
     861             : 
     862             :   // Reweighting factor rct
     863         147 :   parseFlag("CALC_RCT",calc_rct_);
     864         147 :   if (calc_rct_) plumed_massert(grid_,"CALC_RCT is supported only if bias is on a grid");
     865         147 :   parse("RCT_USTRIDE",rct_ustride_);
     866             : 
     867         147 :   if(dampfactor_>0.0) {
     868           2 :     if(!grid_) error("With DAMPFACTOR you should use grids");
     869             :   }
     870             : 
     871             :   // Multiple walkers
     872         147 :   parse("WALKERS_N",mw_n_);
     873         147 :   parse("WALKERS_ID",mw_id_);
     874         147 :   if(mw_n_<=mw_id_) error("walker ID should be a numerical value less than the total number of walkers");
     875         147 :   parse("WALKERS_DIR",mw_dir_);
     876         147 :   parse("WALKERS_RSTRIDE",mw_rstride_);
     877             : 
     878             :   // MPI version
     879         147 :   parseFlag("WALKERS_MPI",walkers_mpi_);
     880             : 
     881             :   // Flying Gaussian
     882         147 :   parseFlag("FLYING_GAUSSIAN", flying_);
     883             : 
     884             :   // Inteval keyword
     885         147 :   std::vector<double> tmpI(2);
     886         294 :   parseVector("INTERVAL",tmpI);
     887         147 :   if(tmpI.size()!=2&&tmpI.size()!=0) error("both a lower and an upper limits must be provided with INTERVAL");
     888         147 :   else if(tmpI.size()==2) {
     889           2 :     lowI_=tmpI.at(0);
     890           2 :     uppI_=tmpI.at(1);
     891           2 :     if(getNumberOfArguments()!=1) error("INTERVAL limits correction works only for monodimensional metadynamics!");
     892           2 :     if(uppI_<lowI_) error("The Upper limit must be greater than the Lower limit!");
     893           2 :     if(getPntrToArgument(0)->isPeriodic()) error("INTERVAL cannot be used with periodic variables!");
     894           2 :     doInt_=true;
     895             :   }
     896             : 
     897         294 :   parseFlag("ACCELERATION",acceleration_);
     898             :   // Check for a restart acceleration if acceleration is active.
     899             :   std::string acc_rfilename;
     900         147 :   if(acceleration_) {
     901           8 :     parse("ACCELERATION_RFILE", acc_rfilename);
     902             :   }
     903             : 
     904         147 :   freq_adaptive_=false;
     905         147 :   parseFlag("FREQUENCY_ADAPTIVE",freq_adaptive_);
     906             :   //
     907         147 :   fa_update_frequency_=0;
     908         147 :   parse("FA_UPDATE_FREQUENCY",fa_update_frequency_);
     909         147 :   if(fa_update_frequency_!=0 && !freq_adaptive_) {
     910           0 :     plumed_merror("It doesn't make sense to use the FA_MAX_PACE keyword if frequency adaptive METAD hasn't been activated by using the FREQUENCY_ADAPTIVE flag");
     911             :   }
     912         147 :   if(fa_update_frequency_==0 && freq_adaptive_) {
     913           0 :     fa_update_frequency_=stride_;
     914             :   }
     915             :   //
     916         147 :   fa_max_stride_=0;
     917         147 :   parse("FA_MAX_PACE",fa_max_stride_);
     918         147 :   if(fa_max_stride_!=0 && !freq_adaptive_) {
     919           0 :     plumed_merror("It doesn't make sense to use the FA_MAX_PACE keyword if frequency adaptive METAD hasn't been activated by using the FREQUENCY_ADAPTIVE flag");
     920             :   }
     921             :   //
     922         147 :   fa_min_acceleration_=1.0;
     923         147 :   parse("FA_MIN_ACCELERATION",fa_min_acceleration_);
     924         147 :   if(fa_min_acceleration_!=1.0 && !freq_adaptive_) {
     925           0 :     plumed_merror("It doesn't make sense to use the FA_MIN_ACCELERATION keyword if frequency adaptive METAD hasn't been activated by using the FREQUENCY_ADAPTIVE flag");
     926             :   }
     927             : 
     928         147 :   checkRead();
     929             : 
     930         147 :   log.printf("  Gaussian width ");
     931         147 :   if (adaptive_==FlexibleBin::diffusion)log.printf(" (Note: The units of sigma are in timesteps) ");
     932         147 :   if (adaptive_==FlexibleBin::geometry)log.printf(" (Note: The units of sigma are in dist units) ");
     933         393 :   for(unsigned i=0; i<sigma0_.size(); ++i) log.printf(" %f",sigma0_[i]);
     934         147 :   log.printf("  Gaussian height %f\n",height0_);
     935         147 :   log.printf("  Gaussian deposition pace %d\n",stride_);
     936         147 :   log.printf("  Gaussian file %s\n",hillsfname.c_str());
     937         147 :   if(welltemp_) {
     938          37 :     log.printf("  Well-Tempered Bias Factor %f\n",biasf_);
     939          37 :     log.printf("  Hills relaxation time (tau) %f\n",tau);
     940          37 :     log.printf("  KbT %f\n",kbt_);
     941             :   }
     942             : 
     943             :   // Transition tempered metadynamics options
     944         147 :   if (tt_specs_.is_active) {
     945           3 :     logTemperingSpecs(tt_specs_);
     946             :     // Check that the appropriate transition bias quantity is calculated.
     947             :     // (Should never trip, given that the flag is automatically set.)
     948           3 :     if (!calc_transition_bias_) {
     949           0 :       error(" transition tempering requires calculation of a transition bias");
     950             :     }
     951             :   }
     952             : 
     953             :   // Overall tempering sanity check (this gets tricky when multiple are active).
     954             :   // When multiple temperings are active, it's fine to have one tempering attempt
     955             :   // to increase hill size with increasing bias, so long as the others can shrink
     956             :   // the hills faster than it increases their size in the long-time limit.
     957             :   // This set of checks ensures that the hill sizes eventually decay to zero as c(t)
     958             :   // diverges to infinity.
     959             :   // The alpha parameter allows hills to decay as 1/t^alpha instead of 1/t,
     960             :   // a slower decay, so as t -> infinity, only the temperings with the largest
     961             :   // alphas govern the final asymptotic decay. (Alpha helps prevent false convergence.)
     962         147 :   if (welltemp_ || dampfactor_ > 0.0 || tt_specs_.is_active) {
     963             :     // Determine the number of active temperings.
     964             :     int n_active = 0;
     965          42 :     if (welltemp_) n_active++;
     966          42 :     if (dampfactor_ > 0.0) n_active++;
     967          42 :     if (tt_specs_.is_active) n_active++;
     968             :     // Find the greatest alpha.
     969          42 :     double greatest_alpha = 0.0;
     970          42 :     if (welltemp_) greatest_alpha = std::max(greatest_alpha, 1.0);
     971          44 :     if (dampfactor_ > 0.0) greatest_alpha = std::max(greatest_alpha, 1.0);
     972          45 :     if (tt_specs_.is_active) greatest_alpha = std::max(greatest_alpha, tt_specs_.alpha);
     973             :     // Find the least alpha.
     974          42 :     double least_alpha = 1.0;
     975             :     if (welltemp_) least_alpha = std::min(least_alpha, 1.0);
     976          42 :     if (dampfactor_ > 0.0) least_alpha = std::min(least_alpha, 1.0);
     977          43 :     if (tt_specs_.is_active) least_alpha = std::min(least_alpha, tt_specs_.alpha);
     978             :     // Find the inverse harmonic average of the delta T parameters for all
     979             :     // of the temperings with the greatest alpha values.
     980             :     double total_governing_deltaT_inv = 0.0;
     981          42 :     if (welltemp_ && 1.0 == greatest_alpha && biasf_ != 1.0) total_governing_deltaT_inv += 1.0 / (biasf_ - 1.0);
     982          42 :     if (dampfactor_ > 0.0 && 1.0 == greatest_alpha) total_governing_deltaT_inv += 1.0 / (dampfactor_);
     983          42 :     if (tt_specs_.is_active && tt_specs_.alpha == greatest_alpha) total_governing_deltaT_inv += 1.0 / (tt_specs_.biasf - 1.0);
     984             :     // Give a newbie-friendly error message for people using one tempering if
     985             :     // only one is active.
     986          42 :     if (n_active == 1 && total_governing_deltaT_inv < 0.0) {
     987           0 :       error("for stable tempering, the bias factor must be greater than one");
     988             :       // Give a slightly more complex error message to users stacking multiple
     989             :       // tempering options at a time, but all with uniform alpha values.
     990          42 :     } else if (total_governing_deltaT_inv < 0.0 && greatest_alpha == least_alpha) {
     991           0 :       error("for stable tempering, the sum of the inverse Delta T parameters must be greater than zero!");
     992             :       // Give the most technical error message to users stacking multiple tempering
     993             :       // options with different alpha parameters.
     994          42 :     } else if (total_governing_deltaT_inv < 0.0 && greatest_alpha != least_alpha) {
     995           0 :       error("for stable tempering, the sum of the inverse Delta T parameters for the greatest asymptotic hill decay exponents must be greater than zero!");
     996             :     }
     997             :   }
     998             : 
     999         147 :   if(doInt_) log.printf("  Upper and Lower limits boundaries for the bias are activated at %f - %f\n", lowI_, uppI_);
    1000             : 
    1001         147 :   if(grid_) {
    1002          59 :     log.printf("  Grid min");
    1003         158 :     for(unsigned i=0; i<gmin.size(); ++i) log.printf(" %s",gmin[i].c_str() );
    1004          59 :     log.printf("\n");
    1005          59 :     log.printf("  Grid max");
    1006         158 :     for(unsigned i=0; i<gmax.size(); ++i) log.printf(" %s",gmax[i].c_str() );
    1007          59 :     log.printf("\n");
    1008          59 :     log.printf("  Grid bin");
    1009         158 :     for(unsigned i=0; i<gbin.size(); ++i) log.printf(" %u",gbin[i]);
    1010          59 :     log.printf("\n");
    1011          59 :     if(spline) {log.printf("  Grid uses spline interpolation\n");}
    1012          59 :     if(sparsegrid) {log.printf("  Grid uses sparse grid\n");}
    1013          59 :     if(wgridstride_>0) {log.printf("  Grid is written on file %s with stride %d\n",gridfilename_.c_str(),wgridstride_);}
    1014             :   }
    1015             : 
    1016         147 :   if(mw_n_>1) {
    1017           6 :     if(walkers_mpi_) error("MPI version of multiple walkers is not compatible with filesystem version of multiple walkers");
    1018           6 :     log.printf("  %d multiple walkers active\n",mw_n_);
    1019           6 :     log.printf("  walker id %d\n",mw_id_);
    1020           6 :     log.printf("  reading stride %d\n",mw_rstride_);
    1021           6 :     if(mw_dir_!="")log.printf("  directory with hills files %s\n",mw_dir_.c_str());
    1022             :   } else {
    1023         141 :     if(walkers_mpi_) {
    1024          38 :       log.printf("  Multiple walkers active using MPI communnication\n");
    1025          38 :       if(mw_dir_!="")log.printf("  directory with hills files %s\n",mw_dir_.c_str());
    1026          38 :       if(comm.Get_rank()==0) {
    1027             :         // Only root of group can communicate with other walkers
    1028          23 :         mpi_nw_=multi_sim_comm.Get_size();
    1029             :       }
    1030             :       // Communicate to the other members of the same group
    1031             :       // info abount number of walkers and walker index
    1032          38 :       comm.Bcast(mpi_nw_,0);
    1033             :     }
    1034             :   }
    1035             : 
    1036         147 :   if(flying_) {
    1037           6 :     if(!walkers_mpi_) error("Flying Gaussian method must be used with MPI version of multiple walkers");
    1038           6 :     log.printf("  Flying Gaussian method with %d walkers active\n",mpi_nw_);
    1039             :   }
    1040             : 
    1041         147 :   if(nlist_) {
    1042           1 :     addComponent("nlker");
    1043           1 :     componentIsNotPeriodic("nlker");
    1044           1 :     addComponent("nlsteps");
    1045           2 :     componentIsNotPeriodic("nlsteps");
    1046             :   }
    1047             : 
    1048         147 :   if(calc_rct_) {
    1049          12 :     addComponent("rbias"); componentIsNotPeriodic("rbias");
    1050          12 :     addComponent("rct"); componentIsNotPeriodic("rct");
    1051           6 :     log.printf("  The c(t) reweighting factor will be calculated every %u hills\n",rct_ustride_);
    1052          12 :     getPntrToComponent("rct")->set(reweight_factor_);
    1053             :   }
    1054             : 
    1055         149 :   if(calc_work_) { addComponent("work"); componentIsNotPeriodic("work"); }
    1056             : 
    1057         147 :   if(acceleration_) {
    1058           4 :     if (kbt_ == 0.0) {
    1059           0 :       error("The calculation of the acceleration works only if simulation temperature has been defined");
    1060             :     }
    1061           4 :     log.printf("  calculation on the fly of the acceleration factor\n");
    1062          12 :     addComponent("acc"); componentIsNotPeriodic("acc");
    1063             :     // Set the initial value of the the acceleration.
    1064             :     // If this is not a restart, set to 1.0.
    1065           4 :     if (acc_rfilename.length() == 0) {
    1066           4 :       getPntrToComponent("acc")->set(1.0);
    1067           2 :       if(getRestart()) {
    1068           1 :         log.printf("  WARNING: calculating the acceleration factor in a restarted run without reading in the previous value will most likely lead to incorrect results.\n");
    1069           1 :         log.printf("           You should use the ACCELERATION_RFILE keyword.\n");
    1070             :       }
    1071             :       // Otherwise, read and set the restart value.
    1072             :     } else {
    1073             :       // Restart of acceleration does not make sense if the restart timestep is zero.
    1074             :       //if (getStep() == 0) {
    1075             :       //  error("Restarting calculation of acceleration factors works only if simulation timestep is restarted correctly");
    1076             :       //}
    1077             :       // Open the ACCELERATION_RFILE.
    1078           2 :       IFile acc_rfile;
    1079           2 :       acc_rfile.link(*this);
    1080           2 :       if(acc_rfile.FileExist(acc_rfilename)) {
    1081           2 :         acc_rfile.open(acc_rfilename);
    1082             :       } else {
    1083           0 :         error("The ACCELERATION_RFILE file you want to read: " + acc_rfilename + ", cannot be found!");
    1084             :       }
    1085             :       // Read the file to find the restart acceleration.
    1086           2 :       double acc_rmean=0.0;
    1087           2 :       double acc_rtime=0.0;
    1088             :       bool found=false;
    1089           2 :       std::string acclabel = getLabel() + ".acc";
    1090           2 :       acc_rfile.allowIgnoredFields();
    1091         248 :       while(acc_rfile.scanField("time", acc_rtime)) {
    1092         122 :         acc_rfile.scanField(acclabel, acc_rmean);
    1093         122 :         acc_rfile.scanField();
    1094             :         found=true;
    1095             :       }
    1096           2 :       if(!found) error("The ACCELERATION_RFILE file you want to read: " + acc_rfilename + ", does not contain a time field!");
    1097           2 :       acc_restart_mean_ = acc_rmean;
    1098             :       // Set component based on the read values.
    1099           2 :       getPntrToComponent("acc")->set(acc_rmean);
    1100           2 :       log.printf("  initial acceleration factor read from file %s: value of %f at time %f\n",acc_rfilename.c_str(),acc_rmean,acc_rtime);
    1101           2 :     }
    1102             :   }
    1103             : 
    1104         147 :   if (calc_max_bias_) {
    1105           0 :     if (!grid_) error("Calculating the maximum bias on the fly works only with a grid");
    1106           0 :     log.printf("  calculation on the fly of the maximum bias max(V(s,t)) \n");
    1107           0 :     addComponent("maxbias");
    1108           0 :     componentIsNotPeriodic("maxbias");
    1109             :   }
    1110             : 
    1111         147 :   if (calc_transition_bias_) {
    1112          13 :     if (!grid_) error("Calculating the transition bias on the fly works only with a grid");
    1113          13 :     log.printf("  calculation on the fly of the transition bias V*(t)\n");
    1114          13 :     addComponent("transbias");
    1115          13 :     componentIsNotPeriodic("transbias");
    1116          13 :     log<<"  Number of transition wells "<<transitionwells_.size()<<"\n";
    1117          13 :     if (transitionwells_.size() == 0) error("Calculating the transition bias on the fly requires definition of at least one transition well");
    1118             :     // Check that a grid is in use.
    1119          13 :     if (!grid_) error(" transition barrier finding requires a grid for the bias");
    1120             :     // Log the wells and check that they are in the grid.
    1121          39 :     for (unsigned i = 0; i < transitionwells_.size(); i++) {
    1122             :       // Log the coordinate.
    1123          26 :       log.printf("  Transition well %d at coordinate ", i);
    1124          64 :       for (unsigned j = 0; j < getNumberOfArguments(); j++) log.printf("%f ", transitionwells_[i][j]);
    1125          26 :       log.printf("\n");
    1126             :       // Check that the coordinate is in the grid.
    1127          64 :       for (unsigned j = 0; j < getNumberOfArguments(); j++) {
    1128             :         double max, min;
    1129          38 :         Tools::convert(gmin[j], min);
    1130          38 :         Tools::convert(gmax[j], max);
    1131          38 :         if (transitionwells_[i][j] < min || transitionwells_[i][j] > max) error(" transition well is not in grid");
    1132             :       }
    1133             :     }
    1134             :   }
    1135             : 
    1136         147 :   if(freq_adaptive_) {
    1137           2 :     if(!acceleration_) {
    1138           0 :       plumed_merror("Frequency adaptive metadynamics only works if the calculation of the acceleration factor is enabled with the ACCELERATION keyword\n");
    1139             :     }
    1140           2 :     if(walkers_mpi_) {
    1141           0 :       plumed_merror("Combining frequency adaptive metadynamics with MPI multiple walkers is not allowed");
    1142             :     }
    1143             : 
    1144           2 :     log.printf("  Frequency adaptive metadynamics enabled\n");
    1145           2 :     if(getRestart() && acc_rfilename.length() == 0) {
    1146           0 :       log.printf("  WARNING: using the frequency adaptive scheme in a restarted run without reading in the previous value of the acceleration factor will most likely lead to incorrect results.\n");
    1147           0 :       log.printf("           You should use the ACCELERATION_RFILE keyword.\n");
    1148             :     }
    1149           2 :     log.printf("  The frequency for hill addition will change dynamically based on the metadynamics acceleration factor\n");
    1150           2 :     log.printf("  The hill addition frequency will be updated every %d steps\n",fa_update_frequency_);
    1151           2 :     if(fa_min_acceleration_>1.0) {
    1152           2 :       log.printf("  The hill addition frequency will only be updated once the metadynamics acceleration factor becomes larger than %.1f \n",fa_min_acceleration_);
    1153             :     }
    1154           2 :     if(fa_max_stride_!=0) {
    1155           2 :       log.printf("  The hill addition frequency will not become larger than %d steps\n",fa_max_stride_);
    1156             :     }
    1157           4 :     addComponent("pace"); componentIsNotPeriodic("pace");
    1158           2 :     updateFrequencyAdaptiveStride();
    1159             :   }
    1160             : 
    1161             :   // initializing and checking grid
    1162             :   bool restartedFromGrid=false;  // restart from grid file
    1163         147 :   if(grid_) {
    1164          59 :     if(!(gridreadfilename_.length()>0)) {
    1165             :       // check for mesh and sigma size
    1166         113 :       for(unsigned i=0; i<getNumberOfArguments(); i++) {
    1167             :         double a,b;
    1168          72 :         Tools::convert(gmin[i],a);
    1169          72 :         Tools::convert(gmax[i],b);
    1170          72 :         double mesh=(b-a)/((double)gbin[i]);
    1171          72 :         if(adaptive_==FlexibleBin::none) {
    1172          72 :           if(mesh>0.5*sigma0_[i]) log<<"  WARNING: Using a METAD with a Grid Spacing larger than half of the Gaussians width (SIGMA) can produce artifacts\n";
    1173             :         } else {
    1174           0 :           if(sigma0min_[i]<0.) error("When using ADAPTIVE Gaussians on a grid SIGMA_MIN must be specified");
    1175           0 :           if(mesh>0.5*sigma0min_[i]) log<<"  WARNING: to use a METAD with a GRID and ADAPTIVE you need to set a Grid Spacing lower than half of the Gaussians (SIGMA_MIN) \n";
    1176             :         }
    1177             :       }
    1178          41 :       std::string funcl=getLabel() + ".bias";
    1179          41 :       if(!sparsegrid) {BiasGrid_=Tools::make_unique<Grid>(funcl,getArguments(),gmin,gmax,gbin,spline,true);}
    1180           6 :       else {BiasGrid_=Tools::make_unique<SparseGrid>(funcl,getArguments(),gmin,gmax,gbin,spline,true);}
    1181          41 :       std::vector<std::string> actualmin=BiasGrid_->getMin();
    1182          41 :       std::vector<std::string> actualmax=BiasGrid_->getMax();
    1183         113 :       for(unsigned i=0; i<getNumberOfArguments(); i++) {
    1184             :         std::string is;
    1185          72 :         Tools::convert(i,is);
    1186          72 :         if(gmin[i]!=actualmin[i]) error("GRID_MIN["+is+"] must be adjusted to "+actualmin[i]+" to fit periodicity");
    1187          72 :         if(gmax[i]!=actualmax[i]) error("GRID_MAX["+is+"] must be adjusted to "+actualmax[i]+" to fit periodicity");
    1188             :       }
    1189          41 :     } else {
    1190             :       // read the grid in input, find the keys
    1191             : #ifdef __PLUMED_HAS_GETCWD
    1192          18 :       if(walkers_mpi_&&gridreadfilename_.at(0)!='/') {
    1193             :         //if possible the root replica will share its current folder so that all walkers will read the same file
    1194           0 :         char cwd[4096]= {0};
    1195             :         const char* ret=getcwd(cwd,4096);
    1196           0 :         plumed_assert(ret)<<"Name of current directory too long, increase buffer size";
    1197           0 :         gridreadfilename_ = "/" + gridreadfilename_;
    1198           0 :         gridreadfilename_ = ret + gridreadfilename_;
    1199           0 :         if(comm.Get_rank()==0) multi_sim_comm.Bcast(gridreadfilename_,0);
    1200           0 :         comm.Bcast(gridreadfilename_,0);
    1201             :       }
    1202             : #endif
    1203          18 :       IFile gridfile;
    1204          18 :       gridfile.link(*this);
    1205          18 :       if(gridfile.FileExist(gridreadfilename_)) {
    1206          18 :         gridfile.open(gridreadfilename_);
    1207             :       } else {
    1208           0 :         error("The GRID file you want to read: " + gridreadfilename_ + ", cannot be found!");
    1209             :       }
    1210          18 :       std::string funcl=getLabel() + ".bias";
    1211          36 :       BiasGrid_=GridBase::create(funcl, getArguments(), gridfile, gmin, gmax, gbin, sparsegrid, spline, true);
    1212          18 :       if(BiasGrid_->getDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments");
    1213          45 :       for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1214          54 :         if( getPntrToArgument(i)->isPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias");
    1215             :         double a, b;
    1216          27 :         Tools::convert(gmin[i],a);
    1217          27 :         Tools::convert(gmax[i],b);
    1218          27 :         double mesh=(b-a)/((double)gbin[i]);
    1219          27 :         if(mesh>0.5*sigma0_[i]) log<<"  WARNING: Using a METAD with a Grid Spacing larger than half of the Gaussians width can produce artifacts\n";
    1220             :       }
    1221          18 :       log.printf("  Restarting from %s\n",gridreadfilename_.c_str());
    1222          18 :       if(getRestart()) restartedFromGrid=true;
    1223          18 :     }
    1224             :   }
    1225             : 
    1226             :   // if we are restarting from GRID and using WALKERS_MPI we can check that all walkers have actually read the grid
    1227         147 :   if(getRestart()&&walkers_mpi_) {
    1228           9 :     std::vector<int> restarted(mpi_nw_,0);
    1229           9 :     if(comm.Get_rank()==0) multi_sim_comm.Allgather(int(restartedFromGrid), restarted);
    1230           9 :     comm.Bcast(restarted,0);
    1231             :     int result = std::accumulate(restarted.begin(),restarted.end(),0);
    1232           9 :     if(result!=0&&result!=mpi_nw_) error("in this WALKERS_MPI run some replica have restarted from GRID while other do not!");
    1233             :   }
    1234             : 
    1235             : #ifdef __PLUMED_HAS_GETCWD
    1236         185 :   if(walkers_mpi_&&mw_dir_==""&&hillsfname.at(0)!='/') {
    1237             :     //if possible the root replica will share its current folder so that all walkers will read the same file
    1238          38 :     char cwd[4096]= {0};
    1239             :     const char* ret=getcwd(cwd,4096);
    1240          38 :     plumed_assert(ret)<<"Name of current directory too long, increase buffer size";
    1241             :     mw_dir_ = ret;
    1242          38 :     mw_dir_ = mw_dir_ + "/";
    1243          38 :     if(comm.Get_rank()==0) multi_sim_comm.Bcast(mw_dir_,0);
    1244          38 :     comm.Bcast(mw_dir_,0);
    1245             :   }
    1246             : #endif
    1247             : 
    1248             :   // creating std::vector of ifile* for hills reading
    1249             :   // open all files at the beginning and read Gaussians if restarting
    1250             :   bool restartedFromHills=false;  // restart from hills files
    1251         306 :   for(int i=0; i<mw_n_; ++i) {
    1252             :     std::string fname;
    1253         159 :     if(mw_dir_!="") {
    1254          47 :       if(mw_n_>1) {
    1255           9 :         std::stringstream out; out << i;
    1256          18 :         fname = mw_dir_+"/"+hillsfname+"."+out.str();
    1257          47 :       } else if(walkers_mpi_) {
    1258          76 :         fname = mw_dir_+"/"+hillsfname;
    1259             :       } else {
    1260             :         fname = hillsfname;
    1261             :       }
    1262             :     } else {
    1263         112 :       if(mw_n_>1) {
    1264           9 :         std::stringstream out; out << i;
    1265          18 :         fname = hillsfname+"."+out.str();
    1266           9 :       } else {
    1267             :         fname = hillsfname;
    1268             :       }
    1269             :     }
    1270         159 :     ifiles_.emplace_back(Tools::make_unique<IFile>());
    1271             :     // this is just a shortcut pointer to the last element:
    1272             :     IFile *ifile = ifiles_.back().get();
    1273         159 :     ifilesnames_.push_back(fname);
    1274         159 :     ifile->link(*this);
    1275         159 :     if(ifile->FileExist(fname)) {
    1276          35 :       ifile->open(fname);
    1277          35 :       if(getRestart()&&!restartedFromGrid) {
    1278          19 :         log.printf("  Restarting from %s:",ifilesnames_[i].c_str());
    1279          19 :         readGaussians(ifiles_[i].get());
    1280             :         restartedFromHills=true;
    1281             :       }
    1282          35 :       ifiles_[i]->reset(false);
    1283             :       // close only the walker own hills file for later writing
    1284          35 :       if(i==mw_id_) ifiles_[i]->close();
    1285             :     } else {
    1286             :       // in case a file does not exist and we are restarting, complain that the file was not found
    1287         124 :       if(getRestart()&&!restartedFromGrid) error("restart file "+fname+" not found");
    1288             :     }
    1289             :   }
    1290             : 
    1291             :   // if we are restarting from FILE and using WALKERS_MPI we can check that all walkers have actually read the FILE
    1292         147 :   if(getRestart()&&walkers_mpi_) {
    1293           9 :     std::vector<int> restarted(mpi_nw_,0);
    1294           9 :     if(comm.Get_rank()==0) multi_sim_comm.Allgather(int(restartedFromHills), restarted);
    1295           9 :     comm.Bcast(restarted,0);
    1296             :     int result = std::accumulate(restarted.begin(),restarted.end(),0);
    1297           9 :     if(result!=0&&result!=mpi_nw_) error("in this WALKERS_MPI run some replica have restarted from FILE while other do not!");
    1298             :   }
    1299             : 
    1300         147 :   comm.Barrier();
    1301             :   // this barrier is needed when using walkers_mpi
    1302             :   // to be sure that all files have been read before
    1303             :   // backing them up
    1304             :   // it should not be used when walkers_mpi is false otherwise
    1305             :   // it would introduce troubles when using replicas without METAD
    1306             :   // (e.g. in bias exchange with a neutral replica)
    1307             :   // see issue #168 on github
    1308         147 :   if(comm.Get_rank()==0 && walkers_mpi_) multi_sim_comm.Barrier();
    1309             : 
    1310         147 :   if(targetfilename_.length()>0) {
    1311           2 :     IFile gridfile; gridfile.open(targetfilename_);
    1312           2 :     std::string funcl=getLabel() + ".target";
    1313           4 :     TargetGrid_=GridBase::create(funcl,getArguments(),gridfile,false,false,true);
    1314           2 :     if(TargetGrid_->getDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments");
    1315           4 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
    1316           4 :       if( getPntrToArgument(i)->isPeriodic()!=TargetGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias");
    1317             :     }
    1318           2 :   }
    1319             : 
    1320         147 :   if(getRestart()) {
    1321             :     // if this is a restart the neighbor list should be immediately updated
    1322          37 :     if(nlist_) nlist_update_=true;
    1323             :     // Calculate the Tiwary-Parrinello reweighting factor if we are restarting from previous hills
    1324          37 :     if(calc_rct_) computeReweightingFactor();
    1325             :     // Calculate all special bias quantities desired if restarting with nonzero bias.
    1326          37 :     if(calc_max_bias_) {
    1327           0 :       max_bias_ = BiasGrid_->getMaxValue();
    1328           0 :       getPntrToComponent("maxbias")->set(max_bias_);
    1329             :     }
    1330          37 :     if(calc_transition_bias_) {
    1331          13 :       transition_bias_ = getTransitionBarrierBias();
    1332          26 :       getPntrToComponent("transbias")->set(transition_bias_);
    1333             :     }
    1334             :   }
    1335             : 
    1336             :   // open grid file for writing
    1337         147 :   if(wgridstride_>0) {
    1338          18 :     gridfile_.link(*this);
    1339          18 :     if(walkers_mpi_) {
    1340           0 :       int r=0;
    1341           0 :       if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank();
    1342           0 :       comm.Bcast(r,0);
    1343           0 :       if(r>0) gridfilename_="/dev/null";
    1344           0 :       gridfile_.enforceSuffix("");
    1345             :     }
    1346          18 :     if(mw_n_>1) gridfile_.enforceSuffix("");
    1347          18 :     gridfile_.open(gridfilename_);
    1348             :   }
    1349             : 
    1350             :   // open hills file for writing
    1351         147 :   hillsOfile_.link(*this);
    1352         147 :   if(walkers_mpi_) {
    1353          38 :     int r=0;
    1354          38 :     if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank();
    1355          38 :     comm.Bcast(r,0);
    1356          38 :     if(r>0) ifilesnames_[mw_id_]="/dev/null";
    1357          76 :     hillsOfile_.enforceSuffix("");
    1358             :   }
    1359         153 :   if(mw_n_>1) hillsOfile_.enforceSuffix("");
    1360         147 :   hillsOfile_.open(ifilesnames_[mw_id_]);
    1361         147 :   if(fmt_.length()>0) hillsOfile_.fmtField(fmt_);
    1362         147 :   hillsOfile_.addConstantField("multivariate");
    1363         147 :   hillsOfile_.addConstantField("kerneltype");
    1364         147 :   if(doInt_) {
    1365           4 :     hillsOfile_.addConstantField("lower_int").printField("lower_int",lowI_);
    1366           4 :     hillsOfile_.addConstantField("upper_int").printField("upper_int",uppI_);
    1367             :   }
    1368             :   hillsOfile_.setHeavyFlush();
    1369             :   // output periodicities of variables
    1370         412 :   for(unsigned i=0; i<getNumberOfArguments(); ++i) hillsOfile_.setupPrintValue( getPntrToArgument(i) );
    1371             : 
    1372             :   bool concurrent=false;
    1373         147 :   const ActionSet&actionSet(plumed.getActionSet());
    1374         538 :   for(const auto & p : actionSet) if(dynamic_cast<MetaD*>(p.get())) { concurrent=true; break; }
    1375         147 :   if(concurrent) log<<"  You are using concurrent metadynamics\n";
    1376         147 :   if(rect_biasf_.size()>0) {
    1377          18 :     if(walkers_mpi_) {
    1378          12 :       log<<"  You are using RECT in its 'altruistic' implementation\n";
    1379             :     }{
    1380          18 :       log<<"  You are using RECT\n";
    1381             :     }
    1382             :   }
    1383             : 
    1384         294 :   log<<"  Bibliography "<<plumed.cite("Laio and Parrinello, PNAS 99, 12562 (2002)");
    1385         221 :   if(welltemp_) log<<plumed.cite("Barducci, Bussi, and Parrinello, Phys. Rev. Lett. 100, 020603 (2008)");
    1386         147 :   if(tt_specs_.is_active) {
    1387           6 :     log << plumed.cite("Dama, Rotskoff, Parrinello, and Voth, J. Chem. Theory Comput. 10, 3626 (2014)");
    1388           9 :     log << plumed.cite("Dama, Parrinello, and Voth, Phys. Rev. Lett. 112, 240602 (2014)");
    1389             :   }
    1390         235 :   if(mw_n_>1||walkers_mpi_) log<<plumed.cite("Raiteri, Laio, Gervasio, Micheletti, and Parrinello, J. Phys. Chem. B 110, 3533 (2006)");
    1391         189 :   if(adaptive_!=FlexibleBin::none) log<<plumed.cite("Branduardi, Bussi, and Parrinello, J. Chem. Theory Comput. 8, 2247 (2012)");
    1392         151 :   if(doInt_) log<<plumed.cite("Baftizadeh, Cossio, Pietrucci, and Laio, Curr. Phys. Chem. 2, 79 (2012)");
    1393         155 :   if(acceleration_) log<<plumed.cite("Pratyush and Parrinello, Phys. Rev. Lett. 111, 230602 (2013)");
    1394         159 :   if(calc_rct_) log<<plumed.cite("Pratyush and Parrinello, J. Phys. Chem. B, 119, 736 (2015)");
    1395         305 :   if(concurrent || rect_biasf_.size()>0) log<<plumed.cite("Gil-Ley and Bussi, J. Chem. Theory Comput. 11, 1077 (2015)");
    1396         171 :   if(rect_biasf_.size()>0 && walkers_mpi_) log<<plumed.cite("Hosek, Toulcova, Bortolato, and Spiwok, J. Phys. Chem. B 120, 2209 (2016)");
    1397         147 :   if(targetfilename_.length()>0) {
    1398           4 :     log<<plumed.cite("White, Dama, and Voth, J. Chem. Theory Comput. 11, 2451 (2015)");
    1399           4 :     log<<plumed.cite("Marinelli and Faraldo-Gómez,  Biophys. J. 108, 2779 (2015)");
    1400           6 :     log<<plumed.cite("Gil-Ley, Bottaro, and Bussi, J. Chem. Theory Comput. 12, 2790 (2016)");
    1401             :   }
    1402         151 :   if(freq_adaptive_) log<<plumed.cite("Wang, Valsson, Tiwary, Parrinello, and Lindorff-Larsen, J. Chem. Phys. 149, 072309 (2018)");
    1403         147 :   log<<"\n";
    1404         387 : }
    1405             : 
    1406         149 : void MetaD::readTemperingSpecs(TemperingSpecs &t_specs)
    1407             : {
    1408             :   // Set global tempering parameters.
    1409         149 :   parse(t_specs.name_stem + "BIASFACTOR", t_specs.biasf);
    1410         149 :   if (t_specs.biasf != -1.0) {
    1411           3 :     if (kbt_ == 0.0) {
    1412           0 :       error("Unless the MD engine passes the temperature to plumed, with tempered metad you must specify it using TEMP");
    1413             :     }
    1414           3 :     if (t_specs.biasf == 1.0) {
    1415           0 :       error("A bias factor of 1 corresponds to zero delta T and zero hill size, so it is not allowed.");
    1416             :     }
    1417           3 :     t_specs.is_active = true;
    1418           3 :     parse(t_specs.name_stem + "BIASTHRESHOLD", t_specs.threshold);
    1419           3 :     if (t_specs.threshold < 0.0) {
    1420           0 :       error(t_specs.name + " bias threshold is nonsensical");
    1421             :     }
    1422           3 :     parse(t_specs.name_stem + "ALPHA", t_specs.alpha);
    1423           3 :     if (t_specs.alpha <= 0.0 || t_specs.alpha > 1.0) {
    1424           0 :       error(t_specs.name + " decay shape parameter alpha is nonsensical");
    1425             :     }
    1426             :   }
    1427         149 : }
    1428             : 
    1429           3 : void MetaD::logTemperingSpecs(const TemperingSpecs &t_specs)
    1430             : {
    1431           3 :   log.printf("  %s bias factor %f\n", t_specs.name.c_str(), t_specs.biasf);
    1432           3 :   log.printf("  KbT %f\n", kbt_);
    1433           3 :   if (t_specs.threshold != 0.0) log.printf("  %s bias threshold %f\n", t_specs.name.c_str(), t_specs.threshold);
    1434           3 :   if (t_specs.alpha != 1.0) log.printf("  %s decay shape parameter alpha %f\n", t_specs.name.c_str(), t_specs.alpha);
    1435           3 : }
    1436             : 
    1437        6036 : void MetaD::readGaussians(IFile *ifile)
    1438             : {
    1439        6036 :   unsigned ncv=getNumberOfArguments();
    1440        6036 :   std::vector<double> center(ncv);
    1441        6036 :   std::vector<double> sigma(ncv);
    1442             :   double height;
    1443             :   int nhills=0;
    1444        6036 :   bool multivariate=false;
    1445             : 
    1446             :   std::vector<Value> tmpvalues;
    1447       18121 :   for(unsigned j=0; j<getNumberOfArguments(); ++j) tmpvalues.push_back( Value( this, getPntrToArgument(j)->getName(), false ) );
    1448             : 
    1449        8156 :   while(scanOneHill(ifile,tmpvalues,center,sigma,height,multivariate))
    1450             :   {
    1451        2120 :     nhills++;
    1452             :     // note that for gamma=1 we store directly -F
    1453        2120 :     if(welltemp_ && biasf_>1.0) height*=(biasf_-1.0)/biasf_;
    1454        2120 :     addGaussian(Gaussian(multivariate,height,center,sigma));
    1455             :   }
    1456        6036 :   log.printf("      %d Gaussians read\n",nhills);
    1457       12072 : }
    1458             : 
    1459        2918 : void MetaD::writeGaussian(const Gaussian& hill, OFile&file)
    1460             : {
    1461        2918 :   unsigned ncv=getNumberOfArguments();
    1462        2918 :   file.printField("time",getTimeStep()*getStep());
    1463        8182 :   for(unsigned i=0; i<ncv; ++i) {
    1464        5264 :     file.printField(getPntrToArgument(i),hill.center[i]);
    1465             :   }
    1466        5836 :   hillsOfile_.printField("kerneltype","stretched-gaussian");
    1467        2918 :   if(hill.multivariate) {
    1468         892 :     hillsOfile_.printField("multivariate","true");
    1469             :     Matrix<double> mymatrix(ncv,ncv);
    1470             :     unsigned k=0;
    1471        1047 :     for(unsigned i=0; i<ncv; i++) {
    1472        1357 :       for(unsigned j=i; j<ncv; j++) {
    1473             :         // recompose the full inverse matrix
    1474         756 :         mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k];
    1475         756 :         k++;
    1476             :       }
    1477             :     }
    1478             :     // invert it
    1479             :     Matrix<double> invmatrix(ncv,ncv);
    1480         446 :     Invert(mymatrix,invmatrix);
    1481             :     // enforce symmetry
    1482        1047 :     for(unsigned i=0; i<ncv; i++) {
    1483        1357 :       for(unsigned j=i; j<ncv; j++) {
    1484         756 :         invmatrix(i,j)=invmatrix(j,i);
    1485             :       }
    1486             :     }
    1487             : 
    1488             :     // do cholesky so to have a "sigma like" number
    1489             :     Matrix<double> lower(ncv,ncv);
    1490         446 :     cholesky(invmatrix,lower);
    1491             :     // loop in band form
    1492        1047 :     for(unsigned i=0; i<ncv; i++) {
    1493        1357 :       for(unsigned j=0; j<ncv-i; j++) {
    1494        1512 :         file.printField("sigma_"+getPntrToArgument(j+i)->getName()+"_"+getPntrToArgument(j)->getName(),lower(j+i,j));
    1495             :       }
    1496             :     }
    1497             :   } else {
    1498        4944 :     hillsOfile_.printField("multivariate","false");
    1499        7135 :     for(unsigned i=0; i<ncv; ++i)
    1500        9326 :       file.printField("sigma_"+getPntrToArgument(i)->getName(),hill.sigma[i]);
    1501             :   }
    1502        2918 :   double height=hill.height;
    1503             :   // note that for gamma=1 we store directly -F
    1504        2918 :   if(welltemp_ && biasf_>1.0) height*=biasf_/(biasf_-1.0);
    1505        5836 :   file.printField("height",height).printField("biasf",biasf_);
    1506        4427 :   if(mw_n_>1) file.printField("clock",int(std::time(0)));
    1507        2918 :   file.printField();
    1508        2918 : }
    1509             : 
    1510        5200 : void MetaD::addGaussian(const Gaussian& hill)
    1511             : {
    1512        5200 :   if(grid_) {
    1513         636 :     size_t ncv=getNumberOfArguments();
    1514         636 :     std::vector<unsigned> nneighb=getGaussianSupport(hill);
    1515         636 :     std::vector<Grid::index_t> neighbors=BiasGrid_->getNeighbors(hill.center,nneighb);
    1516         636 :     std::vector<double> der(ncv);
    1517         636 :     std::vector<double> xx(ncv);
    1518         636 :     if(comm.Get_size()==1) {
    1519             :       // for performance reasons and thread safety
    1520         540 :       std::vector<double> dp(ncv);
    1521       55188 :       for(size_t i=0; i<neighbors.size(); ++i) {
    1522       54648 :         Grid::index_t ineigh=neighbors[i];
    1523      158526 :         for(unsigned j=0; j<ncv; ++j) der[j]=0.0;
    1524       54648 :         BiasGrid_->getPoint(ineigh,xx);
    1525       54648 :         double bias=evaluateGaussianAndDerivatives(xx,hill,der,dp);
    1526       54648 :         BiasGrid_->addValueAndDerivatives(ineigh,bias,der);
    1527             :       }
    1528             :     } else {
    1529          96 :       unsigned stride=comm.Get_size();
    1530          96 :       unsigned rank=comm.Get_rank();
    1531          96 :       std::vector<double> allder(ncv*neighbors.size(),0.0);
    1532          96 :       std::vector<double> n_der(ncv,0.0);
    1533          96 :       std::vector<double> allbias(neighbors.size(),0.0);
    1534             :       // for performance reasons and thread safety
    1535          96 :       std::vector<double> dp(ncv);
    1536       27148 :       for(unsigned i=rank; i<neighbors.size(); i+=stride) {
    1537       27052 :         Grid::index_t ineigh=neighbors[i];
    1538       81156 :         for(unsigned j=0; j<ncv; ++j) n_der[j]=0.0;
    1539       27052 :         BiasGrid_->getPoint(ineigh,xx);
    1540       27052 :         allbias[i]=evaluateGaussianAndDerivatives(xx,hill,n_der,dp);
    1541       81156 :         for(unsigned j=0; j<ncv; j++) allder[ncv*i+j]=n_der[j];
    1542             :       }
    1543          96 :       comm.Sum(allbias);
    1544          96 :       comm.Sum(allder);
    1545      103200 :       for(unsigned i=0; i<neighbors.size(); ++i) {
    1546      103104 :         Grid::index_t ineigh=neighbors[i];
    1547      309312 :         for(unsigned j=0; j<ncv; ++j) der[j]=allder[ncv*i+j];
    1548      103104 :         BiasGrid_->addValueAndDerivatives(ineigh,allbias[i],der);
    1549             :       }
    1550             :     }
    1551        4564 :   } else hills_.push_back(hill);
    1552        5200 : }
    1553             : 
    1554         636 : std::vector<unsigned> MetaD::getGaussianSupport(const Gaussian& hill)
    1555             : {
    1556             :   std::vector<unsigned> nneigh;
    1557             :   std::vector<double> cutoff;
    1558         636 :   unsigned ncv=getNumberOfArguments();
    1559             : 
    1560             :   // traditional or flexible hill?
    1561         636 :   if(hill.multivariate) {
    1562             :     unsigned k=0;
    1563             :     Matrix<double> mymatrix(ncv,ncv);
    1564           0 :     for(unsigned i=0; i<ncv; i++) {
    1565           0 :       for(unsigned j=i; j<ncv; j++) {
    1566             :         // recompose the full inverse matrix
    1567           0 :         mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k];
    1568           0 :         k++;
    1569             :       }
    1570             :     }
    1571             :     // Reinvert so to have the ellipses
    1572             :     Matrix<double> myinv(ncv,ncv);
    1573           0 :     Invert(mymatrix,myinv);
    1574             :     Matrix<double> myautovec(ncv,ncv);
    1575           0 :     std::vector<double> myautoval(ncv); //should I take this or their square root?
    1576           0 :     diagMat(myinv,myautoval,myautovec);
    1577             :     double maxautoval=0.;
    1578             :     unsigned ind_maxautoval; ind_maxautoval=ncv;
    1579           0 :     for(unsigned i=0; i<ncv; i++) {
    1580           0 :       if(myautoval[i]>maxautoval) {maxautoval=myautoval[i]; ind_maxautoval=i;}
    1581             :     }
    1582           0 :     for(unsigned i=0; i<ncv; i++) {
    1583           0 :       cutoff.push_back(std::sqrt(2.0*dp2cutoff)*std::abs(std::sqrt(maxautoval)*myautovec(i,ind_maxautoval)));
    1584             :     }
    1585             :   } else {
    1586        1606 :     for(unsigned i=0; i<ncv; ++i) {
    1587         970 :       cutoff.push_back(std::sqrt(2.0*dp2cutoff)*hill.sigma[i]);
    1588             :     }
    1589             :   }
    1590             : 
    1591         636 :   if(doInt_) {
    1592           2 :     if(hill.center[0]+cutoff[0] > uppI_ || hill.center[0]-cutoff[0] < lowI_) {
    1593             :       // in this case, we updated the entire grid to avoid problems
    1594           2 :       return BiasGrid_->getNbin();
    1595             :     } else {
    1596           0 :       nneigh.push_back( static_cast<unsigned>(ceil(cutoff[0]/BiasGrid_->getDx()[0])) );
    1597             :       return nneigh;
    1598             :     }
    1599             :   } else {
    1600        1602 :     for(unsigned i=0; i<ncv; i++) {
    1601        1936 :       nneigh.push_back( static_cast<unsigned>(ceil(cutoff[i]/BiasGrid_->getDx()[i])) );
    1602             :     }
    1603             :   }
    1604             : 
    1605             :   return nneigh;
    1606             : }
    1607             : 
    1608         281 : double MetaD::getBias(const std::vector<double>& cv)
    1609             : {
    1610         281 :   double bias=0.0;
    1611         281 :   if(grid_) bias = BiasGrid_->getValue(cv);
    1612             :   else {
    1613          82 :     unsigned nt=OpenMP::getNumThreads();
    1614          82 :     unsigned stride=comm.Get_size();
    1615          82 :     unsigned rank=comm.Get_rank();
    1616             : 
    1617          82 :     if(!nlist_) {
    1618          82 :       #pragma omp parallel num_threads(nt)
    1619             :       {
    1620             :         #pragma omp for reduction(+:bias) nowait
    1621             :         for(unsigned i=rank; i<hills_.size(); i+=stride) bias+=evaluateGaussian(cv,hills_[i]);
    1622             :       }
    1623             :     } else {
    1624           0 :       #pragma omp parallel num_threads(nt)
    1625             :       {
    1626             :         #pragma omp for reduction(+:bias) nowait
    1627             :         for(unsigned i=rank; i<nlist_hills_.size(); i+=stride) bias+=evaluateGaussian(cv,nlist_hills_[i]);
    1628             :       }
    1629             :     }
    1630          82 :     comm.Sum(bias);
    1631             :   }
    1632             : 
    1633         281 :   return bias;
    1634             : }
    1635             : 
    1636        8390 : double MetaD::getBiasAndDerivatives(const std::vector<double>& cv, std::vector<double>& der)
    1637             : {
    1638        8390 :   unsigned ncv=getNumberOfArguments();
    1639        8390 :   double bias=0.0;
    1640        8390 :   if(grid_) {
    1641        1501 :     std::vector<double> vder(ncv);
    1642        1501 :     bias=BiasGrid_->getValueAndDerivatives(cv,vder);
    1643        3483 :     for(unsigned i=0; i<ncv; i++) der[i]=vder[i];
    1644             :   } else {
    1645        6889 :     unsigned nt=OpenMP::getNumThreads();
    1646        6889 :     unsigned stride=comm.Get_size();
    1647        6889 :     unsigned rank=comm.Get_rank();
    1648             : 
    1649        6889 :     if(!nlist_) {
    1650        6884 :       if(hills_.size()<2*nt*stride||nt==1) {
    1651             :         // for performance reasons and thread safety
    1652        2587 :         std::vector<double> dp(ncv);
    1653        6704 :         for(unsigned i=rank; i<hills_.size(); i+=stride) {
    1654        4117 :           bias+=evaluateGaussianAndDerivatives(cv,hills_[i],der,dp);
    1655             :         }
    1656             :       } else {
    1657        4297 :         #pragma omp parallel num_threads(nt)
    1658             :         {
    1659             :           std::vector<double> omp_deriv(ncv,0.);
    1660             :           // for performance reasons and thread safety
    1661             :           std::vector<double> dp(ncv);
    1662             :           #pragma omp for reduction(+:bias) nowait
    1663             :           for(unsigned i=rank; i<hills_.size(); i+=stride) {
    1664             :             bias+=evaluateGaussianAndDerivatives(cv,hills_[i],omp_deriv,dp);
    1665             :           }
    1666             :           #pragma omp critical
    1667             :           for(unsigned i=0; i<ncv; i++) der[i]+=omp_deriv[i];
    1668             :         }
    1669             :       }
    1670             :     } else {
    1671           5 :       if(hills_.size()<2*nt*stride||nt==1) {
    1672             :         // for performance reasons and thread safety
    1673           0 :         std::vector<double> dp(ncv);
    1674           0 :         for(unsigned i=rank; i<nlist_hills_.size(); i+=stride) {
    1675           0 :           bias+=evaluateGaussianAndDerivatives(cv,nlist_hills_[i],der,dp);
    1676             :         }
    1677             :       } else {
    1678           5 :         #pragma omp parallel num_threads(nt)
    1679             :         {
    1680             :           std::vector<double> omp_deriv(ncv,0.);
    1681             :           // for performance reasons and thread safety
    1682             :           std::vector<double> dp(ncv);
    1683             :           #pragma omp for reduction(+:bias) nowait
    1684             :           for(unsigned i=rank; i<nlist_hills_.size(); i+=stride) {
    1685             :             bias+=evaluateGaussianAndDerivatives(cv,nlist_hills_[i],omp_deriv,dp);
    1686             :           }
    1687             :           #pragma omp critical
    1688             :           for(unsigned i=0; i<ncv; i++) der[i]+=omp_deriv[i];
    1689             :         }
    1690             :       }
    1691             :     }
    1692        6889 :     comm.Sum(bias);
    1693        6889 :     comm.Sum(der);
    1694             :   }
    1695             : 
    1696        8390 :   return bias;
    1697             : }
    1698             : 
    1699           0 : double MetaD::getGaussianNormalization(const Gaussian& hill)
    1700             : {
    1701             :   double norm=1;
    1702           0 :   unsigned ncv=hill.center.size();
    1703             : 
    1704           0 :   if(hill.multivariate) {
    1705             :     // recompose the full sigma from the upper diag cholesky
    1706             :     unsigned k=0;
    1707             :     Matrix<double> mymatrix(ncv,ncv);
    1708           0 :     for(unsigned i=0; i<ncv; i++) {
    1709           0 :       for(unsigned j=i; j<ncv; j++) {
    1710           0 :         mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k]; // recompose the full inverse matrix
    1711           0 :         k++;
    1712             :       }
    1713           0 :       double ldet; logdet( mymatrix, ldet );
    1714           0 :       norm = std::exp( ldet );  // Not sure here if mymatrix is sigma or inverse
    1715             :     }
    1716             :   } else {
    1717           0 :     for(unsigned i=0; i<hill.sigma.size(); i++) norm*=hill.sigma[i];
    1718             :   }
    1719             : 
    1720           0 :   return norm*std::pow(2*pi,static_cast<double>(ncv)/2.0);
    1721             : }
    1722             : 
    1723         192 : double MetaD::evaluateGaussian(const std::vector<double>& cv, const Gaussian& hill)
    1724             : {
    1725         192 :   unsigned ncv=cv.size();
    1726             : 
    1727             :   // I use a pointer here because cv is const (and should be const)
    1728             :   // but when using doInt it is easier to locally replace cv[0] with
    1729             :   // the upper/lower limit in case it is out of range
    1730             :   double tmpcv[1];
    1731             :   const double *pcv=NULL; // pointer to cv
    1732         192 :   if(ncv>0) pcv=&cv[0];
    1733         192 :   if(doInt_) {
    1734           0 :     plumed_assert(ncv==1);
    1735           0 :     tmpcv[0]=cv[0];
    1736           0 :     if(cv[0]<lowI_) tmpcv[0]=lowI_;
    1737           0 :     if(cv[0]>uppI_) tmpcv[0]=uppI_;
    1738             :     pcv=&(tmpcv[0]);
    1739             :   }
    1740             : 
    1741             :   double dp2=0.0;
    1742         192 :   if(hill.multivariate) {
    1743             :     unsigned k=0;
    1744             :     // recompose the full sigma from the upper diag cholesky
    1745             :     Matrix<double> mymatrix(ncv,ncv);
    1746           0 :     for(unsigned i=0; i<ncv; i++) {
    1747           0 :       for(unsigned j=i; j<ncv; j++) {
    1748           0 :         mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k]; // recompose the full inverse matrix
    1749           0 :         k++;
    1750             :       }
    1751             :     }
    1752           0 :     for(unsigned i=0; i<ncv; i++) {
    1753           0 :       double dp_i=difference(i,hill.center[i],pcv[i]);
    1754           0 :       for(unsigned j=i; j<ncv; j++) {
    1755           0 :         if(i==j) {
    1756           0 :           dp2+=dp_i*dp_i*mymatrix(i,j)*0.5;
    1757             :         } else {
    1758           0 :           double dp_j=difference(j,hill.center[j],pcv[j]);
    1759           0 :           dp2+=dp_i*dp_j*mymatrix(i,j);
    1760             :         }
    1761             :       }
    1762             :     }
    1763             :   } else {
    1764         576 :     for(unsigned i=0; i<ncv; i++) {
    1765         384 :       double dp=difference(i,hill.center[i],pcv[i])*hill.invsigma[i];
    1766         384 :       dp2+=dp*dp;
    1767             :     }
    1768         192 :     dp2*=0.5;
    1769             :   }
    1770             : 
    1771             :   double bias=0.0;
    1772         192 :   if(dp2<dp2cutoff) bias=hill.height*(stretchA*std::exp(-dp2)+stretchB);
    1773             : 
    1774         192 :   return bias;
    1775             : }
    1776             : 
    1777     2408896 : double MetaD::evaluateGaussianAndDerivatives(const std::vector<double>& cv, const Gaussian& hill, std::vector<double>& der, std::vector<double>& dp_)
    1778             : {
    1779     2408896 :   unsigned ncv=cv.size();
    1780             : 
    1781             :   // I use a pointer here because cv is const (and should be const)
    1782             :   // but when using doInt it is easier to locally replace cv[0] with
    1783             :   // the upper/lower limit in case it is out of range
    1784             :   const double *pcv=NULL; // pointer to cv
    1785             :   double tmpcv[1]; // tmp array with cv (to be used with doInt_)
    1786     2408896 :   if(ncv>0) pcv=&cv[0];
    1787     2408896 :   if(doInt_) {
    1788         602 :     plumed_assert(ncv==1);
    1789         602 :     tmpcv[0]=cv[0];
    1790         602 :     if(cv[0]<lowI_) tmpcv[0]=lowI_;
    1791         602 :     if(cv[0]>uppI_) tmpcv[0]=uppI_;
    1792             :     pcv=&(tmpcv[0]);
    1793             :   }
    1794             : 
    1795             :   bool int_der=false;
    1796     2408896 :   if(doInt_) {
    1797         602 :     if(cv[0]<lowI_ || cv[0]>uppI_) int_der=true;
    1798             :   }
    1799             : 
    1800             :   double dp2=0.0;
    1801             :   double bias=0.0;
    1802     2408896 :   if(hill.multivariate) {
    1803             :     unsigned k=0;
    1804             :     // recompose the full sigma from the upper diag cholesky
    1805             :     Matrix<double> mymatrix(ncv,ncv);
    1806      161635 :     for(unsigned i=0; i<ncv; i++) {
    1807      162513 :       for(unsigned j=i; j<ncv; j++) {
    1808       81476 :         mymatrix(i,j)=mymatrix(j,i)=hill.sigma[k]; // recompose the full inverse matrix
    1809       81476 :         k++;
    1810             :       }
    1811             :     }
    1812      161635 :     for(unsigned i=0; i<ncv; i++) {
    1813       81037 :       dp_[i]=difference(i,hill.center[i],pcv[i]);
    1814      162513 :       for(unsigned j=i; j<ncv; j++) {
    1815       81476 :         if(i==j) {
    1816       81037 :           dp2+=dp_[i]*dp_[i]*mymatrix(i,j)*0.5;
    1817             :         } else {
    1818         439 :           double dp_j=difference(j,hill.center[j],pcv[j]);
    1819         439 :           dp2+=dp_[i]*dp_j*mymatrix(i,j);
    1820             :         }
    1821             :       }
    1822             :     }
    1823       80598 :     if(dp2<dp2cutoff) {
    1824       77683 :       bias=hill.height*std::exp(-dp2);
    1825       77683 :       if(!int_der) {
    1826      155673 :         for(unsigned i=0; i<ncv; i++) {
    1827             :           double tmp=0.0;
    1828      156594 :           for(unsigned j=0; j<ncv; j++) tmp += dp_[j]*mymatrix(i,j)*bias;
    1829       77990 :           der[i]-=tmp*stretchA;
    1830             :         }
    1831             :       } else {
    1832           0 :         for(unsigned i=0; i<ncv; i++) der[i]=0.;
    1833             :       }
    1834       77683 :       bias=stretchA*bias+hill.height*stretchB;
    1835             :     }
    1836             :   } else {
    1837     6975252 :     for(unsigned i=0; i<ncv; i++) {
    1838     4646954 :       dp_[i]=difference(i,hill.center[i],pcv[i])*hill.invsigma[i];
    1839     4646954 :       dp2+=dp_[i]*dp_[i];
    1840             :     }
    1841     2328298 :     dp2*=0.5;
    1842     2328298 :     if(dp2<dp2cutoff) {
    1843     1356532 :       bias=hill.height*std::exp(-dp2);
    1844     1356532 :       if(!int_der) {
    1845     4060817 :         for(unsigned i=0; i<ncv; i++) der[i]-=bias*dp_[i]*hill.invsigma[i]*stretchA;
    1846             :       } else {
    1847         478 :         for(unsigned i=0; i<ncv; i++) der[i]=0.;
    1848             :       }
    1849     1356532 :       bias=stretchA*bias+hill.height*stretchB;
    1850             :     }
    1851             :   }
    1852             : 
    1853     2408896 :   return bias;
    1854             : }
    1855             : 
    1856        2732 : double MetaD::getHeight(const std::vector<double>& cv)
    1857             : {
    1858        2732 :   double height=height0_;
    1859        2732 :   if(welltemp_) {
    1860         271 :     double vbias = getBias(cv);
    1861         271 :     if(biasf_>1.0) {
    1862         255 :       height = height0_*std::exp(-vbias/(kbt_*(biasf_-1.0)));
    1863             :     } else {
    1864             :       // notice that if gamma=1 we store directly -F
    1865          16 :       height = height0_*std::exp(-vbias/kbt_);
    1866             :     }
    1867             :   }
    1868        2732 :   if(dampfactor_>0.0) {
    1869          18 :     plumed_assert(BiasGrid_);
    1870          18 :     double m=BiasGrid_->getMaxValue();
    1871          18 :     height*=std::exp(-m/(kbt_*(dampfactor_)));
    1872             :   }
    1873        2732 :   if (tt_specs_.is_active) {
    1874          60 :     double vbarrier = transition_bias_;
    1875          60 :     temperHeight(height, tt_specs_, vbarrier);
    1876             :   }
    1877        2732 :   if(TargetGrid_) {
    1878          18 :     double f=TargetGrid_->getValue(cv)-TargetGrid_->getMaxValue();
    1879          18 :     height*=std::exp(f/kbt_);
    1880             :   }
    1881        2732 :   return height;
    1882             : }
    1883             : 
    1884          60 : void MetaD::temperHeight(double& height, const TemperingSpecs& t_specs, const double tempering_bias)
    1885             : {
    1886          60 :   if (t_specs.alpha == 1.0) {
    1887          80 :     height *= std::exp(-std::max(0.0, tempering_bias - t_specs.threshold) / (kbt_ * (t_specs.biasf - 1.0)));
    1888             :   } else {
    1889          40 :     height *= std::pow(1 + (1 - t_specs.alpha) / t_specs.alpha * std::max(0.0, tempering_bias - t_specs.threshold) / (kbt_ * (t_specs.biasf - 1.0)), - t_specs.alpha / (1 - t_specs.alpha));
    1890             :   }
    1891          60 : }
    1892             : 
    1893        8430 : void MetaD::calculate()
    1894             : {
    1895             :   // this is because presently there is no way to properly pass information
    1896             :   // on adaptive hills (diff) after exchanges:
    1897        8430 :   if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) error("ADAPTIVE=DIFF is not compatible with replica exchange");
    1898             : 
    1899        8430 :   const unsigned ncv=getNumberOfArguments();
    1900        8430 :   std::vector<double> cv(ncv);
    1901       21067 :   for(unsigned i=0; i<ncv; ++i) cv[i]=getArgument(i);
    1902             : 
    1903        8430 :   if(nlist_) {
    1904           5 :     nlist_steps_++;
    1905           5 :     if(getExchangeStep()) nlist_update_=true;
    1906             :     else {
    1907          11 :       for(unsigned i=0; i<ncv; ++i) {
    1908           8 :         double d = difference(i, cv[i], nlist_center_[i]);
    1909           8 :         double nk_dist2 = d*d/nlist_dev2_[i];
    1910           8 :         if(nk_dist2>nlist_param_[1]) {nlist_update_=true; break;}
    1911             :       }
    1912             :     }
    1913           5 :     if(nlist_update_) updateNlist();
    1914             :   }
    1915             : 
    1916             :   double ene = 0.;
    1917        8430 :   std::vector<double> der(ncv,0.);
    1918        8430 :   if(biasf_!=1.0) ene = getBiasAndDerivatives(cv,der);
    1919             :   setBias(ene);
    1920       21067 :   for(unsigned i=0; i<ncv; i++) setOutputForce(i,-der[i]);
    1921             : 
    1922        8435 :   if(calc_work_) getPntrToComponent("work")->set(work_);
    1923        8540 :   if(calc_rct_) getPntrToComponent("rbias")->set(ene - reweight_factor_);
    1924             :   // calculate the acceleration factor
    1925        8430 :   if(acceleration_&&!isFirstStep_) {
    1926         329 :     acc_ += static_cast<double>(getStride()) * std::exp(ene/(kbt_));
    1927         329 :     const double mean_acc = acc_/((double) getStep());
    1928         329 :     getPntrToComponent("acc")->set(mean_acc);
    1929        8430 :   } else if (acceleration_ && isFirstStep_ && acc_restart_mean_ > 0.0) {
    1930           2 :     acc_ = acc_restart_mean_ * static_cast<double>(getStep());
    1931           2 :     if(freq_adaptive_) {
    1932             :       // has to be done here if restarting, as the acc is not defined before
    1933           1 :       updateFrequencyAdaptiveStride();
    1934             :     }
    1935             :   }
    1936        8430 : }
    1937             : 
    1938        6234 : void MetaD::update()
    1939             : {
    1940             :   // adding hills criteria (could be more complex though)
    1941             :   bool nowAddAHill;
    1942        6234 :   if(getStep()%current_stride_==0 && !isFirstStep_) nowAddAHill=true;
    1943             :   else {
    1944             :     nowAddAHill=false;
    1945        3502 :     isFirstStep_=false;
    1946             :   }
    1947             : 
    1948        6234 :   unsigned ncv=getNumberOfArguments();
    1949        6234 :   std::vector<double> cv(ncv);
    1950       16675 :   for(unsigned i=0; i<ncv; ++i) cv[i] = getArgument(i);
    1951             : 
    1952             :   double vbias=0.;
    1953        6234 :   if(calc_work_) vbias=getBias(cv);
    1954             : 
    1955             :   // if you use adaptive, call the FlexibleBin
    1956             :   bool multivariate=false;
    1957        6234 :   if(adaptive_!=FlexibleBin::none) {
    1958         778 :     flexbin_->update(nowAddAHill);
    1959             :     multivariate=true;
    1960             :   }
    1961             : 
    1962             :   std::vector<double> thissigma;
    1963        6234 :   if(nowAddAHill) {
    1964             :     // add a Gaussian
    1965        2732 :     double height=getHeight(cv);
    1966             :     // returns upper diagonal inverse
    1967        3106 :     if(adaptive_!=FlexibleBin::none) thissigma=flexbin_->getInverseMatrix();
    1968             :     // returns normal sigma
    1969        2358 :     else thissigma=sigma0_;
    1970             : 
    1971             :     // In case we use walkers_mpi, it is now necessary to communicate with other replicas.
    1972        2732 :     if(walkers_mpi_) {
    1973             :       // Allocate arrays to store all walkers hills
    1974         174 :       std::vector<double> all_cv(mpi_nw_*ncv,0.0);
    1975         174 :       std::vector<double> all_sigma(mpi_nw_*thissigma.size(),0.0);
    1976         174 :       std::vector<double> all_height(mpi_nw_,0.0);
    1977         174 :       std::vector<int>    all_multivariate(mpi_nw_,0);
    1978         174 :       if(comm.Get_rank()==0) {
    1979             :         // Communicate (only root)
    1980          99 :         multi_sim_comm.Allgather(cv,all_cv);
    1981          99 :         multi_sim_comm.Allgather(thissigma,all_sigma);
    1982             :         // notice that if gamma=1 we store directly -F so this scaling is not necessary:
    1983          99 :         multi_sim_comm.Allgather(height*(biasf_>1.0?biasf_/(biasf_-1.0):1.0),all_height);
    1984          99 :         multi_sim_comm.Allgather(int(multivariate),all_multivariate);
    1985             :       }
    1986             :       // Share info with group members
    1987         174 :       comm.Bcast(all_cv,0);
    1988         174 :       comm.Bcast(all_sigma,0);
    1989         174 :       comm.Bcast(all_height,0);
    1990         174 :       comm.Bcast(all_multivariate,0);
    1991             : 
    1992             :       // Flying Gaussian
    1993         174 :       if (flying_) {
    1994          54 :         hills_.clear();
    1995          54 :         comm.Barrier();
    1996             :       }
    1997             : 
    1998         696 :       for(unsigned i=0; i<mpi_nw_; i++) {
    1999             :         // actually add hills one by one
    2000         522 :         std::vector<double> cv_now(ncv);
    2001         522 :         std::vector<double> sigma_now(thissigma.size());
    2002        1566 :         for(unsigned j=0; j<ncv; j++) cv_now[j]=all_cv[i*ncv+j];
    2003        1674 :         for(unsigned j=0; j<thissigma.size(); j++) sigma_now[j]=all_sigma[i*thissigma.size()+j];
    2004             :         // notice that if gamma=1 we store directly -F so this scaling is not necessary:
    2005         522 :         double fact=(biasf_>1.0?(biasf_-1.0)/biasf_:1.0);
    2006         522 :         Gaussian newhill=Gaussian(all_multivariate[i],all_height[i]*fact,cv_now,sigma_now);
    2007         522 :         addGaussian(newhill);
    2008         522 :         if(!flying_) writeGaussian(newhill,hillsOfile_);
    2009         522 :       }
    2010             :     } else {
    2011        2558 :       Gaussian newhill=Gaussian(multivariate,height,cv,thissigma);
    2012        2558 :       addGaussian(newhill);
    2013        2558 :       writeGaussian(newhill,hillsOfile_);
    2014        2558 :     }
    2015             : 
    2016             :     // this is to update the hills neighbor list
    2017        2732 :     if(nlist_) nlist_update_=true;
    2018             :   }
    2019             : 
    2020             :   // this should be outside of the if block in case
    2021             :   // mw_rstride_ is not a multiple of stride_
    2022        6234 :   if(mw_n_>1 && getStep()%mw_rstride_==0) hillsOfile_.flush();
    2023             : 
    2024        6234 :   if(calc_work_) {
    2025           5 :     if(nlist_) updateNlist();
    2026           5 :     double vbias1=getBias(cv);
    2027           5 :     work_+=vbias1-vbias;
    2028             :   }
    2029             : 
    2030             :   // dump grid on file
    2031        6234 :   if(wgridstride_>0&&(getStep()%wgridstride_==0||getCPT())) {
    2032             :     // in case old grids are stored, a sequence of grids should appear
    2033             :     // this call results in a repetition of the header:
    2034          90 :     if(storeOldGrids_) gridfile_.clearFields();
    2035             :     // in case only latest grid is stored, file should be rewound
    2036             :     // this will overwrite previously written grids
    2037             :     else {
    2038          50 :       int r = 0;
    2039          50 :       if(walkers_mpi_) {
    2040           0 :         if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank();
    2041           0 :         comm.Bcast(r,0);
    2042             :       }
    2043          50 :       if(r==0) gridfile_.rewind();
    2044             :     }
    2045          90 :     BiasGrid_->writeToFile(gridfile_);
    2046             :     // if a single grid is stored, it is necessary to flush it, otherwise
    2047             :     // the file might stay empty forever (when a single grid is not large enough to
    2048             :     // trigger flushing from the operating system).
    2049             :     // on the other hand, if grids are stored one after the other this is
    2050             :     // no necessary, and we leave the flushing control to the user as usual
    2051             :     // (with FLUSH keyword)
    2052          90 :     if(!storeOldGrids_) gridfile_.flush();
    2053             :   }
    2054             : 
    2055             :   // if multiple walkers and time to read Gaussians
    2056        6234 :   if(mw_n_>1 && getStep()%mw_rstride_==0) {
    2057       12048 :     for(int i=0; i<mw_n_; ++i) {
    2058             :       // don't read your own Gaussians
    2059        9036 :       if(i==mw_id_) continue;
    2060             :       // if the file is not open yet
    2061        6024 :       if(!(ifiles_[i]->isOpen())) {
    2062             :         // check if it exists now and open it!
    2063           7 :         if(ifiles_[i]->FileExist(ifilesnames_[i])) {
    2064           7 :           ifiles_[i]->open(ifilesnames_[i]);
    2065           7 :           ifiles_[i]->reset(false);
    2066             :         }
    2067             :         // otherwise read the new Gaussians
    2068             :       } else {
    2069        6017 :         log.printf("  Reading hills from %s:",ifilesnames_[i].c_str());
    2070        6017 :         readGaussians(ifiles_[i].get());
    2071        6017 :         ifiles_[i]->reset(false);
    2072             :       }
    2073             :     }
    2074             :     // this is to update the hills neighbor list
    2075        3012 :     if(nlist_) nlist_update_=true;
    2076             :   }
    2077             : 
    2078             :   // Recalculate special bias quantities whenever the bias has been changed by the update.
    2079        6234 :   bool bias_has_changed = (nowAddAHill || (mw_n_ > 1 && getStep() % mw_rstride_ == 0));
    2080        6234 :   if (calc_rct_ && bias_has_changed && getStep()%(stride_*rct_ustride_)==0) computeReweightingFactor();
    2081        6234 :   if (calc_max_bias_ && bias_has_changed) {
    2082           0 :     max_bias_ = BiasGrid_->getMaxValue();
    2083           0 :     getPntrToComponent("maxbias")->set(max_bias_);
    2084             :   }
    2085        6234 :   if (calc_transition_bias_ && bias_has_changed) {
    2086         260 :     transition_bias_ = getTransitionBarrierBias();
    2087         520 :     getPntrToComponent("transbias")->set(transition_bias_);
    2088             :   }
    2089             : 
    2090             :   // Frequency adaptive metadynamics - update hill addition frequency
    2091        6234 :   if(freq_adaptive_ && getStep()%fa_update_frequency_==0) {
    2092         151 :     updateFrequencyAdaptiveStride();
    2093             :   }
    2094        6234 : }
    2095             : 
    2096             : /// takes a pointer to the file and a template std::string with values v and gives back the next center, sigma and height
    2097        8156 : bool MetaD::scanOneHill(IFile* ifile, std::vector<Value>& tmpvalues, std::vector<double>& center, std::vector<double>& sigma, double& height, bool& multivariate)
    2098             : {
    2099             :   double dummy;
    2100        8156 :   multivariate=false;
    2101       16312 :   if(ifile->scanField("time",dummy)) {
    2102        2120 :     unsigned ncv=tmpvalues.size();
    2103        6314 :     for(unsigned i=0; i<ncv; ++i) {
    2104        4194 :       ifile->scanField( &tmpvalues[i] );
    2105        4194 :       if( tmpvalues[i].isPeriodic() && ! getPntrToArgument(i)->isPeriodic() ) {
    2106           0 :         error("in hills file periodicity for variable " + tmpvalues[i].getName() + " does not match periodicity in input");
    2107        4194 :       } else if( tmpvalues[i].isPeriodic() ) {
    2108           0 :         std::string imin, imax; tmpvalues[i].getDomain( imin, imax );
    2109           0 :         std::string rmin, rmax; getPntrToArgument(i)->getDomain( rmin, rmax );
    2110           0 :         if( imin!=rmin || imax!=rmax ) {
    2111           0 :           error("in hills file periodicity for variable " + tmpvalues[i].getName() + " does not match periodicity in input");
    2112             :         }
    2113             :       }
    2114        4194 :       center[i]=tmpvalues[i].get();
    2115             :     }
    2116             :     // scan for kerneltype
    2117        2120 :     std::string ktype="stretched-gaussian";
    2118        6351 :     if( ifile->FieldExist("kerneltype") ) ifile->scanField("kerneltype",ktype);
    2119        2120 :     if( ktype=="gaussian" ) {
    2120          12 :       noStretchWarning();
    2121        2108 :     } else if( ktype!="stretched-gaussian") {
    2122           0 :       error("non Gaussian kernels are not supported in MetaD");
    2123             :     }
    2124             :     // scan for multivariate label: record the actual file position so to eventually rewind
    2125             :     std::string sss;
    2126        4240 :     ifile->scanField("multivariate",sss);
    2127        2120 :     if(sss=="true") multivariate=true;
    2128        2120 :     else if(sss=="false") multivariate=false;
    2129           0 :     else plumed_merror("cannot parse multivariate = "+ sss);
    2130        2120 :     if(multivariate) {
    2131           0 :       sigma.resize(ncv*(ncv+1)/2);
    2132             :       Matrix<double> upper(ncv,ncv);
    2133             :       Matrix<double> lower(ncv,ncv);
    2134           0 :       for(unsigned i=0; i<ncv; i++) {
    2135           0 :         for(unsigned j=0; j<ncv-i; j++) {
    2136           0 :           ifile->scanField("sigma_"+getPntrToArgument(j+i)->getName()+"_"+getPntrToArgument(j)->getName(),lower(j+i,j));
    2137           0 :           upper(j,j+i)=lower(j+i,j);
    2138             :         }
    2139             :       }
    2140             :       Matrix<double> mymult(ncv,ncv);
    2141             :       Matrix<double> invmatrix(ncv,ncv);
    2142           0 :       mult(lower,upper,mymult);
    2143             :       // now invert and get the sigmas
    2144           0 :       Invert(mymult,invmatrix);
    2145             :       // put the sigmas in the usual order: upper diagonal (this time in normal form and not in band form)
    2146             :       unsigned k=0;
    2147           0 :       for(unsigned i=0; i<ncv; i++) {
    2148           0 :         for(unsigned j=i; j<ncv; j++) {
    2149           0 :           sigma[k]=invmatrix(i,j);
    2150           0 :           k++;
    2151             :         }
    2152             :       }
    2153             :     } else {
    2154        6314 :       for(unsigned i=0; i<ncv; ++i) {
    2155        8388 :         ifile->scanField("sigma_"+getPntrToArgument(i)->getName(),sigma[i]);
    2156             :       }
    2157             :     }
    2158             : 
    2159        2120 :     ifile->scanField("height",height);
    2160        2120 :     ifile->scanField("biasf",dummy);
    2161        6177 :     if(ifile->FieldExist("clock")) ifile->scanField("clock",dummy);
    2162        4240 :     if(ifile->FieldExist("lower_int")) ifile->scanField("lower_int",dummy);
    2163        4240 :     if(ifile->FieldExist("upper_int")) ifile->scanField("upper_int",dummy);
    2164        2120 :     ifile->scanField();
    2165             :     return true;
    2166             :   } else {
    2167             :     return false;
    2168             :   }
    2169             : }
    2170             : 
    2171         102 : void MetaD::computeReweightingFactor()
    2172             : {
    2173         102 :   if(biasf_==1.0) { // in this case we have no bias, so reweight factor is 0.0
    2174           0 :     getPntrToComponent("rct")->set(0.0);
    2175           0 :     return;
    2176             :   }
    2177             : 
    2178         102 :   double Z_0=0; //proportional to the integral of exp(-beta*F)
    2179         102 :   double Z_V=0; //proportional to the integral of exp(-beta*(F+V))
    2180         102 :   double minusBetaF=biasf_/(biasf_-1.)/kbt_;
    2181         102 :   double minusBetaFplusV=1./(biasf_-1.)/kbt_;
    2182         102 :   if (biasf_==-1.0) { //non well-tempered case
    2183           0 :     minusBetaF=1./kbt_;
    2184             :     minusBetaFplusV=0;
    2185             :   }
    2186         102 :   max_bias_=BiasGrid_->getMaxValue(); //to avoid exp overflow
    2187             : 
    2188         102 :   const unsigned rank=comm.Get_rank();
    2189         102 :   const unsigned stride=comm.Get_size();
    2190      920504 :   for (Grid::index_t t=rank; t<BiasGrid_->getSize(); t+=stride) {
    2191      920402 :     const double val=BiasGrid_->getValue(t);
    2192      920402 :     Z_0+=std::exp(minusBetaF*(val-max_bias_));
    2193      920402 :     Z_V+=std::exp(minusBetaFplusV*(val-max_bias_));
    2194             :   }
    2195         102 :   comm.Sum(Z_0);
    2196         102 :   comm.Sum(Z_V);
    2197             : 
    2198         102 :   reweight_factor_=kbt_*std::log(Z_0/Z_V)+max_bias_;
    2199         204 :   getPntrToComponent("rct")->set(reweight_factor_);
    2200             : }
    2201             : 
    2202         273 : double MetaD::getTransitionBarrierBias()
    2203             : {
    2204             :   // If there is only one well of interest, return the bias at that well point.
    2205         273 :   if (transitionwells_.size() == 1) {
    2206           0 :     double tb_bias = getBias(transitionwells_[0]);
    2207           0 :     return tb_bias;
    2208             : 
    2209             :     // Otherwise, check for the least barrier bias between all pairs of wells.
    2210             :     // Note that because the paths can be considered edges between the wells' nodes
    2211             :     // to make a graph and the path barriers satisfy certain cycle inequalities, it
    2212             :     // is sufficient to look at paths corresponding to a minimal spanning tree of the
    2213             :     // overall graph rather than examining every edge in the graph.
    2214             :     // For simplicity, I chose the star graph with center well 0 as the spanning tree.
    2215             :     // It is most efficient to start the path searches from the wells that are
    2216             :     // expected to be sampled last, so transitionwell_[0] should correspond to the
    2217             :     // starting well. With this choice the searches will terminate in one step until
    2218             :     // transitionwell_[1] is sampled.
    2219             :   } else {
    2220             :     double least_transition_bias;
    2221         273 :     std::vector<double> sink = transitionwells_[0];
    2222         273 :     std::vector<double> source = transitionwells_[1];
    2223         273 :     least_transition_bias = BiasGrid_->findMaximalPathMinimum(source, sink);
    2224         273 :     for (unsigned i = 2; i < transitionwells_.size(); i++) {
    2225           0 :       if (least_transition_bias == 0.0) {
    2226             :         break;
    2227             :       }
    2228           0 :       source = transitionwells_[i];
    2229           0 :       double curr_transition_bias = BiasGrid_->findMaximalPathMinimum(source, sink);
    2230           0 :       least_transition_bias = fmin(curr_transition_bias, least_transition_bias);
    2231             :     }
    2232             :     return least_transition_bias;
    2233             :   }
    2234             : }
    2235             : 
    2236         154 : void MetaD::updateFrequencyAdaptiveStride()
    2237             : {
    2238         154 :   plumed_massert(freq_adaptive_,"should only be used if frequency adaptive metadynamics is enabled");
    2239         154 :   plumed_massert(acceleration_,"frequency adaptive metadynamics can only be used if the acceleration factor is calculated");
    2240         154 :   const double mean_acc = acc_/((double) getStep());
    2241         154 :   int tmp_stride= stride_*floor((mean_acc/fa_min_acceleration_)+0.5);
    2242         154 :   if(mean_acc >= fa_min_acceleration_) {
    2243         129 :     if(tmp_stride > current_stride_) {current_stride_ = tmp_stride;}
    2244             :   }
    2245         154 :   if(fa_max_stride_!=0 && current_stride_>fa_max_stride_) {
    2246           0 :     current_stride_=fa_max_stride_;
    2247             :   }
    2248         154 :   getPntrToComponent("pace")->set(current_stride_);
    2249         154 : }
    2250             : 
    2251        8430 : bool MetaD::checkNeedsGradients()const
    2252             : {
    2253        8430 :   if(adaptive_==FlexibleBin::geometry) {
    2254         192 :     if(getStep()%stride_==0 && !isFirstStep_) return true;
    2255         109 :     else return false;
    2256             :   } else return false;
    2257             : }
    2258             : 
    2259           4 : void MetaD::updateNlist()
    2260             : {
    2261             :   // no need to check for neighbors
    2262           4 :   if(hills_.size()==0) return;
    2263             : 
    2264             :   // here we generate the neighbor list
    2265           4 :   nlist_hills_.clear();
    2266             :   std::vector<Gaussian> local_flat_nl;
    2267           4 :   unsigned nt=OpenMP::getNumThreads();
    2268           4 :   if(hills_.size()<2*nt) nt=1;
    2269           4 :   #pragma omp parallel num_threads(nt)
    2270             :   {
    2271             :     std::vector<Gaussian> private_flat_nl;
    2272             :     #pragma omp for nowait
    2273             :     for(unsigned k=0; k<hills_.size(); k++)
    2274             :     {
    2275             :       double dist2=0;
    2276             :       for(unsigned i=0; i<getNumberOfArguments(); i++)
    2277             :       {
    2278             :         const double d=difference(i,getArgument(i),hills_[k].center[i])/hills_[k].sigma[i];
    2279             :         dist2+=d*d;
    2280             :       }
    2281             :       if(dist2<=nlist_param_[0]*dp2cutoff) private_flat_nl.push_back(hills_[k]);
    2282             :     }
    2283             :     #pragma omp critical
    2284             :     local_flat_nl.insert(local_flat_nl.end(), private_flat_nl.begin(), private_flat_nl.end());
    2285             :   }
    2286           4 :   nlist_hills_ = local_flat_nl;
    2287             : 
    2288             :   // here we set some properties that are used to decide when to update it again
    2289          12 :   for(unsigned i=0; i<getNumberOfArguments(); i++) nlist_center_[i]=getArgument(i);
    2290             :   std::vector<double> dev2;
    2291           4 :   dev2.resize(getNumberOfArguments(),0);
    2292          46 :   for(unsigned k=0; k<nlist_hills_.size(); k++)
    2293             :   {
    2294         126 :     for(unsigned i=0; i<getNumberOfArguments(); i++)
    2295             :     {
    2296          84 :       const double d=difference(i,getArgument(i),nlist_hills_[k].center[i]);
    2297          84 :       dev2[i]+=d*d;
    2298             :     }
    2299             :   }
    2300          12 :   for(unsigned i=0; i<getNumberOfArguments(); i++) {
    2301           8 :     if(dev2[i]>0.) nlist_dev2_[i]=dev2[i]/static_cast<double>(nlist_hills_.size());
    2302           0 :     else nlist_dev2_[i]=hills_.back().sigma[i]*hills_.back().sigma[i];
    2303             :   }
    2304             : 
    2305             :   // we are done
    2306           4 :   getPntrToComponent("nlker")->set(nlist_hills_.size());
    2307           4 :   getPntrToComponent("nlsteps")->set(nlist_steps_);
    2308           4 :   nlist_steps_=0;
    2309           4 :   nlist_update_=false;
    2310           4 : }
    2311             : 
    2312             : }
    2313             : }

Generated by: LCOV version 1.15