LCOV - code coverage report
Current view: top level - cltools - Driver.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 492 522 94.3 %
Date: 2021-11-18 15:22:58 Functions: 9 16 56.2 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2012-2020 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 "CLTool.h"
      23             : #include "CLToolRegister.h"
      24             : #include "tools/Tools.h"
      25             : #include "core/PlumedMain.h"
      26             : #include "tools/Communicator.h"
      27             : #include "tools/Random.h"
      28             : #include "tools/Pbc.h"
      29             : #include <cstdio>
      30             : #include <cstring>
      31             : #include <vector>
      32             : #include <map>
      33             : #include <memory>
      34             : #include "tools/Units.h"
      35             : #include "tools/PDB.h"
      36             : #include "tools/FileBase.h"
      37             : #include "tools/IFile.h"
      38             : 
      39             : // when using molfile plugin
      40             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
      41             : #ifndef __PLUMED_HAS_EXTERNAL_MOLFILE_PLUGINS
      42             : /* Use the internal ones. Alternatively:
      43             :  *    ifeq (,$(findstring __PLUMED_HAS_EXTERNAL_MOLFILE_PLUGINS,$(CPPFLAGS)))
      44             :  *    CPPFLAGS+=-I../molfile
      45             :  */
      46             : #include "molfile/libmolfile_plugin.h"
      47             : #include "molfile/molfile_plugin.h"
      48             : using namespace PLMD::molfile;
      49             : #else
      50             : #include <libmolfile_plugin.h>
      51             : #include <molfile_plugin.h>
      52             : #endif
      53             : #endif
      54             : 
      55             : #ifdef __PLUMED_HAS_XDRFILE
      56             : #include <xdrfile/xdrfile_trr.h>
      57             : #include <xdrfile/xdrfile_xtc.h>
      58             : #endif
      59             : 
      60             : using namespace std;
      61             : 
      62             : namespace PLMD {
      63             : namespace cltools {
      64             : 
      65             : //+PLUMEDOC TOOLS driver-float
      66             : /*
      67             : Equivalent to \ref driver, but using single precision reals.
      68             : 
      69             : The purpose of this tool is just to test what PLUMED does when linked from
      70             : a single precision code.
      71             : 
      72             : \par Examples
      73             : 
      74             : \verbatim
      75             : plumed driver-float --plumed plumed.dat --ixyz trajectory.xyz
      76             : \endverbatim
      77             : 
      78             : See also examples in \ref driver
      79             : 
      80             : */
      81             : //+ENDPLUMEDOC
      82             : //
      83             : 
      84             : 
      85             : //+PLUMEDOC TOOLS driver
      86             : /*
      87             : driver is a tool that allows one to to use plumed to post-process an existing trajectory.
      88             : 
      89             : The input to driver is specified using the command line arguments described below.
      90             : 
      91             : In addition, you can use the special \subpage READ command inside your plumed input
      92             : to read in colvar files that were generated during your MD simulation.  The values
      93             : read in can then be treated like calculated colvars.
      94             : 
      95             : \warning
      96             : Notice that by default the driver has no knowledge about the masses and charges
      97             : of your atoms! Thus, if you want to compute quantities depending charges (e.g. \ref DHENERGY)
      98             : or masses (e.g. \ref COM) you should pass the proper information to the driver.
      99             : You can do it either with the --pdb option or with the --mc option. The latter
     100             : will read a file produced by \ref DUMPMASSCHARGE .
     101             : 
     102             : 
     103             : \par Examples
     104             : 
     105             : The following command tells plumed to post process the trajectory contained in `trajectory.xyz`
     106             :  by performing the actions described in the input file `plumed.dat`.  If an action that takes the
     107             : stride keyword is given a stride equal to \f$n\f$ then it will be performed only on every \f$n\f$th
     108             : frames in the trajectory file.
     109             : \verbatim
     110             : plumed driver --plumed plumed.dat --ixyz trajectory.xyz
     111             : \endverbatim
     112             : 
     113             : Notice that `xyz` files are expected to be in internal PLUMED units, that is by default nm.
     114             : You can change this behavior by using the `--length-units` option:
     115             : \verbatim
     116             : plumed driver --plumed plumed.dat --ixyz trajectory.xyz --length-units A
     117             : \endverbatim
     118             : The strings accepted by the `--length-units` options are the same ones accepted by the \ref UNITS action.
     119             : Other file formats typically have their default coordinates (e.g., `gro` files are always in nm)
     120             : and it thus should not be necessary to use the `--length-units` option. Additionally,
     121             : consider that the units used by the `driver` might be different by the units used in the PLUMED input
     122             : file `plumed.dat`. For instance consider the command:
     123             : \verbatim
     124             : plumed driver --plumed plumed.dat --ixyz trajectory.xyz --length-units A
     125             : \endverbatim
     126             : where `plumed.dat` is
     127             : \plumedfile
     128             : # no explicit UNITS action here
     129             : d: DISTANCE ATOMS=1,2
     130             : PRINT ARG=d FILE=colvar
     131             : \endplumedfile
     132             : In this case, the driver reads the `xyz` file assuming it to contain coordinates in Angstrom units.
     133             : However, the resulting `colvar` file contains a distance expressed in nm.
     134             : 
     135             : The following command tells plumed to post process the trajectory contained in trajectory.xyz.
     136             :  by performing the actions described in the input file plumed.dat.
     137             : \verbatim
     138             : plumed driver --plumed plumed.dat --ixyz trajectory.xyz --trajectory-stride 100 --timestep 0.001
     139             : \endverbatim
     140             : Here though
     141             : `--trajectory-stride` is set equal to the frequency with which frames were output during the trajectory
     142             : and the `--timestep` is equal to the simulation timestep.  As such the `STRIDE` parameters in the `plumed.dat`
     143             : files are referred to the original timestep and any files output resemble those that would have been generated
     144             : had we run the calculation we are running with driver when the MD simulation was running.
     145             : 
     146             : PLUMED can read xyz files (in PLUMED units) and gro files (in nm). In addition,
     147             : PLUMED includes by default support for a
     148             : subset of the trajectory file formats supported by VMD, e.g. xtc and dcd:
     149             : 
     150             : \verbatim
     151             : plumed driver --plumed plumed.dat --pdb diala.pdb --mf_xtc traj.xtc --trajectory-stride 100 --timestep 0.001
     152             : \endverbatim
     153             : 
     154             : where `--mf_` prefixes the extension of one of the accepted molfile plugin format.
     155             : If PLUMED has been \ref Installation "installed" with full molfile support, other formats will be available.
     156             : Just type `plumed driver --help` to see which plugins are available.
     157             : 
     158             : Molfile plugin require periodic cell to be triangular (i.e. first vector oriented along x and
     159             : second vector in xy plane). This is true for many MD codes. However, it could be false
     160             : if you rotate the coordinates in your trajectory before reading them in the driver.
     161             : Also notice that some formats (e.g. amber crd) do not specify atom number. In this case you can use
     162             : the `--natoms` option:
     163             : \verbatim
     164             : plumed driver --plumed plumed.dat --imf_crd trajectory.crd --natoms 128
     165             : \endverbatim
     166             : 
     167             : Check the available molfile plugins and limitations at [this link](http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/).
     168             : 
     169             : Additionally, you can use the xdrfile implementation of xtc and trr. To this aim, just
     170             : download and install properly the xdrfile library (see [this link](http://www.gromacs.org/Developer_Zone/Programming_Guide/XTC_Library)).
     171             : If the xdrfile library is installed properly the PLUMED configure script should be able to
     172             : detect it and enable it.
     173             : Notice that the xdrfile implementation of xtc and trr
     174             : is more robust than the molfile one, since it provides support for generic cell shapes.
     175             : In addition, it allows \ref DUMPATOMS to write compressed xtc files.
     176             : 
     177             : 
     178             : */
     179             : //+ENDPLUMEDOC
     180             : //
     181             : 
     182             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     183        5517 : static vector<molfile_plugin_t *> plugins;
     184        5517 : static map <string, unsigned> pluginmap;
     185       33102 : static int register_cb(void *v, vmdplugin_t *p) {
     186             :   //const char *key = p->name;
     187       99306 :   const auto ret = pluginmap.insert ( std::pair<string,unsigned>(string(p->name),plugins.size()) );
     188       33102 :   if (ret.second==false) {
     189             :     //cerr<<"MOLFILE: found duplicate plugin for "<<key<<" : not inserted "<<endl;
     190             :   } else {
     191             :     //cerr<<"MOLFILE: loading plugin "<<key<<" number "<<plugins.size()-1<<endl;
     192       66204 :     plugins.push_back(reinterpret_cast<molfile_plugin_t *>(p));
     193             :   }
     194       33102 :   return VMDPLUGIN_SUCCESS;
     195             : }
     196             : #endif
     197             : 
     198             : template<typename real>
     199         579 : class Driver : public CLTool {
     200             : public:
     201             :   static void registerKeywords( Keywords& keys );
     202             :   explicit Driver(const CLToolOptions& co );
     203             :   int main(FILE* in,FILE*out,Communicator& pc);
     204             :   void evaluateNumericalDerivatives( const long int& step, PlumedMain& p, const std::vector<real>& coordinates,
     205             :                                      const std::vector<real>& masses, const std::vector<real>& charges,
     206             :                                      std::vector<real>& cell, const double& base, std::vector<real>& numder );
     207             :   string description()const;
     208             : };
     209             : 
     210             : template<typename real>
     211        3678 : void Driver<real>::registerKeywords( Keywords& keys ) {
     212        3678 :   CLTool::registerKeywords( keys ); keys.isDriver();
     213       11034 :   keys.addFlag("--help-debug",false,"print special options that can be used to create regtests");
     214       18390 :   keys.add("compulsory","--plumed","plumed.dat","specify the name of the plumed input file");
     215       18390 :   keys.add("compulsory","--timestep","1.0","the timestep that was used in the calculation that produced this trajectory in picoseconds");
     216       18390 :   keys.add("compulsory","--trajectory-stride","1","the frequency with which frames were output to this trajectory during the simulation"
     217             : #ifdef __PLUMED_HAS_XDRFILE
     218             :            " (0 means that the number of the step is read from the trajectory file,"
     219             :            " currently working only for xtc/trr files read with --ixtc/--trr)"
     220             : #endif
     221             :           );
     222       18390 :   keys.add("compulsory","--multi","0","set number of replicas for multi environment (needs MPI)");
     223       11034 :   keys.addFlag("--noatoms",false,"don't read in a trajectory.  Just use colvar files as specified in plumed.dat");
     224       11034 :   keys.addFlag("--parse-only",false,"read the plumed input file and stop");
     225       14712 :   keys.add("atoms","--ixyz","the trajectory in xyz format");
     226       14712 :   keys.add("atoms","--igro","the trajectory in gro format");
     227             : #ifdef __PLUMED_HAS_XDRFILE
     228       14712 :   keys.add("atoms","--ixtc","the trajectory in xtc format (xdrfile implementation)");
     229       14712 :   keys.add("atoms","--itrr","the trajectory in trr format (xdrfile implementation)");
     230             : #endif
     231       14712 :   keys.add("optional","--length-units","units for length, either as a string or a number");
     232       14712 :   keys.add("optional","--mass-units","units for mass in pdb and mc file, either as a string or a number");
     233       14712 :   keys.add("optional","--charge-units","units for charge in pdb and mc file, either as a string or a number");
     234       14712 :   keys.add("optional","--kt","set \\f$k_B T\\f$, it will not be necessary to specify temperature in input file");
     235       14712 :   keys.add("optional","--dump-forces","dump the forces on a file");
     236       14712 :   keys.add("optional","--dump-forces-fmt","( default=%%f ) the format to use to dump the forces");
     237       11034 :   keys.addFlag("--dump-full-virial",false,"with --dump-forces, it dumps the 9 components of the virial");
     238       14712 :   keys.add("optional","--pdb","provides a pdb with masses and charges");
     239       14712 :   keys.add("optional","--mc","provides a file with masses and charges as produced with DUMPMASSCHARGE");
     240       14712 :   keys.add("optional","--box","comma-separated box dimensions (3 for orthorhombic, 9 for generic)");
     241       14712 :   keys.add("optional","--natoms","provides number of atoms - only used if file format does not contain number of atoms");
     242       14712 :   keys.add("optional","--initial-step","provides a number for the initial step, default is 0");
     243       14712 :   keys.add("optional","--debug-forces","output a file containing the forces due to the bias evaluated using numerical derivatives "
     244             :            "and using the analytical derivatives implemented in plumed");
     245       14712 :   keys.add("hidden","--debug-float","[yes/no] turns on the single precision version (to check float interface)");
     246       14712 :   keys.add("hidden","--debug-dd","[yes/no] use a fake domain decomposition");
     247       14712 :   keys.add("hidden","--debug-pd","[yes/no] use a fake particle decomposition");
     248       14712 :   keys.add("hidden","--debug-grex","use a fake gromacs-like replica exchange, specify exchange stride");
     249       14712 :   keys.add("hidden","--debug-grex-log","log file for debug=grex");
     250             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     251        3678 :   MOLFILE_INIT_ALL
     252        3678 :   MOLFILE_REGISTER_ALL(NULL, register_cb)
     253      106662 :   for(unsigned i=0; i<plugins.size(); i++) {
     254       66204 :     string kk="--mf_"+string(plugins[i]->name);
     255       99306 :     string mm=" molfile: the trajectory in "+string(plugins[i]->name)+" format " ;
     256       66204 :     keys.add("atoms",kk,mm);
     257             :   }
     258             : #endif
     259        3678 : }
     260             : template<typename real>
     261         579 : Driver<real>::Driver(const CLToolOptions& co ):
     262         579 :   CLTool(co)
     263             : {
     264         579 :   inputdata=commandline;
     265         579 : }
     266             : template<typename real>
     267           0 : string Driver<real>::description()const { return "analyze trajectories with plumed"; }
     268             : 
     269             : template<typename real>
     270         579 : int Driver<real>::main(FILE* in,FILE*out,Communicator& pc) {
     271             : 
     272        1158 :   Units units;
     273        1158 :   PDB pdb;
     274             : 
     275             : // Parse everything
     276        1158 :   bool printhelpdebug; parseFlag("--help-debug",printhelpdebug);
     277         579 :   if( printhelpdebug ) {
     278             :     fprintf(out,"%s",
     279             :             "Additional options for debug (only to be used in regtest):\n"
     280             :             "  [--debug-float yes]     : turns on the single precision version (to check float interface)\n"
     281             :             "  [--debug-dd yes]        : use a fake domain decomposition\n"
     282             :             "  [--debug-pd yes]        : use a fake particle decomposition\n"
     283             :            );
     284             :     return 0;
     285             :   }
     286             :   // Are we reading trajectory data
     287        1158 :   bool noatoms; parseFlag("--noatoms",noatoms);
     288        1158 :   bool parseOnly; parseFlag("--parse-only",parseOnly);
     289             : 
     290             :   std::string fakein;
     291             :   bool debug_float=false;
     292             :   fakein="";
     293        1158 :   if(parse("--debug-float",fakein)) {
     294           0 :     if(fakein=="yes") debug_float=true;
     295           0 :     else if(fakein=="no") debug_float=false;
     296           0 :     else error("--debug-float should have argument yes or no");
     297             :   }
     298             : 
     299             :   if(debug_float && sizeof(real)!=sizeof(float)) {
     300           0 :     auto cl=cltoolRegister().create(CLToolOptions("driver-float"));
     301             :     cl->setInputData(this->getInputData());
     302           0 :     int ret=cl->main(in,out,pc);
     303             :     return ret;
     304             :   }
     305             : 
     306             :   bool debug_pd=false;
     307             :   fakein="";
     308        1158 :   if(parse("--debug-pd",fakein)) {
     309          12 :     if(fakein=="yes") debug_pd=true;
     310           0 :     else if(fakein=="no") debug_pd=false;
     311           0 :     else error("--debug-pd should have argument yes or no");
     312             :   }
     313             :   if(debug_pd) fprintf(out,"DEBUGGING PARTICLE DECOMPOSITION\n");
     314             : 
     315             :   bool debug_dd=false;
     316             :   fakein="";
     317        1158 :   if(parse("--debug-dd",fakein)) {
     318          58 :     if(fakein=="yes") debug_dd=true;
     319           0 :     else if(fakein=="no") debug_dd=false;
     320           0 :     else error("--debug-dd should have argument yes or no");
     321             :   }
     322             :   if(debug_dd) fprintf(out,"DEBUGGING DOMAIN DECOMPOSITION\n");
     323             : 
     324         579 :   if( debug_pd || debug_dd ) {
     325          70 :     if(noatoms) error("cannot debug without atoms");
     326             :   }
     327             : 
     328             : // set up for multi replica driver:
     329         579 :   int multi=0;
     330        1158 :   parse("--multi",multi);
     331        1158 :   Communicator intracomm;
     332        1158 :   Communicator intercomm;
     333         579 :   if(multi) {
     334         150 :     int ntot=pc.Get_size();
     335         150 :     int nintra=ntot/multi;
     336         150 :     if(multi*nintra!=ntot) error("invalid number of processes for multi environment");
     337         150 :     pc.Split(pc.Get_rank()/nintra,pc.Get_rank(),intracomm);
     338         150 :     pc.Split(pc.Get_rank()%nintra,pc.Get_rank(),intercomm);
     339             :   } else {
     340         429 :     intracomm.Set_comm(pc.Get_comm());
     341             :   }
     342             : 
     343             : // set up for debug replica exchange:
     344        1158 :   bool debug_grex=parse("--debug-grex",fakein);
     345         579 :   int  grex_stride=0;
     346             :   FILE*grex_log=NULL;
     347         579 :   if(debug_grex) {
     348          30 :     if(noatoms) error("must have atoms to debug_grex");
     349          30 :     if(multi<2)  error("--debug_grex needs --multi with at least two replicas");
     350          30 :     Tools::convert(fakein,grex_stride);
     351          30 :     string n; Tools::convert(intercomm.Get_rank(),n);
     352             :     string file;
     353          60 :     parse("--debug-grex-log",file);
     354          30 :     if(file.length()>0) {
     355          60 :       file+="."+n;
     356          30 :       grex_log=fopen(file.c_str(),"w");
     357             :     }
     358             :   }
     359             : 
     360             : // Read the plumed input file name
     361        1158 :   string plumedFile; parse("--plumed",plumedFile);
     362             : // the timestep
     363        1158 :   double t; parse("--timestep",t);
     364         579 :   real timestep=real(t);
     365             : // the stride
     366        1158 :   unsigned stride; parse("--trajectory-stride",stride);
     367             : // are we writing forces
     368         579 :   string dumpforces(""), debugforces(""), dumpforcesFmt("%f");;
     369         579 :   bool dumpfullvirial=false;
     370         579 :   if(!noatoms) {
     371        1076 :     parse("--dump-forces",dumpforces);
     372        1076 :     parse("--debug-forces",debugforces);
     373             :   }
     374        1167 :   if(dumpforces!="" || debugforces!="" ) parse("--dump-forces-fmt",dumpforcesFmt);
     375         938 :   if(dumpforces!="") parseFlag("--dump-full-virial",dumpfullvirial);
     376         579 :   if( debugforces!="" && (debug_dd || debug_pd) ) error("cannot debug forces and domain/particle decomposition at same time");
     377           0 :   if( debugforces!="" && sizeof(real)!=sizeof(double) ) error("cannot debug forces in single precision mode");
     378             : 
     379         579 :   real kt=-1.0;
     380        1158 :   parse("--kt",kt);
     381             :   string trajectory_fmt;
     382             : 
     383             :   bool use_molfile=false;
     384             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     385             :   molfile_plugin_t *api=NULL;
     386             :   void *h_in=NULL;
     387             :   molfile_timestep_t ts_in; // this is the structure that has the timestep
     388             : // a std::unique_ptr<float> with the same scope as ts_in
     389             : // it is necessary in order to store the pointer to ts_in.coords
     390             :   std::unique_ptr<float[]> ts_in_coords;
     391         579 :   ts_in.coords=ts_in_coords.get();
     392         579 :   ts_in.velocities=NULL;
     393         579 :   ts_in.A=-1; // we use this to check whether cell is provided or not
     394             : #endif
     395             : 
     396             : // Read in an xyz file
     397         579 :   string trajectoryFile(""), pdbfile(""), mcfile("");
     398         579 :   bool pbc_cli_given=false; vector<double> pbc_cli_box(9,0.0);
     399         579 :   int command_line_natoms=-1;
     400             : 
     401         579 :   if(!noatoms) {
     402        1076 :     std::string traj_xyz; parse("--ixyz",traj_xyz);
     403        1076 :     std::string traj_gro; parse("--igro",traj_gro);
     404             :     std::string traj_xtc;
     405             :     std::string traj_trr;
     406             : #ifdef __PLUMED_HAS_XDRFILE
     407        1076 :     parse("--ixtc",traj_xtc);
     408        1076 :     parse("--itrr",traj_trr);
     409             : #endif
     410             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     411       15602 :     for(unsigned i=0; i<plugins.size(); i++) {
     412        9684 :       string molfile_key="--mf_"+string(plugins[i]->name);
     413             :       string traj_molfile;
     414        4842 :       parse(molfile_key,traj_molfile);
     415        4842 :       if(traj_molfile.length()>0) {
     416          72 :         fprintf(out,"\nDRIVER: Found molfile format trajectory %s with name %s\n",plugins[i]->name,traj_molfile.c_str());
     417             :         trajectoryFile=traj_molfile;
     418         144 :         trajectory_fmt=string(plugins[i]->name);
     419             :         use_molfile=true;
     420          72 :         api = plugins[i];
     421             :       }
     422             :     }
     423             : #endif
     424             :     { // check that only one fmt is specified
     425             :       int nn=0;
     426         538 :       if(traj_xyz.length()>0) nn++;
     427         538 :       if(traj_gro.length()>0) nn++;
     428         538 :       if(traj_xtc.length()>0) nn++;
     429         538 :       if(traj_trr.length()>0) nn++;
     430         538 :       if(nn>1) {
     431           0 :         fprintf(stderr,"ERROR: cannot provide more than one trajectory file\n");
     432           0 :         if(grex_log)fclose(grex_log);
     433             :         return 1;
     434             :       }
     435             :     }
     436         899 :     if(traj_xyz.length()>0 && trajectoryFile.length()==0) {
     437             :       trajectoryFile=traj_xyz;
     438             :       trajectory_fmt="xyz";
     439             :     }
     440         638 :     if(traj_gro.length()>0 && trajectoryFile.length()==0) {
     441             :       trajectoryFile=traj_gro;
     442             :       trajectory_fmt="gro";
     443             :     }
     444         540 :     if(traj_xtc.length()>0 && trajectoryFile.length()==0) {
     445             :       trajectoryFile=traj_xtc;
     446             :       trajectory_fmt="xdr-xtc";
     447             :     }
     448         541 :     if(traj_trr.length()>0 && trajectoryFile.length()==0) {
     449             :       trajectoryFile=traj_trr;
     450             :       trajectory_fmt="xdr-trr";
     451             :     }
     452         538 :     if(trajectoryFile.length()==0&&!parseOnly) {
     453           0 :       fprintf(stderr,"ERROR: missing trajectory data\n");
     454           0 :       if(grex_log)fclose(grex_log);
     455             :       return 1;
     456             :     }
     457        1614 :     string lengthUnits(""); parse("--length-units",lengthUnits);
     458         538 :     if(lengthUnits.length()>0) units.setLength(lengthUnits);
     459        1076 :     string chargeUnits(""); parse("--charge-units",chargeUnits);
     460         538 :     if(chargeUnits.length()>0) units.setCharge(chargeUnits);
     461        1076 :     string massUnits(""); parse("--mass-units",massUnits);
     462         538 :     if(massUnits.length()>0) units.setMass(massUnits);
     463             : 
     464        1076 :     parse("--pdb",pdbfile);
     465         538 :     if(pdbfile.length()>0) {
     466          69 :       bool check=pdb.read(pdbfile,false,1.0);
     467          69 :       if(!check) error("error reading pdb file");
     468             :     }
     469             : 
     470        1076 :     parse("--mc",mcfile);
     471             : 
     472        1076 :     string pbc_cli_list; parse("--box",pbc_cli_list);
     473         538 :     if(pbc_cli_list.length()>0) {
     474             :       pbc_cli_given=true;
     475          36 :       vector<string> words=Tools::getWords(pbc_cli_list,",");
     476          18 :       if(words.size()==3) {
     477         180 :         for(int i=0; i<3; i++) sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[4*i]));
     478           0 :       } else if(words.size()==9) {
     479           0 :         for(int i=0; i<9; i++) sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[i]));
     480             :       } else {
     481           0 :         string msg="ERROR: cannot parse command-line box "+pbc_cli_list;
     482           0 :         fprintf(stderr,"%s\n",msg.c_str());
     483             :         return 1;
     484             :       }
     485             : 
     486             :     }
     487             : 
     488        1076 :     parse("--natoms",command_line_natoms);
     489             : 
     490             :   }
     491             : 
     492             : 
     493         579 :   if(debug_dd && debug_pd) error("cannot use debug-dd and debug-pd at the same time");
     494         579 :   if(debug_pd || debug_dd) {
     495          70 :     if( !Communicator::initialized() ) error("needs mpi for debug-pd");
     496             :   }
     497             : 
     498        1158 :   PlumedMain p;
     499         579 :   int rr=sizeof(real);
     500        1158 :   p.cmd("setRealPrecision",&rr);
     501             :   int checknatoms=-1;
     502         579 :   long int step=0;
     503        1158 :   parse("--initial-step",step);
     504             : 
     505         579 :   if(Communicator::initialized()) {
     506         246 :     if(multi) {
     507         252 :       if(intracomm.Get_rank()==0) p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm());
     508         300 :       p.cmd("GREX setMPIIntracomm",&intracomm.Get_comm());
     509         300 :       p.cmd("GREX init");
     510             :     }
     511         492 :     p.cmd("setMPIComm",&intracomm.Get_comm());
     512             :   }
     513        1158 :   p.cmd("setMDLengthUnits",&units.getLength());
     514        1158 :   p.cmd("setMDChargeUnits",&units.getCharge());
     515        1158 :   p.cmd("setMDMassUnits",&units.getMass());
     516        1158 :   p.cmd("setMDEngine","driver");
     517        1158 :   p.cmd("setTimestep",&timestep);
     518        1158 :   p.cmd("setPlumedDat",plumedFile.c_str());
     519        1158 :   p.cmd("setLog",out);
     520             : 
     521             :   int natoms;
     522             : 
     523         579 :   if(parseOnly) {
     524           0 :     if(command_line_natoms<0) error("--parseOnly requires setting the number of atoms with --natoms");
     525           0 :     natoms=command_line_natoms;
     526             :   }
     527             : 
     528             : 
     529        1158 :   FILE* fp=NULL; FILE* fp_forces=NULL; OFile fp_dforces;
     530             : #ifdef __PLUMED_HAS_XDRFILE
     531             :   XDRFILE* xd=NULL;
     532             : #endif
     533         579 :   if(!noatoms&&!parseOnly) {
     534         538 :     if (trajectoryFile=="-")
     535             :       fp=in;
     536             :     else {
     537         538 :       if(multi) {
     538             :         string n;
     539         150 :         Tools::convert(intercomm.Get_rank(),n);
     540         300 :         std::string testfile=FileBase::appendSuffix(trajectoryFile,"."+n);
     541         150 :         FILE* tmp_fp=fopen(testfile.c_str(),"r");
     542         150 :         if(tmp_fp) { fclose(tmp_fp); trajectoryFile=testfile.c_str();}
     543             :       }
     544         538 :       if(use_molfile==true) {
     545             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     546         144 :         h_in = api->open_file_read(trajectoryFile.c_str(), trajectory_fmt.c_str(), &natoms);
     547          72 :         if(natoms==MOLFILE_NUMATOMS_UNKNOWN) {
     548           2 :           if(command_line_natoms>=0) natoms=command_line_natoms;
     549           0 :           else error("this file format does not provide number of atoms; use --natoms on the command line");
     550             :         }
     551          72 :         ts_in_coords.reset(new float [3*natoms]);
     552          72 :         ts_in.coords = ts_in_coords.get();
     553             : #endif
     554         930 :       } else if(trajectory_fmt=="xdr-xtc" || trajectory_fmt=="xdr-trr") {
     555             : #ifdef __PLUMED_HAS_XDRFILE
     556           5 :         xd=xdrfile_open(trajectoryFile.c_str(),"r");
     557           5 :         if(!xd) {
     558           0 :           string msg="ERROR: Error opening trajectory file "+trajectoryFile;
     559           0 :           fprintf(stderr,"%s\n",msg.c_str());
     560             :           return 1;
     561             :         }
     562           7 :         if(trajectory_fmt=="xdr-xtc") read_xtc_natoms(&trajectoryFile[0],&natoms);
     563           8 :         if(trajectory_fmt=="xdr-trr") read_trr_natoms(&trajectoryFile[0],&natoms);
     564             : #endif
     565             :       } else {
     566         461 :         fp=fopen(trajectoryFile.c_str(),"r");
     567         461 :         if(!fp) {
     568           0 :           string msg="ERROR: Error opening trajectory file "+trajectoryFile;
     569           0 :           fprintf(stderr,"%s\n",msg.c_str());
     570             :           return 1;
     571             :         }
     572             :       }
     573             :     }
     574         538 :     if(dumpforces.length()>0) {
     575         359 :       if(Communicator::initialized() && pc.Get_size()>1) {
     576             :         string n;
     577         186 :         Tools::convert(pc.Get_rank(),n);
     578         372 :         dumpforces+="."+n;
     579             :       }
     580         359 :       fp_forces=fopen(dumpforces.c_str(),"w");
     581             :     }
     582         538 :     if(debugforces.length()>0) {
     583          10 :       if(Communicator::initialized() && pc.Get_size()>1) {
     584             :         string n;
     585           6 :         Tools::convert(pc.Get_rank(),n);
     586          12 :         debugforces+="."+n;
     587             :       }
     588          10 :       fp_dforces.open(debugforces);
     589             :     }
     590             :   }
     591             : 
     592             :   std::string line;
     593             :   std::vector<real> coordinates;
     594             :   std::vector<real> forces;
     595             :   std::vector<real> masses;
     596             :   std::vector<real> charges;
     597             :   std::vector<real> cell;
     598             :   std::vector<real> virial;
     599             :   std::vector<real> numder;
     600             : 
     601             : // variables to test particle decomposition
     602             :   int pd_nlocal;
     603             :   int pd_start;
     604             : // variables to test random decomposition (=domain decomposition)
     605             :   std::vector<int>  dd_gatindex;
     606             :   std::vector<int>  dd_g2l;
     607             :   std::vector<real> dd_masses;
     608             :   std::vector<real> dd_charges;
     609             :   std::vector<real> dd_forces;
     610             :   std::vector<real> dd_coordinates;
     611             :   int dd_nlocal;
     612             : // random stream to choose decompositions
     613         579 :   Random rnd;
     614             : 
     615       31770 :   while(true) {
     616       32349 :     if(!noatoms&&!parseOnly) {
     617       30022 :       if(use_molfile==true) {
     618             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     619             :         int rc;
     620        6515 :         rc = api->read_next_timestep(h_in, natoms, &ts_in);
     621        6515 :         if(rc==MOLFILE_EOF) {
     622             :           break;
     623             :         }
     624             : #endif
     625       25689 :       } else if(trajectory_fmt=="xyz" || trajectory_fmt=="gro") {
     626       23438 :         if(!Tools::getline(fp,line)) break;
     627             :       }
     628             :     }
     629             : 
     630             :     bool first_step=false;
     631       31820 :     if(!noatoms&&!parseOnly) {
     632       54628 :       if(use_molfile==false && (trajectory_fmt=="xyz" || trajectory_fmt=="gro")) {
     633       22981 :         if(trajectory_fmt=="gro") if(!Tools::getline(fp,line)) error("premature end of trajectory file");
     634       22981 :         sscanf(line.c_str(),"%100d",&natoms);
     635             :       }
     636             :     }
     637       31820 :     if(checknatoms<0 && !noatoms) {
     638         538 :       pd_nlocal=natoms;
     639         538 :       pd_start=0;
     640             :       first_step=true;
     641        1076 :       masses.assign(natoms,std::numeric_limits<real>::quiet_NaN());
     642        1076 :       charges.assign(natoms,std::numeric_limits<real>::quiet_NaN());
     643             : //case pdb: structure
     644         538 :       if(pdbfile.length()>0) {
     645       13449 :         for(unsigned i=0; i<pdb.size(); ++i) {
     646       13380 :           AtomNumber an=pdb.getAtomNumbers()[i];
     647             :           unsigned index=an.index();
     648        6690 :           if( index>=unsigned(natoms) ) error("atom index in pdb exceeds the number of atoms in trajectory");
     649       20070 :           masses[index]=pdb.getOccupancy()[i];
     650       13380 :           charges[index]=pdb.getBeta()[i];
     651             :         }
     652             :       }
     653         538 :       if(mcfile.length()>0) {
     654          10 :         IFile ifile;
     655           5 :         ifile.open(mcfile);
     656             :         int index; double mass; double charge;
     657        2840 :         while(ifile.scanField("index",index).scanField("mass",mass).scanField("charge",charge).scanField()) {
     658        1128 :           masses[index]=mass;
     659        1128 :           charges[index]=charge;
     660             :         }
     661             :       }
     662       31282 :     } else if( checknatoms<0 && noatoms ) {
     663          41 :       natoms=0;
     664             :     }
     665       31820 :     if( checknatoms<0 ) {
     666         579 :       if(kt>=0) {
     667           2 :         p.cmd("setKbT",&kt);
     668             :       }
     669         579 :       checknatoms=natoms;
     670        1158 :       p.cmd("setNatoms",&natoms);
     671        1158 :       p.cmd("init");
     672         579 :       if(parseOnly) break;
     673             :     }
     674       31820 :     if(checknatoms!=natoms) {
     675           0 :       std::string stepstr; Tools::convert(step,stepstr);
     676           0 :       error("number of atoms in frame " + stepstr + " does not match number of atoms in first frame");
     677             :     }
     678             : 
     679       63640 :     coordinates.assign(3*natoms,real(0.0));
     680       63640 :     forces.assign(3*natoms,real(0.0));
     681       63640 :     cell.assign(9,real(0.0));
     682       63640 :     virial.assign(9,real(0.0));
     683             : 
     684       31820 :     if( first_step || rnd.U01()>0.5) {
     685       16603 :       if(debug_pd) {
     686         152 :         int npe=intracomm.Get_size();
     687         152 :         vector<int> loc(npe,0);
     688         152 :         vector<int> start(npe,0);
     689        1064 :         for(int i=0; i<npe-1; i++) {
     690         456 :           int cc=(natoms*2*rnd.U01())/npe;
     691         912 :           if(start[i]+cc>natoms) cc=natoms-start[i];
     692         456 :           loc[i]=cc;
     693        1368 :           start[i+1]=start[i]+loc[i];
     694             :         }
     695         456 :         loc[npe-1]=natoms-start[npe-1];
     696         152 :         intracomm.Bcast(loc,0);
     697         152 :         intracomm.Bcast(start,0);
     698         304 :         pd_nlocal=loc[intracomm.Get_rank()];
     699         304 :         pd_start=start[intracomm.Get_rank()];
     700         152 :         if(intracomm.Get_rank()==0) {
     701             :           fprintf(out,"\nDRIVER: Reassigning particle decomposition\n");
     702         494 :           fprintf(out,"DRIVER: "); for(int i=0; i<npe; i++) fprintf(out,"%d ",loc[i]); printf("\n");
     703         494 :           fprintf(out,"DRIVER: "); for(int i=0; i<npe; i++) fprintf(out,"%d ",start[i]); printf("\n");
     704             :         }
     705         304 :         p.cmd("setAtomsNlocal",&pd_nlocal);
     706         304 :         p.cmd("setAtomsContiguous",&pd_start);
     707       16451 :       } else if(debug_dd) {
     708         946 :         int npe=intracomm.Get_size();
     709         946 :         int rank=intracomm.Get_rank();
     710        1892 :         dd_charges.assign(natoms,0.0);
     711        1892 :         dd_masses.assign(natoms,0.0);
     712        1892 :         dd_gatindex.assign(natoms,-1);
     713        1892 :         dd_g2l.assign(natoms,-1);
     714        1892 :         dd_coordinates.assign(3*natoms,0.0);
     715        1892 :         dd_forces.assign(3*natoms,0.0);
     716         946 :         dd_nlocal=0;
     717      103966 :         for(int i=0; i<natoms; ++i) {
     718       51510 :           double r=rnd.U01()*npe;
     719      110396 :           int n; for(n=0; n<npe; n++) if(n+1>r)break;
     720       51510 :           plumed_assert(n<npe);
     721       51510 :           if(n==rank) {
     722       38334 :             dd_gatindex[dd_nlocal]=i;
     723       38334 :             dd_g2l[i]=dd_nlocal;
     724       38334 :             dd_charges[dd_nlocal]=charges[i];
     725       38334 :             dd_masses[dd_nlocal]=masses[i];
     726       19167 :             dd_nlocal++;
     727             :           }
     728             :         }
     729         946 :         if(intracomm.Get_rank()==0) {
     730             :           fprintf(out,"\nDRIVER: Reassigning domain decomposition\n");
     731             :         }
     732        1892 :         p.cmd("setAtomsNlocal",&dd_nlocal);
     733        1892 :         p.cmd("setAtomsGatindex",&dd_gatindex[0]);
     734             :       }
     735             :     }
     736             : 
     737       31820 :     int plumedStopCondition=0;
     738       31820 :     if(!noatoms) {
     739       29493 :       if(use_molfile) {
     740             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     741        6443 :         if(pbc_cli_given==false) {
     742        6440 :           if(ts_in.A>0.0) { // this is negative if molfile does not provide box
     743             :             // info on the cell: convert using pbcset.tcl from pbctools in vmd distribution
     744        6437 :             real cosBC=cos(ts_in.alpha*pi/180.);
     745             :             //double sinBC=sin(ts_in.alpha*pi/180.);
     746        6437 :             real cosAC=cos(ts_in.beta*pi/180.);
     747        6437 :             real cosAB=cos(ts_in.gamma*pi/180.);
     748        6437 :             real sinAB=sin(ts_in.gamma*pi/180.);
     749        6437 :             real Ax=ts_in.A;
     750        6437 :             real Bx=ts_in.B*cosAB;
     751        6437 :             real By=ts_in.B*sinAB;
     752        6437 :             real Cx=ts_in.C*cosAC;
     753        6437 :             real Cy=(ts_in.C*ts_in.B*cosBC-Cx*Bx)/By;
     754        6437 :             real Cz=sqrt(ts_in.C*ts_in.C-Cx*Cx-Cy*Cy);
     755       12874 :             cell[0]=Ax/10.; cell[1]=0.; cell[2]=0.;
     756        6437 :             cell[3]=Bx/10.; cell[4]=By/10.; cell[5]=0.;
     757        6437 :             cell[6]=Cx/10.; cell[7]=Cy/10.; cell[8]=Cz/10.;
     758             :           } else {
     759           6 :             cell[0]=0.0; cell[1]=0.0; cell[2]=0.0;
     760           3 :             cell[3]=0.0; cell[4]=0.0; cell[5]=0.0;
     761           3 :             cell[6]=0.0; cell[7]=0.0; cell[8]=0.0;
     762             :           }
     763             :         } else {
     764          57 :           for(unsigned i=0; i<9; i++)cell[i]=pbc_cli_box[i];
     765             :         }
     766             :         // info on coords
     767             :         // the order is xyzxyz...
     768     6536861 :         for(int i=0; i<3*natoms; i++) {
     769     6530418 :           coordinates[i]=real(ts_in.coords[i]/10.); //convert to nm
     770             :           //cerr<<"COOR "<<coordinates[i]<<endl;
     771             :         }
     772             : #endif
     773       46070 :       } else if(trajectory_fmt=="xdr-xtc" || trajectory_fmt=="xdr-trr") {
     774             : #ifdef __PLUMED_HAS_XDRFILE
     775             :         int localstep;
     776             :         float time;
     777             :         matrix box;
     778          69 :         std::unique_ptr<rvec[]> pos(new rvec[natoms]);
     779             :         float prec,lambda;
     780             :         int ret=exdrOK;
     781          69 :         if(trajectory_fmt=="xdr-xtc") ret=read_xtc(xd,natoms,&localstep,&time,box,pos.get(),&prec);
     782          69 :         if(trajectory_fmt=="xdr-trr") ret=read_trr(xd,natoms,&localstep,&time,&lambda,box,pos.get(),NULL,NULL);
     783          69 :         if(stride==0) step=localstep;
     784          69 :         if(ret==exdrENDOFFILE) break;
     785          67 :         if(ret!=exdrOK) break;
     786         832 :         for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) cell[3*i+j]=box[i][j];
     787       10976 :         for(int i=0; i<natoms; i++) for(unsigned j=0; j<3; j++)
     788       24552 :             coordinates[3*i+j]=real(pos[i][j]);
     789             : #endif
     790             :       } else {
     791       22981 :         if(trajectory_fmt=="xyz") {
     792       20965 :           if(!Tools::getline(fp,line)) error("premature end of trajectory file");
     793             : 
     794       20965 :           std::vector<double> celld(9,0.0);
     795       20965 :           if(pbc_cli_given==false) {
     796       20759 :             std::vector<std::string> words;
     797       41518 :             words=Tools::getWords(line);
     798       20759 :             if(words.size()==3) {
     799       20186 :               sscanf(line.c_str(),"%100lf %100lf %100lf",&celld[0],&celld[4],&celld[8]);
     800         573 :             } else if(words.size()==9) {
     801         573 :               sscanf(line.c_str(),"%100lf %100lf %100lf %100lf %100lf %100lf %100lf %100lf %100lf",
     802             :                      &celld[0], &celld[1], &celld[2],
     803             :                      &celld[3], &celld[4], &celld[5],
     804             :                      &celld[6], &celld[7], &celld[8]);
     805           0 :             } else error("needed box in second line of xyz file");
     806             :           } else {                      // from command line
     807         206 :             celld=pbc_cli_box;
     808             :           }
     809      398335 :           for(unsigned i=0; i<9; i++)cell[i]=real(celld[i]);
     810             :         }
     811             :         int ddist=0;
     812             :         // Read coordinates
     813     3459651 :         for(int i=0; i<natoms; i++) {
     814     1718335 :           bool ok=Tools::getline(fp,line);
     815     1718335 :           if(!ok) error("premature end of trajectory file");
     816             :           double cc[3];
     817     1718335 :           if(trajectory_fmt=="xyz") {
     818             :             char dummy[1000];
     819     1642749 :             int ret=std::sscanf(line.c_str(),"%999s %100lf %100lf %100lf",dummy,&cc[0],&cc[1],&cc[2]);
     820     1642749 :             if(ret!=4) error("cannot read line"+line);
     821       75586 :           } else if(trajectory_fmt=="gro") {
     822             :             // do the gromacs way
     823       75586 :             if(!i) {
     824             :               //
     825             :               // calculate the distance between dots (as in gromacs gmxlib/confio.c, routine get_w_conf )
     826             :               //
     827             :               const char      *p1, *p2, *p3;
     828             :               p1 = strchr(line.c_str(), '.');
     829        2016 :               if (p1 == NULL) error("seems there are no coordinates in the gro file");
     830        2016 :               p2 = strchr(&p1[1], '.');
     831        2016 :               if (p2 == NULL) error("seems there is only one coordinates in the gro file");
     832        2016 :               ddist = p2 - p1;
     833        2016 :               p3 = strchr(&p2[1], '.');
     834        2016 :               if (p3 == NULL)error("seems there are only two coordinates in the gro file");
     835        2016 :               if (p3 - p2 != ddist)error("not uniform spacing in fields in the gro file");
     836             :             }
     837      151172 :             Tools::convert(line.substr(20,ddist),cc[0]);
     838      151172 :             Tools::convert(line.substr(20+ddist,ddist),cc[1]);
     839      151172 :             Tools::convert(line.substr(20+ddist+ddist,ddist),cc[2]);
     840           0 :           } else plumed_error();
     841     1718335 :           if(!debug_pd || ( i>=pd_start && i<pd_start+pd_nlocal) ) {
     842     3397790 :             coordinates[3*i]=real(cc[0]);
     843     3397790 :             coordinates[3*i+1]=real(cc[1]);
     844     3397790 :             coordinates[3*i+2]=real(cc[2]);
     845             :           }
     846             :         }
     847       22981 :         if(trajectory_fmt=="gro") {
     848        2016 :           if(!Tools::getline(fp,line)) error("premature end of trajectory file");
     849        4032 :           std::vector<string> words=Tools::getWords(line);
     850        2016 :           if(words.size()<3) error("cannot understand box format");
     851        2016 :           Tools::convert(words[0],cell[0]);
     852        2016 :           Tools::convert(words[1],cell[4]);
     853        2016 :           Tools::convert(words[2],cell[8]);
     854        2286 :           if(words.size()>3) Tools::convert(words[3],cell[1]);
     855        2286 :           if(words.size()>4) Tools::convert(words[4],cell[2]);
     856        2286 :           if(words.size()>5) Tools::convert(words[5],cell[3]);
     857        2286 :           if(words.size()>6) Tools::convert(words[6],cell[5]);
     858        2286 :           if(words.size()>7) Tools::convert(words[7],cell[6]);
     859        2286 :           if(words.size()>8) Tools::convert(words[8],cell[7]);
     860             :         }
     861             : 
     862             :       }
     863             : 
     864       58976 :       p.cmd("setStepLong",&step);
     865       58976 :       p.cmd("setStopFlag",&plumedStopCondition);
     866             : 
     867       29488 :       if(debug_dd) {
     868       72908 :         for(int i=0; i<dd_nlocal; ++i) {
     869       71144 :           int kk=dd_gatindex[i];
     870      106716 :           dd_coordinates[3*i+0]=coordinates[3*kk+0];
     871      106716 :           dd_coordinates[3*i+1]=coordinates[3*kk+1];
     872      106716 :           dd_coordinates[3*i+2]=coordinates[3*kk+2];
     873             :         }
     874        3528 :         p.cmd("setForces",&dd_forces[0]);
     875        3528 :         p.cmd("setPositions",&dd_coordinates[0]);
     876        3528 :         p.cmd("setMasses",&dd_masses[0]);
     877        3528 :         p.cmd("setCharges",&dd_charges[0]);
     878             :       } else {
     879             : // this is required to avoid troubles when the last domain
     880             : // contains zero atoms
     881             : // Basically, for empty domains we pass null pointers
     882             : #define fix_pd(xx) (pd_nlocal!=0?&xx:NULL)
     883       83172 :         p.cmd("setForces",fix_pd(forces[3*pd_start]));
     884       83172 :         p.cmd("setPositions",fix_pd(coordinates[3*pd_start]));
     885       83172 :         p.cmd("setMasses",fix_pd(masses[pd_start]));
     886       83172 :         p.cmd("setCharges",fix_pd(charges[pd_start]));
     887             :       }
     888       58976 :       p.cmd("setBox",&cell[0]);
     889       58976 :       p.cmd("setVirial",&virial[0]);
     890             :     } else {
     891        4654 :       p.cmd("setStepLong",&step);
     892        4654 :       p.cmd("setStopFlag",&plumedStopCondition);
     893             :     }
     894       63630 :     p.cmd("calc");
     895             : 
     896             : // this is necessary as only processor zero is adding to the virial:
     897       31815 :     intracomm.Bcast(virial,0);
     898       31815 :     if(debug_pd) intracomm.Sum(forces);
     899       31815 :     if(debug_dd) {
     900       72908 :       for(int i=0; i<dd_nlocal; i++) {
     901      142288 :         forces[3*dd_gatindex[i]+0]=dd_forces[3*i+0];
     902      106716 :         forces[3*dd_gatindex[i]+1]=dd_forces[3*i+1];
     903      106716 :         forces[3*dd_gatindex[i]+2]=dd_forces[3*i+2];
     904             :       }
     905        3528 :       dd_forces.assign(3*natoms,0.0);
     906        1764 :       intracomm.Sum(forces);
     907             :     }
     908       31815 :     if(debug_grex &&step%grex_stride==0) {
     909         228 :       p.cmd("GREX savePositions");
     910         114 :       if(intracomm.Get_rank()>0) {
     911         114 :         p.cmd("GREX prepare");
     912             :       } else {
     913          57 :         int r=intercomm.Get_rank();
     914          57 :         int n=intercomm.Get_size();
     915          57 :         int partner=r+(2*((r+step/grex_stride)%2))-1;
     916          57 :         if(partner<0)partner=0;
     917          57 :         if(partner>=n) partner=n-1;
     918         114 :         p.cmd("GREX setPartner",&partner);
     919         114 :         p.cmd("GREX calculate");
     920         114 :         p.cmd("GREX shareAllDeltaBias");
     921         399 :         for(int i=0; i<n; i++) {
     922         171 :           string s; Tools::convert(i,s);
     923         684 :           real a=std::numeric_limits<real>::quiet_NaN(); s="GREX getDeltaBias "+s; p.cmd(s.c_str(),&a);
     924         171 :           if(grex_log) fprintf(grex_log," %f",a);
     925             :         }
     926          57 :         if(grex_log) fprintf(grex_log,"\n");
     927             :       }
     928             :     }
     929             : 
     930             : 
     931       31815 :     if(fp_forces) {
     932       18458 :       fprintf(fp_forces,"%d\n",natoms);
     933      313786 :       string fmtv=dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+"\n";
     934       92290 :       string fmt=dumpforcesFmt+" "+dumpforcesFmt+" "+dumpforcesFmt+"\n";
     935       18458 :       if(dumpfullvirial) {
     936         350 :         fprintf(fp_forces,fmtv.c_str(),virial[0],virial[1],virial[2],virial[3],virial[4],virial[5],virial[6],virial[7],virial[8]);
     937             :       } else {
     938       18108 :         fprintf(fp_forces,fmt.c_str(),virial[0],virial[4],virial[8]);
     939             :       }
     940       36916 :       fmt="X "+fmt;
     941     3135886 :       for(int i=0; i<natoms; i++)
     942     6234856 :         fprintf(fp_forces,fmt.c_str(),forces[3*i],forces[3*i+1],forces[3*i+2]);
     943             :     }
     944       31815 :     if(debugforces.length()>0) {
     945             :       // Now call the routine to work out the derivatives numerically
     946          40 :       numder.assign(3*natoms+9,real(0.0)); real base=0;
     947          40 :       p.cmd("getBias",&base);
     948          20 :       if( fabs(base)<epsilon ) printf("WARNING: bias for configuration appears to be zero so debugging forces is trivial");
     949          20 :       evaluateNumericalDerivatives( step, p, coordinates, masses, charges, cell, base, numder );
     950             : 
     951             :       // And output everything to a file
     952          40 :       fp_dforces.fmtField(" " + dumpforcesFmt);
     953         320 :       for(int i=0; i<3*natoms; ++i) {
     954         300 :         fp_dforces.printField("parameter",(int)i);
     955         450 :         fp_dforces.printField("analytical",forces[i]);
     956         300 :         fp_dforces.printField("numerical",-numder[i]);
     957         150 :         fp_dforces.printField();
     958             :       }
     959             :       // And print the virial
     960         380 :       for(int i=0; i<9; ++i) {
     961         360 :         fp_dforces.printField("parameter",3*natoms+i );
     962         540 :         fp_dforces.printField("analytical",virial[i] );
     963         540 :         fp_dforces.printField("numerical",-numder[3*natoms+i]);
     964         180 :         fp_dforces.printField();
     965             :       }
     966             :     }
     967             : 
     968       31815 :     if(plumedStopCondition) break;
     969             : 
     970       31770 :     step+=stride;
     971             :   }
     972        1158 :   if(!parseOnly) p.cmd("runFinalJobs");
     973             : 
     974         579 :   if(fp_forces) fclose(fp_forces);
     975         579 :   if(debugforces.length()>0) fp_dforces.close();
     976         579 :   if(fp && fp!=in)fclose(fp);
     977             : #ifdef __PLUMED_HAS_XDRFILE
     978         579 :   if(xd) xdrfile_close(xd);
     979             : #endif
     980             : #ifdef __PLUMED_HAS_MOLFILE_PLUGINS
     981         579 :   if(h_in) api->close_file_read(h_in);
     982             : #endif
     983         579 :   if(grex_log) fclose(grex_log);
     984             : 
     985             :   return 0;
     986             : }
     987             : 
     988             : template<typename real>
     989          20 : void Driver<real>::evaluateNumericalDerivatives( const long int& step, PlumedMain& p, const std::vector<real>& coordinates,
     990             :     const std::vector<real>& masses, const std::vector<real>& charges,
     991             :     std::vector<real>& cell, const double& base, std::vector<real>& numder ) {
     992             : 
     993          20 :   int natoms = coordinates.size() / 3; real delta = sqrt(epsilon);
     994          20 :   std::vector<Vector> pos(natoms); real bias=0;
     995          20 :   std::vector<real> fake_forces( 3*natoms ), fake_virial(9);
     996         120 :   for(int i=0; i<natoms; ++i) {
     997         500 :     for(unsigned j=0; j<3; ++j) pos[i][j]=coordinates[3*i+j];
     998             :   }
     999             : 
    1000         120 :   for(int i=0; i<natoms; ++i) {
    1001         350 :     for(unsigned j=0; j<3; ++j) {
    1002         300 :       pos[i][j]=pos[i][j]+delta;
    1003         300 :       p.cmd("setStepLong",&step);
    1004         450 :       p.cmd("setPositions",&pos[0][0]);
    1005         450 :       p.cmd("setForces",&fake_forces[0]);
    1006         300 :       p.cmd("setMasses",&masses[0]);
    1007         300 :       p.cmd("setCharges",&charges[0]);
    1008         450 :       p.cmd("setBox",&cell[0]);
    1009         450 :       p.cmd("setVirial",&fake_virial[0]);
    1010         300 :       p.cmd("prepareCalc");
    1011         300 :       p.cmd("performCalcNoUpdate");
    1012         300 :       p.cmd("getBias",&bias);
    1013         300 :       pos[i][j]=coordinates[3*i+j];
    1014         300 :       numder[3*i+j] = (bias - base) / delta;
    1015             :     }
    1016             :   }
    1017             : 
    1018             :   // Create the cell
    1019          20 :   Tensor box( cell[0], cell[1], cell[2], cell[3], cell[4], cell[5], cell[6], cell[7], cell[8] );
    1020             :   // And the virial
    1021          20 :   Pbc pbc; pbc.setBox( box ); Tensor nvirial;
    1022         260 :   for(unsigned i=0; i<3; i++) for(unsigned k=0; k<3; k++) {
    1023         180 :       double arg0=box(i,k);
    1024        1080 :       for(int j=0; j<natoms; ++j) pos[j]=pbc.realToScaled( pos[j] );
    1025         360 :       cell[3*i+k]=box(i,k)=box(i,k)+delta; pbc.setBox(box);
    1026        1080 :       for(int j=0; j<natoms; j++) pos[j]=pbc.scaledToReal( pos[j] );
    1027         360 :       p.cmd("setStepLong",&step);
    1028         540 :       p.cmd("setPositions",&pos[0][0]);
    1029         540 :       p.cmd("setForces",&fake_forces[0]);
    1030         360 :       p.cmd("setMasses",&masses[0]);
    1031         360 :       p.cmd("setCharges",&charges[0]);
    1032         540 :       p.cmd("setBox",&cell[0]);
    1033         540 :       p.cmd("setVirial",&fake_virial[0]);
    1034         360 :       p.cmd("prepareCalc");
    1035         360 :       p.cmd("performCalcNoUpdate");
    1036         360 :       p.cmd("getBias",&bias);
    1037         360 :       cell[3*i+k]=box(i,k)=arg0; pbc.setBox(box);
    1038        3330 :       for(int j=0; j<natoms; j++) for(unsigned n=0; n<3; ++n) pos[j][n]=coordinates[3*j+n];
    1039         180 :       nvirial(i,k) = ( bias - base ) / delta;
    1040             :     }
    1041          20 :   nvirial=-matmul(box.transpose(),nvirial);
    1042         260 :   for(unsigned i=0; i<3; i++) for(unsigned k=0; k<3; k++)  numder[3*natoms+3*i+k] = nvirial(i,k);
    1043             : 
    1044          20 : }
    1045             : 
    1046             : }
    1047        5517 : }

Generated by: LCOV version 1.14