LCOV - code coverage report
Current view: top level - generic - Plumed.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 167 179 93.3 %
Date: 2024-10-11 08:09:47 Functions: 12 14 85.7 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2018-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 "core/ActionAtomistic.h"
      23             : #include "core/ActionWithValue.h"
      24             : #include "core/ActionPilot.h"
      25             : #include "core/ActionRegister.h"
      26             : #include "tools/Tools.h"
      27             : #include "tools/PlumedHandle.h"
      28             : #include "core/PlumedMain.h"
      29             : #include <cstring>
      30             : #ifdef __PLUMED_HAS_DLOPEN
      31             : #include <dlfcn.h>
      32             : #endif
      33             : 
      34             : #include <iostream>
      35             : 
      36             : namespace PLMD {
      37             : namespace generic {
      38             : 
      39             : //+PLUMEDOC GENERIC PLUMED
      40             : /*
      41             : Embed a separate PLUMED instance.
      42             : 
      43             : This command can be used to embed a separate PLUMED instance.
      44             : Only required atoms will be passed to that instance, using an interface
      45             : that is similar to the one used when calling PLUMED from the NAMD engine.
      46             : 
      47             : Notice that the two instances are running in the same UNIX process, so that they cannot be perfectly isolated.
      48             : However, most of the features are expected to work correctly.
      49             : 
      50             : Notes:
      51             : - The \ref LOAD action will not work correctly since registers will be shared among the two instances.
      52             :   In particular, the loaded actions will be visible to both guest and host irrespective of where they are loaded from.
      53             :   This can be fixed and will probably be fixed in a later version.
      54             : - `CHDIR` is not thread safe.
      55             :    However, in most implementations there will be a single process running PLUMED, with perhaps multiple OpenMP threads
      56             :    spawn in order to parallelize the calculation of individual variables. So, this is likely not a problem.
      57             : - MPI is working correctly. However, notice that the guest PLUMED will always run with a single process.
      58             :   Multiple replicas should be handled correctly.
      59             : 
      60             : As an advanced feature, one can use the option `KERNEL` to select the version of the guest PLUMED instance.
      61             : In particular, an empty `KERNEL` (default) implies that the guest PLUMED instance is the same as the host one
      62             : (no library is loaded).
      63             : On the other hand, `KERNEL=/path/to/libplumedKernel.so` will allow specifying a library to be loaded for the
      64             : guest instance.
      65             : In addition to those mentioned above, this feature has limitations mostly related to
      66             : clashes in the symbols defined in the different instances of the PLUMED library:
      67             : - On OSX, if you load a KERNEL with version >=2.5 there should be no problem thanks to the use
      68             :   of two-level namespaces.
      69             : - On OSX, if you load a KERNEL with version <=2.4 there should be clashes in symbol resolution.
      70             :   The only possible workarounds are:
      71             :   - If you are are using PLUMED with an MD code, it should be patched with `--runtime` and you should
      72             :     `export PLUMED_LOAD_NAMESPACE=LOCAL` before starting the MD engine.
      73             :   - If you are using PLUMED driver, you should launch the `plumed-runtime` executable (contained in the
      74             :     `prefix/lib/plumed/` directory), export `PLUMED_KERNEL` equal to the path of the host kernel library
      75             :    (as usual in runtime loading) and `export PLUMED_LOAD_NAMESPACE=LOCAL` before launching `plumed-runtime driver`.
      76             : - On Linux, any `KERNEL` should in principle work correctly. To achieve namespace separation we are loading
      77             :   the guest kernel with `RTLD_DEEPBIND`. However, this might create difficult to track problems in other linked libraries.
      78             : - On Unix systems where `RTLD_DEEPBIND` is not available kernels will not load correctly.
      79             : - In general, there might be unexpected crashes. Particularly difficult are situations where different
      80             :   kernels were compiled with different libraries.
      81             : 
      82             : A possible solution for the symbol clashes (not tested) could be to recompile the alternative PLUMED
      83             : versions using separate C++ namespaces (e.g. `./configure CPPFLAGS=-DPLMD=PLMD_2_3`).
      84             : 
      85             : \todo
      86             : - Add support for multiple time stepping (`STRIDE` different from 1).
      87             : - Add the possibility to import CVs calculated in the host PLUMED instance into the guest PLUMED instance.
      88             :   Will be possible after \issue{83} will be closed.
      89             : - Add the possibility to export CVs calculated in the guest PLUMED instance into the host PLUMED instance.
      90             :   Could be implemented using the `DataFetchingObject` class.
      91             : 
      92             : \par Examples
      93             : 
      94             : Here an example plumed file:
      95             : \plumedfile
      96             : # plumed.dat
      97             : p: PLUMED FILE=plumed2.dat
      98             : PRINT ARG=p.bias FILE=COLVAR
      99             : \endplumedfile
     100             : `plumed2.dat` can be an arbitrary plumed input file, for instance
     101             : \plumedfile
     102             : #SETTINGS FILENAME=plumed2.dat
     103             : # plumed2.dat
     104             : d: DISTANCE ATOMS=1,10
     105             : RESTRAINT ARG=d KAPPA=10 AT=2
     106             : \endplumedfile
     107             : 
     108             : Now a more useful example.
     109             : Imagine that you ran simulations using two different PLUMED input files.
     110             : The files are long and complex and there are some clashes in the name of the variables (that is: same names
     111             : are used in both files, same files are written, etc). In addition, files might have been written using different units (see \ref UNITS`).
     112             : If you want to run a single simulation with a bias potential
     113             : that is the sum of the two bias potentials, you can:
     114             : - Place the two input files, as well as all the files required by plumed, in separate directories `directory1` and `directory2`.
     115             : - Run with the following input file in the parent directory:
     116             : \plumedfile
     117             : # plumed.dat
     118             : PLUMED FILE=plumed.dat CHDIR=directory1
     119             : PLUMED FILE=plumed.dat CHDIR=directory2
     120             : \endplumedfile
     121             : 
     122             : */
     123             : //+ENDPLUMEDOC
     124             : 
     125             : class Plumed:
     126             :   public ActionAtomistic,
     127             :   public ActionWithValue,
     128             :   public ActionPilot
     129             : {
     130             : /// True on root processor
     131             :   const bool root;
     132             : /// Separate directory.
     133             :   const std::string directory;
     134             : /// Interface to underlying plumed object.
     135             :   PlumedHandle p;
     136             : /// API number.
     137             :   const int API;
     138             : /// Self communicator
     139             :   Communicator comm_self;
     140             : /// Intercommunicator
     141             :   Communicator intercomm;
     142             : /// Detect first usage.
     143             :   bool first=true;
     144             : /// Stop flag, used to stop e.g. in committor analysis
     145             :   int stop=0;
     146             : /// Index of requested atoms.
     147             :   std::vector<int> index;
     148             : /// Masses of requested atoms.
     149             :   std::vector<double> masses;
     150             : /// Charges of requested atoms.
     151             :   std::vector<double> charges;
     152             : /// Forces on requested atoms.
     153             :   std::vector<double> forces;
     154             : /// Requested positions.
     155             :   std::vector<double> positions;
     156             : /// Applied virial.
     157             :   Tensor virial;
     158             : public:
     159             : /// Constructor.
     160             :   explicit Plumed(const ActionOptions&);
     161             : /// Documentation.
     162             :   static void registerKeywords( Keywords& keys );
     163             :   void prepare() override;
     164             :   void calculate() override;
     165             :   void apply() override;
     166             :   void update() override;
     167           0 :   unsigned getNumberOfDerivatives() override {
     168           0 :     return 0;
     169             :   }
     170             : };
     171             : 
     172       10443 : PLUMED_REGISTER_ACTION(Plumed,"PLUMED")
     173             : 
     174          13 : void Plumed::registerKeywords( Keywords& keys ) {
     175          13 :   Action::registerKeywords( keys );
     176          13 :   ActionPilot::registerKeywords( keys );
     177          13 :   ActionAtomistic::registerKeywords( keys );
     178          26 :   keys.add("compulsory","STRIDE","1","stride different from 1 are not supported yet");
     179          26 :   keys.add("optional","FILE","input file for the guest PLUMED instance");
     180          26 :   keys.add("optional","KERNEL","kernel to be used for the guest PLUMED instance (USE WITH CAUTION!)");
     181          26 :   keys.add("optional","LOG","log file for the guest PLUMED instance. By default the host log is used");
     182          26 :   keys.add("optional","CHDIR","run guest in a separate directory");
     183          26 :   keys.addFlag("NOREPLICAS",false,"run multiple replicas as isolated ones, without letting them know that the host has multiple replicas");
     184          26 :   keys.addOutputComponent("bias","default","the instantaneous value of the bias potential");
     185          13 : }
     186             : 
     187          12 : Plumed::Plumed(const ActionOptions&ao):
     188             :   Action(ao),
     189             :   ActionAtomistic(ao),
     190             :   ActionWithValue(ao),
     191             :   ActionPilot(ao),
     192          24 :   root(comm.Get_rank()==0),
     193          24 :   directory([&]() {
     194             :   std::string directory;
     195          24 :   parse("CHDIR",directory);
     196          12 :   if(directory.length()>0) {
     197           0 :     log<<"  running on separate directory "<<directory<<"\n";
     198             :   }
     199          12 :   return directory;
     200             : }()),
     201          24 : p([&]() {
     202             :   std::string kernel;
     203          24 :   parse("KERNEL",kernel);
     204          12 :   if(kernel.length()==0) {
     205          11 :     log<<"  using the current kernel\n";
     206          11 :     return PlumedHandle();
     207             :   } else {
     208           1 :     log<<"  using the kernel "<<kernel<<"\n";
     209           1 :     return PlumedHandle::dlopen(kernel.c_str());
     210             :   }
     211             : }()),
     212          24 : API([&]() {
     213          12 :   int api=0;
     214          24 :   p.cmd("getApiVersion",&api);
     215          12 :   log<<"  reported API version is "<<api<<"\n";
     216             :   // note: this is required in order to have cmd performCalcNoUpdate and cmd update
     217             :   // as a matter of fact, any version <2.5 will not even load due to namespace pollution
     218          12 :   plumed_assert(api>3) << "API>3 is required for the PLUMED action to work correctly\n";
     219          12 :   return api;
     220          24 : }())
     221             : {
     222          12 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     223             : 
     224             :   bool noreplicas;
     225          12 :   parseFlag("NOREPLICAS",noreplicas);
     226             :   int nreps;
     227          12 :   if(root) nreps=multi_sim_comm.Get_size();
     228          12 :   comm.Bcast(nreps,0);
     229          12 :   if(nreps>1) {
     230           6 :     if(noreplicas) {
     231           0 :       log<<"  running replicas as independent (no suffix used)\n";
     232             :     } else {
     233           6 :       log<<"  running replicas as standard multi replic (with suffix)\n";
     234           6 :       if(root) {
     235           6 :         intercomm.Set_comm(&multi_sim_comm.Get_comm());
     236           9 :         p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm());
     237           9 :         p.cmd("GREX setMPIIntracomm",&comm_self.Get_comm());
     238           6 :         p.cmd("GREX init");
     239             :       }
     240             :     }
     241             :   } else {
     242           6 :     if(noreplicas) {
     243           0 :       log<<"  WARNING: flag NOREPLICAS ignored since we are running without replicas\n";
     244             :     }
     245             :   }
     246             : 
     247          12 :   int natoms=plumed.getAtoms().getNatoms();
     248             : 
     249          12 :   plumed_assert(getStride()==1) << "currently only supports STRIDE=1";
     250             : 
     251          12 :   double dt=getTimeStep();
     252             : 
     253             :   std::string file;
     254          24 :   parse("FILE",file);
     255          12 :   if(file.length()>0) {
     256          12 :     log<<"  with input file "<<file<<"\n";
     257           0 :   } else plumed_error() << "you must provide an input file\n";
     258             : 
     259             :   bool inherited_logfile=false;
     260             :   std::string logfile;
     261          24 :   parse("LOG",logfile);
     262          12 :   if(logfile.length()>0) {
     263           0 :     log<<"  with log file "<<logfile<<"\n";
     264           0 :     if(root) p.cmd("setLogFile",logfile.c_str());
     265          12 :   } else if(log.getFILE()) {
     266          12 :     log<<"  with inherited log file\n";
     267          18 :     if(root) p.cmd("setLog",log.getFILE());
     268             :     inherited_logfile=true;
     269             :   } else {
     270           0 :     log<<"  with log on stdout\n";
     271           0 :     if(root) p.cmd("setLog",stdout);
     272             :   }
     273             : 
     274          12 :   checkRead();
     275             : 
     276          18 :   if(root) p.cmd("setMDEngine","plumed");
     277             : 
     278          12 :   double engunits=plumed.getAtoms().getUnits().getEnergy();
     279          18 :   if(root) p.cmd("setMDEnergyUnits",&engunits);
     280             : 
     281          12 :   double lenunits=plumed.getAtoms().getUnits().getLength();
     282          18 :   if(root) p.cmd("setMDLengthUnits",&lenunits);
     283             : 
     284          12 :   double timunits=plumed.getAtoms().getUnits().getTime();
     285          18 :   if(root) p.cmd("setMDTimeUnits",&timunits);
     286             : 
     287          12 :   double chaunits=plumed.getAtoms().getUnits().getCharge();
     288          18 :   if(root) p.cmd("setMDChargeUnits",&chaunits);
     289          12 :   double masunits=plumed.getAtoms().getUnits().getMass();
     290          18 :   if(root) p.cmd("setMDMassUnits",&masunits);
     291             : 
     292          12 :   double kbt=plumed.getAtoms().getKbT();
     293          18 :   if(root) p.cmd("setKbT",&kbt);
     294             : 
     295          12 :   int res=0;
     296          12 :   if(getRestart()) res=1;
     297          18 :   if(root) p.cmd("setRestart",&res);
     298             : 
     299          18 :   if(root) p.cmd("setNatoms",&natoms);
     300          18 :   if(root) p.cmd("setTimestep",&dt);
     301          18 :   if(root) p.cmd("setPlumedDat",file.c_str());
     302             : 
     303          12 :   addComponentWithDerivatives("bias");
     304          12 :   componentIsNotPeriodic("bias");
     305             : 
     306          12 :   if(inherited_logfile) log<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
     307          18 :   if(root) p.cmd("init");
     308          12 :   if(inherited_logfile) log<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
     309          12 : }
     310             : 
     311         164 : void Plumed::prepare() {
     312         164 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     313         164 :   int step=getStep();
     314         253 :   if(root) p.cmd("setStep",&step);
     315         253 :   if(root) p.cmd("prepareDependencies");
     316         164 :   int ene=0;
     317         253 :   if(root) p.cmd("isEnergyNeeded",&ene);
     318         164 :   if(ene) plumed_error()<<"It is not currently possible to use ENERGY in a guest PLUMED";
     319         164 :   int n=0;
     320         253 :   if(root) p.cmd("createFullList",&n);
     321         164 :   const int *pointer=nullptr;
     322         253 :   if(root) p.cmd("getFullList",&pointer);
     323         164 :   bool redo=(index.size()!=n);
     324         164 :   if(first) redo=true;
     325         164 :   first=false;
     326        4409 :   if(root && !redo) for(int i=0; i<n; i++) if(index[i]!=pointer[i]) { redo=true; break;};
     327         164 :   if(root && redo) {
     328          22 :     index.resize(n);
     329          22 :     masses.resize(n);
     330          22 :     forces.resize(3*n);
     331          22 :     positions.resize(3*n);
     332          22 :     charges.resize(n);
     333        1043 :     for(int i=0; i<n; i++) {
     334        1021 :       index[i]=pointer[i];
     335             :     };
     336          44 :     p.cmd("setAtomsNlocal",&n);
     337          44 :     p.cmd("setAtomsGatindex",index.data(),index.size());
     338             :   }
     339         253 :   if(root) p.cmd("clearFullList");
     340         164 :   int tmp=0;
     341         164 :   if(root && redo) {
     342          22 :     tmp=1;
     343             :   }
     344         164 :   comm.Bcast(tmp,0);
     345         164 :   if(tmp) {
     346          34 :     int s=index.size();
     347          34 :     comm.Bcast(s,0);
     348          34 :     if(!root) index.resize(s);
     349          34 :     comm.Bcast(index,0);
     350             :     std::vector<AtomNumber> numbers;
     351          34 :     numbers.reserve(index.size());
     352        2138 :     for(auto i : index) numbers.emplace_back(AtomNumber::index(i));
     353          34 :     requestAtoms(numbers);
     354             :   }
     355         164 : }
     356             : 
     357         134 : void Plumed::calculate() {
     358         134 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     359         208 :   if(root) p.cmd("setStopFlag",&stop);
     360         134 :   Tensor box=getPbc().getBox();
     361         208 :   if(root) p.cmd("setBox",&box[0][0],9);
     362             : 
     363         134 :   virial.zero();
     364       24875 :   for(int i=0; i<forces.size(); i++) forces[i]=0.0;
     365        4238 :   for(int i=0; i<masses.size(); i++) masses[i]=getMass(i);
     366        4238 :   for(int i=0; i<charges.size(); i++) charges[i]=getCharge(i);
     367             : 
     368         208 :   if(root) p.cmd("setMasses",masses.data(),masses.size());
     369         208 :   if(root) p.cmd("setCharges",charges.data(),charges.size());
     370         208 :   if(root) p.cmd("setPositions",positions.data(),positions.size());
     371         208 :   if(root) p.cmd("setForces",forces.data(),forces.size());
     372         208 :   if(root) p.cmd("setVirial",&virial[0][0],9);
     373             : 
     374             : 
     375        4238 :   if(root) for(unsigned i=0; i<getNumberOfAtoms(); i++) {
     376        4104 :       positions[3*i+0]=getPosition(i)[0];
     377        4104 :       positions[3*i+1]=getPosition(i)[1];
     378        4104 :       positions[3*i+2]=getPosition(i)[2];
     379             :     }
     380             : 
     381         208 :   if(root) p.cmd("shareData");
     382         208 :   if(root) p.cmd("performCalcNoUpdate");
     383             : 
     384         134 :   int s=forces.size();
     385         134 :   comm.Bcast(s,0);
     386         134 :   if(!root) forces.resize(s);
     387         134 :   comm.Bcast(forces,0);
     388         134 :   comm.Bcast(virial,0);
     389             : 
     390         134 :   double bias=0.0;
     391         208 :   if(root) p.cmd("getBias",&bias);
     392         134 :   comm.Bcast(bias,0);
     393         134 :   getPntrToComponent("bias")->set(bias);
     394         134 : }
     395             : 
     396         104 : void Plumed::apply() {
     397         104 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     398             :   auto & f(modifyForces());
     399        6596 :   for(unsigned i=0; i<getNumberOfAtoms(); i++) {
     400        6492 :     f[i][0]+=forces[3*i+0];
     401        6492 :     f[i][1]+=forces[3*i+1];
     402        6492 :     f[i][2]+=forces[3*i+2];
     403             :   }
     404             :   auto & v(modifyVirial());
     405         104 :   v+=virial;
     406         104 : }
     407             : 
     408         104 : void Plumed::update() {
     409         104 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     410         163 :   if(root) p.cmd("update");
     411         104 :   comm.Bcast(stop,0);
     412         104 :   if(stop) {
     413           0 :     log<<"  Action " << getLabel()<<" asked to stop\n";
     414           0 :     plumed.stop();
     415             :   }
     416         104 : }
     417             : 
     418             : }
     419             : }

Generated by: LCOV version 1.15