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 : {
131 : /// True on root processor
132 : const bool root;
133 : /// Separate directory.
134 : const std::string directory;
135 : /// Interface to underlying plumed object.
136 : PlumedHandle p;
137 : /// API number.
138 : const int API;
139 : /// Self communicator
140 : Communicator comm_self;
141 : /// Intercommunicator
142 : Communicator intercomm;
143 : /// Detect first usage.
144 : bool first=true;
145 : /// Stop flag, used to stop e.g. in committor analysis
146 : int stop=0;
147 : /// Index of requested atoms.
148 : std::vector<int> index;
149 : /// Masses of requested atoms.
150 : std::vector<double> masses;
151 : /// Charges of requested atoms.
152 : std::vector<double> charges;
153 : /// Forces on requested atoms.
154 : std::vector<double> forces;
155 : /// Requested positions.
156 : std::vector<double> positions;
157 : /// Applied virial.
158 : Tensor virial;
159 : public:
160 : /// Constructor.
161 : explicit Plumed(const ActionOptions&);
162 : /// Documentation.
163 : static void registerKeywords( Keywords& keys );
164 : void prepare() override;
165 : void calculate() override;
166 : void apply() override;
167 : void update() override;
168 0 : unsigned getNumberOfDerivatives() override {
169 0 : return 0;
170 : }
171 92 : bool actionHasForces() override { return true; }
172 : };
173 :
174 : PLUMED_REGISTER_ACTION(Plumed,"PLUMED")
175 :
176 14 : void Plumed::registerKeywords( Keywords& keys ) {
177 14 : Action::registerKeywords( keys );
178 14 : ActionPilot::registerKeywords( keys );
179 14 : ActionAtomistic::registerKeywords( keys );
180 28 : keys.add("compulsory","STRIDE","1","stride different from 1 are not supported yet");
181 28 : keys.add("optional","FILE","input file for the guest PLUMED instance");
182 28 : keys.add("optional","KERNEL","kernel to be used for the guest PLUMED instance (USE WITH CAUTION!)");
183 28 : keys.add("optional","LOG","log file for the guest PLUMED instance. By default the host log is used");
184 28 : keys.add("optional","CHDIR","run guest in a separate directory");
185 28 : keys.addFlag("NOREPLICAS",false,"run multiple replicas as isolated ones, without letting them know that the host has multiple replicas");
186 28 : keys.addOutputComponent("bias","default","the instantaneous value of the bias potential");
187 14 : }
188 :
189 12 : Plumed::Plumed(const ActionOptions&ao):
190 : Action(ao),
191 : ActionAtomistic(ao),
192 : ActionWithValue(ao),
193 : ActionPilot(ao),
194 24 : root(comm.Get_rank()==0),
195 24 : directory([&]() {
196 : std::string directory;
197 24 : parse("CHDIR",directory);
198 12 : if(directory.length()>0) {
199 0 : log<<" running on separate directory "<<directory<<"\n";
200 : }
201 12 : return directory;
202 : }()),
203 24 : p([&]() {
204 : std::string kernel;
205 24 : parse("KERNEL",kernel);
206 12 : if(kernel.length()==0) {
207 11 : log<<" using the current kernel\n";
208 11 : return PlumedHandle();
209 : } else {
210 1 : log<<" using the kernel "<<kernel<<"\n";
211 1 : return PlumedHandle::dlopen(kernel.c_str());
212 : }
213 : }()),
214 24 : API([&]() {
215 12 : int api=0;
216 12 : p.cmd("getApiVersion",&api);
217 12 : log<<" reported API version is "<<api<<"\n";
218 : // note: this is required in order to have cmd performCalcNoUpdate and cmd update
219 : // as a matter of fact, any version <2.5 will not even load due to namespace pollution
220 12 : plumed_assert(api>3) << "API>3 is required for the PLUMED action to work correctly\n";
221 12 : return api;
222 24 : }())
223 : {
224 12 : Tools::DirectoryChanger directoryChanger(directory.c_str());
225 :
226 : bool noreplicas;
227 12 : parseFlag("NOREPLICAS",noreplicas);
228 : int nreps;
229 12 : if(root) nreps=multi_sim_comm.Get_size();
230 12 : comm.Bcast(nreps,0);
231 12 : if(nreps>1) {
232 6 : if(noreplicas) {
233 0 : log<<" running replicas as independent (no suffix used)\n";
234 : } else {
235 6 : log<<" running replicas as standard multi replic (with suffix)\n";
236 6 : if(root) {
237 6 : intercomm.Set_comm(&multi_sim_comm.Get_comm());
238 6 : p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm());
239 6 : p.cmd("GREX setMPIIntracomm",&comm_self.Get_comm());
240 3 : p.cmd("GREX init");
241 : }
242 : }
243 : } else {
244 6 : if(noreplicas) {
245 0 : log<<" WARNING: flag NOREPLICAS ignored since we are running without replicas\n";
246 : }
247 : }
248 :
249 12 : int natoms=getTotAtoms();
250 :
251 12 : plumed_assert(getStride()==1) << "currently only supports STRIDE=1";
252 :
253 12 : double dt=getTimeStep();
254 :
255 : std::string file;
256 24 : parse("FILE",file);
257 12 : if(file.length()>0) {
258 12 : log<<" with input file "<<file<<"\n";
259 0 : } else plumed_error() << "you must provide an input file\n";
260 :
261 : bool inherited_logfile=false;
262 : std::string logfile;
263 24 : parse("LOG",logfile);
264 12 : if(logfile.length()>0) {
265 0 : log<<" with log file "<<logfile<<"\n";
266 0 : if(root) p.cmd("setLogFile",logfile.c_str());
267 12 : } else if(log.getFILE()) {
268 12 : log<<" with inherited log file\n";
269 12 : if(root) p.cmd("setLog",log.getFILE());
270 : inherited_logfile=true;
271 : } else {
272 0 : log<<" with log on stdout\n";
273 0 : if(root) p.cmd("setLog",stdout);
274 : }
275 :
276 12 : checkRead();
277 :
278 12 : if(root) p.cmd("setMDEngine","plumed");
279 :
280 12 : double engunits=getUnits().getEnergy();
281 12 : if(root) p.cmd("setMDEnergyUnits",&engunits);
282 :
283 12 : double lenunits=getUnits().getLength();
284 12 : if(root) p.cmd("setMDLengthUnits",&lenunits);
285 :
286 12 : double timunits=getUnits().getTime();
287 12 : if(root) p.cmd("setMDTimeUnits",&timunits);
288 :
289 12 : double chaunits=getUnits().getCharge();
290 12 : if(root) p.cmd("setMDChargeUnits",&chaunits);
291 12 : double masunits=getUnits().getMass();
292 12 : if(root) p.cmd("setMDMassUnits",&masunits);
293 :
294 12 : double kbt=getkBT();
295 12 : if(root) p.cmd("setKbT",&kbt);
296 :
297 12 : int res=0;
298 12 : if(getRestart()) res=1;
299 12 : if(root) p.cmd("setRestart",&res);
300 :
301 12 : if(root) p.cmd("setNatoms",&natoms);
302 12 : if(root) p.cmd("setTimestep",&dt);
303 12 : if(root) p.cmd("setPlumedDat",file.c_str());
304 :
305 24 : addComponentWithDerivatives("bias");
306 12 : componentIsNotPeriodic("bias");
307 :
308 12 : if(inherited_logfile) log<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
309 12 : if(root) p.cmd("init");
310 12 : if(inherited_logfile) log<<"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
311 12 : }
312 :
313 164 : void Plumed::prepare() {
314 164 : Tools::DirectoryChanger directoryChanger(directory.c_str());
315 164 : int step=getStep();
316 164 : if(root) p.cmd("setStep",&step);
317 164 : if(root) p.cmd("prepareDependencies");
318 164 : int ene=0;
319 164 : if(root) p.cmd("isEnergyNeeded",&ene);
320 164 : if(ene) plumed_error()<<"It is not currently possible to use ENERGY in a guest PLUMED";
321 164 : int n=0;
322 164 : if(root) p.cmd("createFullList",&n);
323 164 : const int *pointer=nullptr;
324 164 : if(root) p.cmd("getFullList",&pointer);
325 164 : bool redo=(index.size()!=n);
326 164 : if(first) redo=true;
327 164 : first=false;
328 4409 : if(root && !redo) for(int i=0; i<n; i++) if(index[i]!=pointer[i]) { redo=true; break;};
329 164 : if(root && redo) {
330 22 : index.resize(n);
331 22 : masses.resize(n);
332 22 : forces.resize(3*n);
333 22 : positions.resize(3*n);
334 22 : charges.resize(n);
335 1043 : for(int i=0; i<n; i++) {
336 1021 : index[i]=pointer[i];
337 : };
338 22 : p.cmd("setAtomsNlocal",&n);
339 22 : p.cmd("setAtomsGatindex",index.data(), {index.size()});
340 : }
341 164 : if(root) p.cmd("clearFullList");
342 164 : int tmp=0;
343 164 : if(root && redo) {
344 22 : tmp=1;
345 : }
346 164 : comm.Bcast(tmp,0);
347 164 : if(tmp) {
348 34 : int s=index.size();
349 34 : comm.Bcast(s,0);
350 34 : if(!root) index.resize(s);
351 34 : comm.Bcast(index,0);
352 : std::vector<AtomNumber> numbers;
353 34 : numbers.reserve(index.size());
354 2138 : for(auto i : index) numbers.emplace_back(AtomNumber::index(i));
355 34 : requestAtoms(numbers);
356 : }
357 164 : }
358 :
359 134 : void Plumed::calculate() {
360 134 : Tools::DirectoryChanger directoryChanger(directory.c_str());
361 134 : if(root) p.cmd("setStopFlag",&stop);
362 134 : Tensor box=getPbc().getBox();
363 134 : if(root) p.cmd("setBox",&box[0][0], {3,3});
364 :
365 134 : virial.zero();
366 24875 : for(int i=0; i<forces.size(); i++) forces[i]=0.0;
367 4238 : for(int i=0; i<masses.size(); i++) masses[i]=getMass(i);
368 4238 : for(int i=0; i<charges.size(); i++) charges[i]=getCharge(i);
369 :
370 134 : if(root) p.cmd("setMasses",masses.data(), {masses.size()});
371 134 : if(root) p.cmd("setCharges",charges.data(), {charges.size()});
372 134 : if(root) p.cmd("setPositions",positions.data(), {masses.size(),3});
373 134 : if(root) p.cmd("setForces",forces.data(),forces.size());
374 134 : if(root) p.cmd("setVirial",&virial[0][0], {3,3});
375 :
376 :
377 4238 : if(root) for(unsigned i=0; i<getNumberOfAtoms(); i++) {
378 4104 : positions[3*i+0]=getPosition(i)[0];
379 4104 : positions[3*i+1]=getPosition(i)[1];
380 4104 : positions[3*i+2]=getPosition(i)[2];
381 : }
382 :
383 134 : if(root) p.cmd("shareData");
384 134 : if(root) p.cmd("performCalcNoUpdate");
385 :
386 134 : int s=forces.size();
387 134 : comm.Bcast(s,0);
388 134 : if(!root) forces.resize(s);
389 134 : comm.Bcast(forces,0);
390 134 : comm.Bcast(virial,0);
391 :
392 134 : double bias=0.0;
393 134 : if(root) p.cmd("getBias",&bias);
394 134 : comm.Bcast(bias,0);
395 134 : getPntrToComponent("bias")->set(bias);
396 134 : }
397 :
398 104 : void Plumed::apply() {
399 104 : Tools::DirectoryChanger directoryChanger(directory.c_str());
400 104 : std::vector<double> fforces( forces.size() + 9, 0 );
401 19580 : for(unsigned i=0; i<forces.size(); i++) fforces[i] += forces[i];
402 1352 : for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) fforces[forces.size()+3*i+j] = virial[i][j];
403 104 : unsigned ind=0; setForcesOnAtoms( fforces, ind );
404 104 : }
405 :
406 104 : void Plumed::update() {
407 104 : Tools::DirectoryChanger directoryChanger(directory.c_str());
408 104 : if(root) p.cmd("update");
409 104 : comm.Bcast(stop,0);
410 104 : if(stop) {
411 0 : log<<" Action " << getLabel()<<" asked to stop\n";
412 0 : plumed.stop();
413 : }
414 104 : }
415 :
416 : }
417 : }
|