LCOV - code coverage report
Current view: top level - generic - Plumed.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 213 229 93.0 %
Date: 2026-03-30 11:13:23 Functions: 10 12 83.3 %

          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 "tools/Communicator.h"
      29             : #include "core/PlumedMain.h"
      30             : #include <cstring>
      31             : #ifdef __PLUMED_HAS_DLOPEN
      32             : #include <dlfcn.h>
      33             : #endif
      34             : 
      35             : #include <iostream>
      36             : 
      37             : namespace PLMD {
      38             : namespace generic {
      39             : 
      40             : //+PLUMEDOC GENERIC PLUMED
      41             : /*
      42             : Embed a separate PLUMED instance.
      43             : 
      44             : This command can be used to embed a separate PLUMED instance.
      45             : Only required atoms will be passed to that instance, using an interface
      46             : that is similar to the one used when calling PLUMED from the NAMD engine.
      47             : 
      48             : Notice that the two instances are running in the same UNIX process, so that they cannot be perfectly isolated.
      49             : However, most of the features are expected to work correctly.
      50             : 
      51             : Notes:
      52             : - The \ref LOAD action will not work correctly since registers will be shared among the two instances.
      53             :   In particular, the loaded actions will be visible to both guest and host irrespective of where they are loaded from.
      54             :   This can be fixed and will probably be fixed in a later version.
      55             : - `CHDIR` is not thread safe.
      56             :    However, in most implementations there will be a single process running PLUMED, with perhaps multiple OpenMP threads
      57             :    spawn in order to parallelize the calculation of individual variables. So, this is likely not a problem.
      58             : - MPI is working correctly. However, notice that the guest PLUMED will always run with a single process.
      59             :   Multiple replicas should be handled correctly.
      60             : 
      61             : As an advanced feature, one can use the option `KERNEL` to select the version of the guest PLUMED instance.
      62             : In particular, an empty `KERNEL` (default) implies that the guest PLUMED instance is the same as the host one
      63             : (no library is loaded).
      64             : On the other hand, `KERNEL=/path/to/libplumedKernel.so` will allow specifying a library to be loaded for the
      65             : guest instance.
      66             : In addition to those mentioned above, this feature has limitations mostly related to
      67             : clashes in the symbols defined in the different instances of the PLUMED library.
      68             : Clashes might be due by synonymous symbols from the PLUMED library or synonymous symbols
      69             : from libraries linked to PLUMED, and would differ depending on the operating system you
      70             : are using:
      71             : - On OSX:
      72             :   - Symbols from the PLUMED library would clash. The only way to avoid is to load PLUMED dynamically:
      73             :     - If you are are using PLUMED with an MD code, it should be patched with `--runtime`.
      74             :     - If you are using PLUMED driver, you should launch the `plumed-runtime` executable (contained in the
      75             :       `prefix/lib/plumed/` directory) and export `PLUMED_KERNEL` equal to the path of the host kernel library
      76             :      (as usual in runtime loading). Notice that as of PLUMED 2.10 we load kernels with RTLD_LOCAL by default.
      77             :     - Symbols from dependent libraries should not clash since, as of version 2.5, we are using
      78             :       two-level namespace. Problems when loading previous versions should anyway be solved using runtime
      79             :       mode as explained above.
      80             : - On Linux, any `KERNEL` should in principle work correctly. To achieve namespace separation we are loading
      81             :   the guest kernel with `RTLD_DEEPBIND`. However, this might create difficult to track problems in other linked libraries.
      82             : - On Unix systems where `RTLD_DEEPBIND` is not available kernels will not load correctly.
      83             : - In general, there might be unexpected crashes. Particularly difficult are situations where different
      84             :   kernels were compiled with different libraries.
      85             : 
      86             : \todo
      87             : - Add support for multiple time stepping (`STRIDE` different from 1).
      88             : - Add the possibility to import CVs calculated in the host PLUMED instance into the guest PLUMED instance.
      89             :   Will be possible after \issue{83} will be closed.
      90             : - Add the possibility to export CVs calculated in the guest PLUMED instance into the host PLUMED instance.
      91             :   Could be implemented using the `DataFetchingObject` class.
      92             : 
      93             : \par Examples
      94             : 
      95             : Here an example plumed file:
      96             : \plumedfile
      97             : # plumed.dat
      98             : p: PLUMED FILE=plumed2.dat
      99             : PRINT ARG=p.bias FILE=COLVAR
     100             : \endplumedfile
     101             : `plumed2.dat` can be an arbitrary plumed input file, for instance
     102             : \plumedfile
     103             : #SETTINGS FILENAME=plumed2.dat
     104             : # plumed2.dat
     105             : d: DISTANCE ATOMS=1,10
     106             : RESTRAINT ARG=d KAPPA=10 AT=2
     107             : \endplumedfile
     108             : 
     109             : Now a more useful example.
     110             : Imagine that you ran simulations using two different PLUMED input files.
     111             : The files are long and complex and there are some clashes in the name of the variables (that is: same names
     112             : are used in both files, same files are written, etc). In addition, files might have been written using different units (see \ref UNITS`).
     113             : If you want to run a single simulation with a bias potential
     114             : that is the sum of the two bias potentials, you can:
     115             : - Place the two input files, as well as all the files required by plumed, in separate directories `directory1` and `directory2`.
     116             : - Run with the following input file in the parent directory:
     117             : \plumedfile
     118             : # plumed.dat
     119             : PLUMED FILE=plumed.dat CHDIR=directory1
     120             : PLUMED FILE=plumed.dat CHDIR=directory2
     121             : \endplumedfile
     122             : 
     123             : */
     124             : //+ENDPLUMEDOC
     125             : 
     126             : class Plumed:
     127             :   public ActionAtomistic,
     128             :   public ActionWithValue,
     129             :   public ActionPilot {
     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          92 :   bool actionHasForces() override {
     171          92 :     return true;
     172             :   }
     173             : };
     174             : 
     175             : PLUMED_REGISTER_ACTION(Plumed,"PLUMED")
     176             : 
     177          16 : void Plumed::registerKeywords( Keywords& keys ) {
     178          16 :   Action::registerKeywords( keys );
     179          16 :   ActionPilot::registerKeywords( keys );
     180          16 :   ActionAtomistic::registerKeywords( keys );
     181          32 :   keys.add("compulsory","STRIDE","1","stride different from 1 are not supported yet");
     182          32 :   keys.add("optional","FILE","input file for the guest PLUMED instance");
     183          32 :   keys.add("optional","KERNEL","kernel to be used for the guest PLUMED instance (USE WITH CAUTION!)");
     184          32 :   keys.add("optional","LOG","log file for the guest PLUMED instance. By default the host log is used");
     185          32 :   keys.add("optional","CHDIR","run guest in a separate directory");
     186          32 :   keys.addFlag("NOREPLICAS",false,"run multiple replicas as isolated ones, without letting them know that the host has multiple replicas");
     187          32 :   keys.addOutputComponent("bias","default","the instantaneous value of the bias potential");
     188          16 : }
     189             : 
     190          12 : Plumed::Plumed(const ActionOptions&ao):
     191             :   Action(ao),
     192             :   ActionAtomistic(ao),
     193             :   ActionWithValue(ao),
     194             :   ActionPilot(ao),
     195          24 :   root(comm.Get_rank()==0),
     196          24 :   directory([&]() {
     197             :   std::string directory;
     198          24 :   parse("CHDIR",directory);
     199          12 :   if(directory.length()>0) {
     200           0 :     log<<"  running on separate directory "<<directory<<"\n";
     201             :   }
     202          12 :   return directory;
     203             : }()),
     204          24 : p([&]() {
     205             :   std::string kernel;
     206          24 :   parse("KERNEL",kernel);
     207          12 :   if(kernel.length()==0) {
     208          11 :     log<<"  using the current kernel\n";
     209          11 :     return PlumedHandle();
     210             :   } else {
     211           1 :     log<<"  using the kernel "<<kernel<<"\n";
     212           1 :     return PlumedHandle::dlopen(kernel.c_str());
     213             :   }
     214             : }()),
     215          24 : API([&]() {
     216          12 :   int api=0;
     217          12 :   p.cmd("getApiVersion",&api);
     218          12 :   log<<"  reported API version is "<<api<<"\n";
     219             :   // note: this is required in order to have cmd performCalcNoUpdate and cmd update
     220             :   // as a matter of fact, any version <2.5 will not even load due to namespace pollution
     221          12 :   plumed_assert(api>3) << "API>3 is required for the PLUMED action to work correctly\n";
     222          12 :   return api;
     223          24 : }()) {
     224          12 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     225             : 
     226             :   bool noreplicas;
     227          12 :   parseFlag("NOREPLICAS",noreplicas);
     228             :   int nreps;
     229          12 :   if(root) {
     230           6 :     nreps=multi_sim_comm.Get_size();
     231             :   }
     232          12 :   comm.Bcast(nreps,0);
     233          12 :   if(nreps>1) {
     234           6 :     if(noreplicas) {
     235           0 :       log<<"  running replicas as independent (no suffix used)\n";
     236             :     } else {
     237           6 :       log<<"  running replicas as standard multi replic (with suffix)\n";
     238           6 :       if(root) {
     239           6 :         intercomm.Set_comm(&multi_sim_comm.Get_comm());
     240           6 :         p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm());
     241           6 :         p.cmd("GREX setMPIIntracomm",&comm_self.Get_comm());
     242           3 :         p.cmd("GREX init");
     243             :       }
     244             :     }
     245             :   } else {
     246           6 :     if(noreplicas) {
     247           0 :       log<<"  WARNING: flag NOREPLICAS ignored since we are running without replicas\n";
     248             :     }
     249             :   }
     250             : 
     251          12 :   int natoms=getTotAtoms();
     252             : 
     253          12 :   plumed_assert(getStride()==1) << "currently only supports STRIDE=1";
     254             : 
     255          12 :   double dt=getTimeStep();
     256             : 
     257             :   std::string file;
     258          24 :   parse("FILE",file);
     259          12 :   if(file.length()>0) {
     260          12 :     log<<"  with input file "<<file<<"\n";
     261             :   } else {
     262           0 :     plumed_error() << "you must provide an input file\n";
     263             :   }
     264             : 
     265             :   bool inherited_logfile=false;
     266             :   std::string logfile;
     267          24 :   parse("LOG",logfile);
     268          12 :   if(logfile.length()>0) {
     269           0 :     log<<"  with log file "<<logfile<<"\n";
     270           0 :     if(root) {
     271           0 :       p.cmd("setLogFile",logfile.c_str());
     272             :     }
     273          12 :   } else if(log.getFILE()) {
     274          12 :     log<<"  with inherited log file\n";
     275          12 :     if(root) {
     276           6 :       p.cmd("setLog",log.getFILE());
     277             :     }
     278             :     inherited_logfile=true;
     279             :   } else {
     280           0 :     log<<"  with log on stdout\n";
     281           0 :     if(root) {
     282           0 :       p.cmd("setLog",stdout);
     283             :     }
     284             :   }
     285             : 
     286          12 :   checkRead();
     287             : 
     288          12 :   if(root) {
     289           6 :     p.cmd("setMDEngine","plumed");
     290             :   }
     291             : 
     292          12 :   double engunits=getUnits().getEnergy();
     293          12 :   if(root) {
     294           6 :     p.cmd("setMDEnergyUnits",&engunits);
     295             :   }
     296             : 
     297          12 :   double lenunits=getUnits().getLength();
     298          12 :   if(root) {
     299           6 :     p.cmd("setMDLengthUnits",&lenunits);
     300             :   }
     301             : 
     302          12 :   double timunits=getUnits().getTime();
     303          12 :   if(root) {
     304           6 :     p.cmd("setMDTimeUnits",&timunits);
     305             :   }
     306             : 
     307          12 :   double chaunits=getUnits().getCharge();
     308          12 :   if(root) {
     309           6 :     p.cmd("setMDChargeUnits",&chaunits);
     310             :   }
     311          12 :   double masunits=getUnits().getMass();
     312          12 :   if(root) {
     313           6 :     p.cmd("setMDMassUnits",&masunits);
     314             :   }
     315             : 
     316          12 :   double kbt=getkBT();
     317          12 :   if(root) {
     318           6 :     p.cmd("setKbT",&kbt);
     319             :   }
     320             : 
     321          12 :   int res=0;
     322          12 :   if(getRestart()) {
     323           0 :     res=1;
     324             :   }
     325          12 :   if(root) {
     326           6 :     p.cmd("setRestart",&res);
     327             :   }
     328             : 
     329          12 :   if(root) {
     330           6 :     p.cmd("setNatoms",&natoms);
     331             :   }
     332          12 :   if(root) {
     333           6 :     p.cmd("setTimestep",&dt);
     334             :   }
     335          12 :   if(root) {
     336           6 :     p.cmd("setPlumedDat",file.c_str());
     337             :   }
     338             : 
     339          24 :   addComponentWithDerivatives("bias");
     340          12 :   componentIsNotPeriodic("bias");
     341             : 
     342          12 :   if(inherited_logfile) {
     343          12 :     log<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
     344             :   }
     345          12 :   if(root) {
     346           6 :     p.cmd("init");
     347             :   }
     348          12 :   if(inherited_logfile) {
     349          12 :     log<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
     350             :   }
     351          12 : }
     352             : 
     353         164 : void Plumed::prepare() {
     354         164 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     355         164 :   int step=getStep();
     356         164 :   if(root) {
     357          89 :     p.cmd("setStep",&step);
     358             :   }
     359         164 :   if(root) {
     360          89 :     p.cmd("prepareDependencies");
     361             :   }
     362         164 :   int ene=0;
     363         164 :   if(root) {
     364          89 :     p.cmd("isEnergyNeeded",&ene);
     365             :   }
     366         164 :   if(ene) {
     367           0 :     plumed_error()<<"It is not currently possible to use ENERGY in a guest PLUMED";
     368             :   }
     369         164 :   int n=0;
     370         164 :   if(root) {
     371          89 :     p.cmd("createFullList",&n);
     372             :   }
     373         164 :   const int *pointer=nullptr;
     374         164 :   if(root) {
     375          89 :     p.cmd("getFullList",&pointer);
     376             :   }
     377         164 :   bool redo=(index.size()!=n);
     378         164 :   if(first) {
     379             :     redo=true;
     380             :   }
     381         164 :   first=false;
     382         164 :   if(root && !redo)
     383        4245 :     for(int i=0; i<n; i++)
     384        4178 :       if(index[i]!=pointer[i]) {
     385             :         redo=true;
     386             :         break;
     387             :       };
     388         164 :   if(root && redo) {
     389          22 :     index.resize(n);
     390          22 :     masses.resize(n);
     391          22 :     forces.resize(3*n);
     392          22 :     positions.resize(3*n);
     393          22 :     charges.resize(n);
     394        1043 :     for(int i=0; i<n; i++) {
     395        1021 :       index[i]=pointer[i];
     396             :     };
     397          22 :     p.cmd("setAtomsNlocal",&n);
     398          22 :     p.cmd("setAtomsGatindex",index.data(), {index.size()});
     399             :   }
     400         164 :   if(root) {
     401          89 :     p.cmd("clearFullList");
     402             :   }
     403         164 :   int tmp=0;
     404         164 :   if(root && redo) {
     405          22 :     tmp=1;
     406             :   }
     407         164 :   comm.Bcast(tmp,0);
     408         164 :   if(tmp) {
     409          34 :     int s=index.size();
     410          34 :     comm.Bcast(s,0);
     411          34 :     if(!root) {
     412          12 :       index.resize(s);
     413             :     }
     414          34 :     comm.Bcast(index,0);
     415             :     std::vector<AtomNumber> numbers;
     416          34 :     numbers.reserve(index.size());
     417        2138 :     for(auto i : index) {
     418        2104 :       numbers.emplace_back(AtomNumber::index(i));
     419             :     }
     420          34 :     requestAtoms(numbers);
     421             :   }
     422         164 : }
     423             : 
     424         134 : void Plumed::calculate() {
     425         134 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     426         134 :   if(root) {
     427          74 :     p.cmd("setStopFlag",&stop);
     428             :   }
     429         134 :   Tensor box=getPbc().getBox();
     430         134 :   if(root)
     431          74 :     p.cmd("setBox",&box[0][0], {3,3});
     432             : 
     433         134 :   virial.zero();
     434       24875 :   for(int i=0; i<forces.size(); i++) {
     435       24741 :     forces[i]=0.0;
     436             :   }
     437        4238 :   for(int i=0; i<masses.size(); i++) {
     438        4104 :     masses[i]=getMass(i);
     439             :   }
     440        4238 :   for(int i=0; i<charges.size(); i++) {
     441        4104 :     charges[i]=getCharge(i);
     442             :   }
     443             : 
     444         134 :   if(root)
     445          74 :     p.cmd("setMasses",masses.data(), {masses.size()});
     446         134 :   if(root)
     447          74 :     p.cmd("setCharges",charges.data(), {charges.size()});
     448         134 :   if(root)
     449          74 :     p.cmd("setPositions",positions.data(), {masses.size(),3});
     450         134 :   if(root) {
     451          74 :     p.cmd("setForces",forces.data(),forces.size());
     452             :   }
     453         134 :   if(root)
     454          74 :     p.cmd("setVirial",&virial[0][0], {3,3});
     455             : 
     456             : 
     457         134 :   if(root)
     458        4178 :     for(unsigned i=0; i<getNumberOfAtoms(); i++) {
     459        4104 :       positions[3*i+0]=getPosition(i)[0];
     460        4104 :       positions[3*i+1]=getPosition(i)[1];
     461        4104 :       positions[3*i+2]=getPosition(i)[2];
     462             :     }
     463             : 
     464         134 :   if(root) {
     465          74 :     p.cmd("shareData");
     466             :   }
     467         134 :   if(root) {
     468          74 :     p.cmd("performCalcNoUpdate");
     469             :   }
     470             : 
     471         134 :   int s=forces.size();
     472         134 :   comm.Bcast(s,0);
     473         134 :   if(!root) {
     474          60 :     forces.resize(s);
     475             :   }
     476         134 :   comm.Bcast(forces,0);
     477         134 :   comm.Bcast(virial,0);
     478             : 
     479         134 :   double bias=0.0;
     480         134 :   if(root) {
     481          74 :     p.cmd("getBias",&bias);
     482             :   }
     483         134 :   comm.Bcast(bias,0);
     484         134 :   getPntrToComponent("bias")->set(bias);
     485         134 : }
     486             : 
     487         104 : void Plumed::apply() {
     488         104 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     489         104 :   std::vector<double> fforces( forces.size() + 9, 0 );
     490       19580 :   for(unsigned i=0; i<forces.size(); i++) {
     491       19476 :     fforces[i] += forces[i];
     492             :   }
     493         416 :   for(unsigned i=0; i<3; ++i)
     494        1248 :     for(unsigned j=0; j<3; ++j) {
     495         936 :       fforces[forces.size()+3*i+j] = virial[i][j];
     496             :     }
     497         104 :   unsigned ind=0;
     498         104 :   setForcesOnAtoms( fforces, ind );
     499         104 : }
     500             : 
     501         104 : void Plumed::update() {
     502         104 :   Tools::DirectoryChanger directoryChanger(directory.c_str());
     503         104 :   if(root) {
     504          59 :     p.cmd("update");
     505             :   }
     506         104 :   comm.Bcast(stop,0);
     507         104 :   if(stop) {
     508           0 :     log<<"  Action " << getLabel()<<" asked to stop\n";
     509           0 :     plumed.stop();
     510             :   }
     511         104 : }
     512             : 
     513             : }
     514             : }

Generated by: LCOV version 1.16