Line data Source code
1 : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 : Copyright (c) 2011-2023 The plumed team
3 : (see the PEOPLE file at the root of the distribution for a list of names)
4 :
5 : See http://www.plumed.org for more information.
6 :
7 : This file is part of plumed, version 2.
8 :
9 : plumed is free software: you can redistribute it and/or modify
10 : it under the terms of the GNU Lesser General Public License as published by
11 : the Free Software Foundation, either version 3 of the License, or
12 : (at your option) any later version.
13 :
14 : plumed is distributed in the hope that it will be useful,
15 : but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : GNU Lesser General Public License for more details.
18 :
19 : You should have received a copy of the GNU Lesser General Public License
20 : along with plumed. If not, see <http://www.gnu.org/licenses/>.
21 : +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
22 : #ifndef __PLUMED_core_PlumedMain_h
23 : #define __PLUMED_core_PlumedMain_h
24 :
25 : #include "WithCmd.h"
26 : #include "tools/ForwardDecl.h"
27 : #include <cstdio>
28 : #include <string>
29 : #include <vector>
30 : #include <set>
31 : #include <stack>
32 : #include <memory>
33 : #include <map>
34 : #include <atomic>
35 :
36 : // !!!!!!!!!!!!!!!!!!!!!! DANGER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11
37 : // THE FOLLOWING ARE DEFINITIONS WHICH ARE NECESSARY FOR DYNAMIC LOADING OF THE PLUMED KERNEL:
38 : // This section should be consistent with the Plumed.h file.
39 : // Since the Plumed.h file may be included in host MD codes, **NEVER** MODIFY THE CODE DOWN HERE
40 :
41 : /* Generic function pointer */
42 : typedef void (*plumed_function_pointer)(void);
43 :
44 : /* Holder for function pointer */
45 : typedef struct {
46 : plumed_function_pointer p;
47 : } plumed_function_holder;
48 :
49 : // END OF DANGER
50 : ////////////////////////////////////////////////////////////
51 :
52 : namespace PLMD {
53 :
54 :
55 :
56 : class ActionAtomistic;
57 : class ActionPilot;
58 : class ActionForInterface;
59 : class Log;
60 : class Atoms;
61 : class ActionSet;
62 : class DLLoader;
63 : class Communicator;
64 : class Stopwatch;
65 : class Citations;
66 : class ExchangePatterns;
67 : class FileBase;
68 : class TypesafePtr;
69 : class IFile;
70 : class Units;
71 : class Keywords;
72 : class DataPassingTools;
73 :
74 : /**
75 : Main plumed object.
76 : In MD engines this object is not manipulated directly but it is wrapped in
77 : plumed or PLMD::Plumed objects. Its main method is cmd(),
78 : which defines completely the external plumed interface.
79 : It does not contain any static data.
80 : */
81 : class PlumedMain:
82 : public WithCmd {
83 : /// Pointers to files opened in actions associated to this object.
84 : /// Notice that with the current implementation this should be at the top of this
85 : /// structure. Indeed, this should be destroyed *after* all the actions allocated
86 : /// in this PlumedMain object have been destroyed.
87 : std::set<FileBase*> files;
88 : /// Forward declaration.
89 : ForwardDecl<Communicator> comm_fwd;
90 : public:
91 : /// Communicator for plumed.
92 : /// Includes all the processors used by plumed in this replica.
93 : /// See Action::comm.
94 : Communicator&comm=*comm_fwd;
95 :
96 : private:
97 : class DeprecatedAtoms {
98 : private:
99 : PlumedMain & plumed;
100 : public:
101 807846 : explicit DeprecatedAtoms(PlumedMain& p): plumed(p) {}
102 : [[deprecated("Use Action::getKBoltzmann().")]]
103 : double getKBoltzmann() const ;
104 : [[deprecated("Use Action::getkBT() N.B. this function also reads the TEMP keyword from the input for you.")]]
105 : double getKbT() const ;
106 : [[deprecated]]
107 : int getNatoms() const ;
108 : [[deprecated("Use Action::usingNaturalUnits().")]]
109 : bool usingNaturalUnits() const ;
110 : [[deprecated]]
111 : void setCollectEnergy(bool b) const;
112 : [[deprecated]]
113 : double getEnergy() const ;
114 : };
115 : /// Forward declaration.
116 : ForwardDecl<DeprecatedAtoms> datoms_fwd;
117 : /// Object containing old bits of atoms that are used by many folks
118 : DeprecatedAtoms& datoms=*datoms_fwd;
119 : /// Forward declaration.
120 : ForwardDecl<Communicator> multi_sim_comm_fwd;
121 : public:
122 : DeprecatedAtoms& getAtoms();
123 : /// Communicator between replicas.
124 : /// Valid only on process 0 of comm; MPI_COMM_SELF elsewhere.
125 : /// See Action::multi_sim_comm.
126 : Communicator&multi_sim_comm=*multi_sim_comm_fwd;
127 :
128 : private:
129 : /// Error handler.
130 : /// Pointer to a function that is called an exception thrown within
131 : /// the library is about to leave the library.
132 : /// Can be used to remap exceptions in case the plumed wrapper was compiled
133 : /// with a different version of the C++ standard library.
134 : /// Should only be called from \ref plumed_plumedmain_cmd().
135 : typedef struct {
136 : void* ptr;
137 : void(*handler)(void* ptr,int code,const char*);
138 : } plumed_error_handler;
139 :
140 : plumed_error_handler error_handler= {NULL,NULL};
141 :
142 : bool nestedExceptions=false;
143 :
144 : /// Forward declaration.
145 : ForwardDecl<DLLoader> dlloader_fwd;
146 : DLLoader& dlloader=*dlloader_fwd;
147 :
148 : std::unique_ptr<WithCmd> cltool;
149 :
150 : std::unique_ptr<WithCmd> grex;
151 : /// Flag to avoid double initialization
152 : bool initialized=false;
153 : /// Name of MD engine
154 : std::string MDEngine{"mdcode"};
155 :
156 : /// Forward declaration.
157 : ForwardDecl<Log> log_fwd;
158 : /// Log stream
159 : Log& log=*log_fwd;
160 :
161 : /// Forward declaration.
162 : /// Should be placed after log since its constructor takes a log reference as an argument.
163 : ForwardDecl<Stopwatch> stopwatch_fwd;
164 : Stopwatch& stopwatch=*stopwatch_fwd;
165 :
166 : /// Forward declaration.
167 : ForwardDecl<Citations> citations_fwd;
168 : /// tools/Citations.holder
169 : Citations& citations=*citations_fwd;
170 :
171 : /// Present step number.
172 : long long int step=0;
173 :
174 : /// Condition for plumed to be active.
175 : /// At every step, PlumedMain is checking if there are Action's requiring some work.
176 : /// If at least one Action requires some work, this variable is set to true.
177 : bool active=false;
178 :
179 : /// Name of the input file
180 : std::string plumedDat;
181 :
182 : /// End of input file.
183 : /// Set to true to terminate reading
184 : bool endPlumed=false;
185 :
186 : /// Forward declaration.
187 : ForwardDecl<ActionSet> actionSet_fwd;
188 : /// Set of actions found in plumed.dat file
189 : ActionSet& actionSet=*actionSet_fwd;
190 :
191 : /// These are tools to pass data to PLUMED
192 : std::unique_ptr<DataPassingTools> passtools;
193 :
194 : /// Vector of actions that are passed data from the MD code
195 : std::vector<ActionForInterface*> inputs;
196 :
197 : /// Set of Pilot actions.
198 : /// These are the action the, if they are Pilot::onStep(), can trigger execution
199 : std::vector<ActionPilot*> pilots;
200 :
201 : /// Suffix string for file opening, useful for multiple simulations in the same directory
202 : std::string suffix;
203 :
204 : /// The total bias (=total energy of the restraints)
205 : double bias=0.0;
206 :
207 : /// The total work.
208 : /// This computed by accumulating the change in external potentials.
209 : double work=0.0;
210 :
211 : /// Forward declaration.
212 : ForwardDecl<ExchangePatterns> exchangePatterns_fwd;
213 : /// Class of possible exchange patterns, used for BIASEXCHANGE but also for future parallel tempering
214 : ExchangePatterns& exchangePatterns=*exchangePatterns_fwd;
215 :
216 : /// Set to true if on an exchange step
217 : bool exchangeStep=false;
218 :
219 : /// Flag for restart
220 : bool restart=false;
221 :
222 : /// Flag for checkpointig
223 : bool doCheckPoint=false;
224 :
225 : /// A string that holds the name of the action that gets the energy from the MD
226 : /// code. Set empty if energy is not used.
227 : std::string name_of_energy{""};
228 :
229 : /// This sets up the values that are set from the MD code
230 : void startStep();
231 :
232 : /// This sets up the vector that contains the interface to the MD code
233 : void setupInterfaceActions();
234 :
235 : /// Flag for parse only mode -- basically just forces restart to turn off
236 : bool doParseOnly=false;
237 :
238 : private:
239 : /// Forward declaration.
240 : ForwardDecl<TypesafePtr> stopFlag_fwd;
241 : public:
242 : /// Stuff to make plumed stop the MD code cleanly
243 : TypesafePtr& stopFlag=*stopFlag_fwd;
244 : bool stopNow=false;
245 :
246 : /// Stack for update flags.
247 : /// Store information used in class \ref generic::UpdateIf
248 : std::stack<bool> updateFlags;
249 :
250 : public:
251 : /// This determines if the user has created a value to hold the quantity that is being passed
252 : bool valueExists( const std::string& name ) const ;
253 :
254 : /// This sets the the value with a particular name to the pointer to the data in the MD code
255 : void setInputValue( const std::string& name, const unsigned& start, const unsigned& stride, const TypesafePtr & val );
256 :
257 : /// This sets the the forces with a particular name to the pointer to the data in the MD code
258 : void setInputForce( const std::string& name, const TypesafePtr & val );
259 :
260 : /// This updates the units of the input quantities
261 : void setUnits( const bool& natural, const Units& u );
262 :
263 : /// Flag to switch off virial calculation (for debug and MD codes with no barostat)
264 : bool novirial=false;
265 :
266 : /// Flag to switch on detailed timers
267 : bool detailedTimers=false;
268 :
269 : /// GpuDevice Identifier
270 : int gpuDeviceId=-1;
271 :
272 : /// Generic map string -> double
273 : /// intended to pass information across Actions
274 : std::map<std::string,double> passMap;
275 :
276 : /// Add a citation, returning a string containing the reference number, something like "[10]"
277 : std::string cite(const std::string&);
278 :
279 : /// Get number of threads that can be used by openmp
280 : unsigned getNumThreads()const;
281 :
282 : /// Get a reasonable number of threads so as to access to an array of size s located at x
283 : template<typename T>
284 : unsigned getGoodNumThreads(const T*x,unsigned s)const;
285 :
286 : /// Get a reasonable number of threads so as to access to vector v;
287 : template<typename T>
288 : unsigned getGoodNumThreads(const std::vector<T> & v)const;
289 :
290 : public:
291 : PlumedMain();
292 : // this is to access to WithCmd versions of cmd (allowing overloading of a virtual method)
293 : using WithCmd::cmd;
294 : /**
295 : cmd method, accessible with standard Plumed.h interface.
296 : \param key The name of the command to be executed.
297 : \param val The argument of the command to be executed.
298 : It is called as plumed_cmd() or as PLMD::Plumed::cmd()
299 : It is the interpreter for plumed commands. It basically contains the definition of the plumed interface.
300 : If you want to add a new functionality to the interface between plumed
301 : and an MD engine, this is the right place
302 : Notice that this interface should always keep retro-compatibility
303 : */
304 : void cmd(std::string_view key,const TypesafePtr & val) override;
305 : ~PlumedMain();
306 : /**
307 : Turn on parse only mode to deactivate restart in all actions.
308 : This is only used by plumed driver --parse-only
309 : */
310 : void activateParseOnlyMode();
311 : /**
312 : This checks if parse only mode is active and turns off any restart.
313 : */
314 : bool parseOnlyMode() const ;
315 : /**
316 : Read an input file.
317 : \param str name of the file
318 : */
319 : void readInputFile(const std::string & str);
320 : /**
321 : Read an input file.
322 : \param ifile
323 : */
324 : void readInputFile(IFile & ifile);
325 : /**
326 : Read an input string.
327 : \param str name of the string
328 : */
329 : void readInputWords(const std::vector<std::string> & str, const bool& before_init);
330 :
331 : /**
332 : Read an input string.
333 : \param str name of the string
334 : At variance with readInputWords(), this is splitting the string into words
335 : */
336 : void readInputLine(const std::string & str, const bool& before_init=false);
337 :
338 : /**
339 : Read an input buffer.
340 : \param str name of the string
341 : Same as readInputFile, but first write str on a temporary file and then read
342 : that files. At variance with readInputLine, it can take care of comments and
343 : continuation lines.
344 : */
345 : void readInputLines(const std::string & str);
346 :
347 : /**
348 : Initialize the object.
349 : Should be called once.
350 : */
351 : void init();
352 : /**
353 : Prepare the calculation.
354 : Here it is checked which are the active Actions and communication of the relevant atoms is initiated.
355 : Shortcut for prepareDependencies() + shareData()
356 : */
357 : void prepareCalc();
358 : /**
359 : Prepare the list of active Actions and needed atoms.
360 : Scan the Actions to see which are active and which are not, so as to prepare a list of
361 : the atoms needed at this step.
362 : */
363 : void prepareDependencies();
364 : /**
365 : Ensure that all the atoms are shared.
366 : This is used in GREX to ensure that we transfer all the positions from the MD code to PLUMED.
367 : */
368 : void shareAll();
369 : /**
370 : Share the needed atoms.
371 : In asynchronous implementations, this method sends the required atoms to all the plumed processes,
372 : without waiting for the communication to complete.
373 : */
374 : void shareData();
375 : /**
376 : Perform the calculation.
377 : Shortcut for waitData() + justCalculate() + justApply().
378 : Equivalently: waitData() + justCalculate() + backwardPropagate() + update().
379 : */
380 : void performCalc();
381 : /**
382 : Perform the calculation without update()
383 : Shortcut for: waitData() + justCalculate() + backwardPropagate()
384 : */
385 : void performCalcNoUpdate();
386 : /**
387 : Perform the calculation without backpropagation nor update()
388 : Shortcut for: waitData() + justCalculate()
389 : */
390 : void performCalcNoForces();
391 : /**
392 : Complete PLUMED calculation.
393 : Shortcut for prepareCalc() + performCalc()
394 : */
395 : void calc();
396 : /**
397 : Scatters the needed atoms.
398 : In asynchronous implementations, this method waits for the communications started in shareData()
399 : to be completed. Otherwise, just send around needed atoms.
400 : */
401 : void waitData();
402 : /**
403 : Perform the forward loop on active actions.
404 : */
405 : void justCalculate();
406 : /**
407 : Backward propagate and update.
408 : Shortcut for backwardPropagate() + update()
409 : I leave it here for backward compatibility
410 : */
411 : void justApply();
412 : /**
413 : Perform the backward loop on active actions.
414 : Needed to apply the forces back.
415 : */
416 : void backwardPropagate();
417 : /**
418 : Call the update() method.
419 : */
420 : void update();
421 : /**
422 : If there are calculations that need to be done at the very end of the calculations this
423 : makes sures they are done
424 : */
425 : /**
426 : This function does clearInputForces for the list of atoms that have a force on them. This
427 : is an optimisation to prevent calling std::fill over a large array
428 : */
429 : void resetInputs();
430 : void runJobsAtEndOfCalculation();
431 : /// Reference to the list of Action's
432 : const ActionSet & getActionSet()const;
433 : /// Referenge to the log stream
434 : Log & getLog();
435 : /// Return the number of the step
436 : long long int getStep()const {
437 6373239 : return step;
438 : }
439 : /// Stop the run
440 : void exit(int c=0);
441 : /// Load a shared library
442 : void load(const std::string&);
443 : /// Get the suffix string
444 : const std::string & getSuffix()const;
445 : /// Set the suffix string
446 : void setSuffix(const std::string&);
447 : /// get the value of the bias
448 : double getBias()const;
449 : /// get the value of the work
450 : double getWork()const;
451 : /// Opens a file.
452 : /// Similar to plain fopen, but, if it finds an error in opening the file, it also tries with
453 : /// path+suffix. This trick is useful for multiple replica simulations.
454 : FILE* fopen(const char *path, const char *mode);
455 : /// Closes a file opened with PlumedMain::fopen()
456 : int fclose(FILE*fp);
457 : /// Insert a file
458 : void insertFile(FileBase&);
459 : /// Erase a file
460 : void eraseFile(FileBase&);
461 : /// Get the files currently registered with insertFile()
462 : const std::set<FileBase*> & getFiles()const {
463 : return files;
464 : }
465 : /// Flush all files
466 : void fflush();
467 : /// Check if restarting
468 : bool getRestart()const;
469 : /// Set restart flag
470 : void setRestart(bool f) {
471 58 : if(!doParseOnly) {
472 58 : restart=f;
473 : }
474 : }
475 : /// Check if checkpointing
476 : bool getCPT()const;
477 : /// Set exchangeStep flag
478 : void setExchangeStep(bool f);
479 : /// Get exchangeStep flag
480 : bool getExchangeStep()const;
481 : /// Stop the calculation cleanly (both the MD code and plumed)
482 : void stop();
483 : /// Enforce active flag.
484 : /// This is a (bit dirty) hack to solve a bug. When there is no active ActionPilot,
485 : /// several shortcuts are used. However, these shortcuts can block GREX module.
486 : /// This function allows to enforce active plumed when doing exchanges,
487 : /// thus fixing the bug.
488 : void resetActive(bool active);
489 :
490 : /// Access to exchange patterns
491 : ExchangePatterns& getExchangePatterns() {
492 0 : return exchangePatterns;
493 : }
494 :
495 : /// Push a state to update flags
496 : void updateFlagsPush(bool);
497 : /// Pop a state from update flags
498 : void updateFlagsPop();
499 : /// Get top of update flags
500 : bool updateFlagsTop();
501 : /// Set end of input file
502 : void setEndPlumed();
503 : /// Get the value of the end plumed flag
504 : bool getEndPlumed() const ;
505 : /// Get the value of the gpuDeviceId
506 : int getGpuDeviceId() const ;
507 : /// Call error handler.
508 : /// Should only be called from \ref plumed_plumedmain_cmd().
509 : /// If the error handler was not set, returns false.
510 : bool callErrorHandler(int code,const char* msg)const;
511 : private:
512 : std::atomic<unsigned> referenceCounter{};
513 : public:
514 : /// Atomically increase reference counter and return the new value
515 : unsigned increaseReferenceCounter() noexcept;
516 : /// Atomically decrease reference counter and return the new value
517 : unsigned decreaseReferenceCounter() noexcept;
518 : /// Report the reference counter
519 : unsigned useCountReferenceCounter() const noexcept;
520 : void enableNestedExceptions();
521 : bool getNestedExceptions()const {
522 183 : return nestedExceptions;
523 : }
524 : /// Check if there is active input in the action set
525 : bool inputsAreActive() const ;
526 : /// Transfer information from input MD code
527 : void writeBinary(std::ostream&)const;
528 : void readBinary(std::istream&);
529 : /// Used to set the name of the action that holds the energy
530 : void setEnergyValue( const std::string& name );
531 : /// Get the real preicision
532 : int getRealPrecision() const;
533 : /// Are we using natural units
534 : bool usingNaturalUnits() const ;
535 : /// Get the units that are being used
536 : const Units& getUnits();
537 : /// Take an energy that is calculated by PLUMED and pass it to a typesafe pointer
538 : /// that the MD code can access.
539 : void plumedQuantityToMD( const std::string& unit, const double& eng, const TypesafePtr & m) const ;
540 : /// Take a typesafe pointer from the MD code and convert it to a double
541 : double MDQuantityToPLUMED( const std::string& unit, const TypesafePtr & m) const ;
542 : /// Get the keywords for a particular action
543 : void getKeywordsForAction( const std::string& action, Keywords& keys ) const ;
544 : };
545 :
546 : /////
547 : // FAST INLINE METHODS:
548 :
549 : inline
550 : const ActionSet & PlumedMain::getActionSet()const {
551 1574913 : return actionSet;
552 : }
553 :
554 : inline
555 : const std::string & PlumedMain::getSuffix()const {
556 5558 : return suffix;
557 : }
558 :
559 : inline
560 : void PlumedMain::setSuffix(const std::string&s) {
561 703 : suffix=s;
562 703 : }
563 :
564 : inline
565 : bool PlumedMain::getRestart()const {
566 55531 : return restart;
567 : }
568 :
569 : inline
570 : bool PlumedMain::getCPT()const {
571 55473 : return doCheckPoint;
572 : }
573 :
574 : inline
575 : void PlumedMain::setExchangeStep(bool s) {
576 228 : exchangeStep=s;
577 : }
578 :
579 : inline
580 : bool PlumedMain::getExchangeStep()const {
581 44038 : return exchangeStep;
582 : }
583 :
584 : inline
585 : void PlumedMain::resetActive(bool active) {
586 114 : this->active=active;
587 : }
588 :
589 : inline
590 : void PlumedMain::updateFlagsPush(bool on) {
591 : updateFlags.push(on);
592 : }
593 :
594 : inline
595 : void PlumedMain::updateFlagsPop() {
596 : updateFlags.pop();
597 12 : }
598 :
599 : inline
600 : bool PlumedMain::updateFlagsTop() {
601 3262980 : return updateFlags.top();
602 : }
603 :
604 : inline
605 : void PlumedMain::setEndPlumed() {
606 302 : endPlumed=true;
607 : }
608 :
609 : inline
610 : bool PlumedMain::getEndPlumed() const {
611 24 : return endPlumed;
612 : }
613 :
614 : inline
615 : int PlumedMain::getGpuDeviceId() const {
616 : return gpuDeviceId;
617 : }
618 :
619 : inline
620 : bool PlumedMain::callErrorHandler(int code,const char* msg)const {
621 : if(error_handler.handler) {
622 : error_handler.handler(error_handler.ptr,code,msg);
623 : return true;
624 : } else {
625 : return false;
626 : }
627 : }
628 :
629 :
630 : }
631 :
632 : #endif
633 :
|