268465463bace2c03800f307b1600ed891759fc5
[alexxy/gromacs.git] / src / gromacs / mdrun / runner.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2017,2018,2019,2020, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS 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 GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \libinternal \file
36  *
37  * \brief Declares the routine running the inetgrators.
38  *
39  * \author David van der Spoel <david.vanderspoel@icm.uu.se>
40  * \ingroup module_mdrun
41  */
42 #ifndef GMX_MDRUN_RUNNER_H
43 #define GMX_MDRUN_RUNNER_H
44
45 #include <cstdio>
46
47 #include <array>
48 #include <memory>
49
50 #include "gromacs/commandline/filenm.h"
51 #include "gromacs/compat/pointers.h"
52 #include "gromacs/domdec/options.h"
53 #include "gromacs/hardware/hw_info.h"
54 #include "gromacs/math/vec.h"
55 #include "gromacs/mdrun/mdmodules.h"
56 #include "gromacs/mdrunutility/handlerestart.h"
57 #include "gromacs/mdtypes/mdrunoptions.h"
58 #include "gromacs/utility/arrayref.h"
59 #include "gromacs/utility/basedefinitions.h"
60 #include "gromacs/utility/gmxmpi.h"
61 #include "gromacs/utility/real.h"
62
63 #include "replicaexchange.h"
64
65 struct gmx_multisim_t;
66 struct gmx_output_env_t;
67 struct ReplicaExchangeParameters;
68 struct t_fileio;
69
70 namespace gmx
71 {
72
73 // Todo: move to forward declaration headers...
74 class MDModules;
75 class IRestraintPotential; // defined in restraint/restraintpotential.h
76 class RestraintManager;
77 class SimulationContext;
78 class StopHandlerBuilder;
79
80 /*! \libinternal \brief Runner object for supporting setup and execution of mdrun.
81  *
82  * This class has responsibility for the lifetime of data structures
83  * that exist for the life of the simulation, e.g. for logging and
84  * communication.
85  *
86  * It is also responsible for initializing data members that
87  * e.g. correspond to values potentially set by commmand-line
88  * options. Later these will be obtained directly from modules, and
89  * the results of command-line option handling returned directly to
90  * the modules, rather than propagated to them by data members of this
91  * class.
92  *
93  * \todo Most of the attributes should be declared by specific modules
94  * as command-line options. Accordingly, they do not conform to the
95  * naming scheme, because that would make for a lot of noise in the
96  * diff, only to have it change again when the options move to their
97  * modules.
98  *
99  * \todo Preparing logging and MPI contexts could probably be a
100  * higher-level responsibility, so that an Mdrunner would get made
101  * without needing to re-initialize these components (as currently
102  * happens always for the master rank, and differently for the spawned
103  * ranks with thread-MPI).
104  *
105  * \ingroup module_mdrun
106  */
107 class Mdrunner
108 {
109 public:
110     /*! \brief Builder class to manage object creation.
111      *
112      * This class is a member of gmx::Mdrunner so that it can initialize
113      * private members of gmx::Mdrunner.
114      *
115      * It is non-trivial to establish an initialized gmx::Mdrunner invariant,
116      * so objects can be obtained by clients using a Builder or a move.
117      * Clients cannot default initialize or copy gmx::Mdrunner.
118      */
119     class BuilderImplementation;
120
121     ~Mdrunner();
122
123     /*!
124      * \brief Copy not allowed.
125      *
126      * An Mdrunner has unique resources and it is not clear whether any of
127      * one of those resources should be duplicated or shared unless the
128      * specific use case is known. Either build a fresh runner or use a
129      * helper function for clearly indicated behavior. API clarification may
130      * allow unambiguous initialization by copy in future versions.
131      *
132      * \{
133      */
134     Mdrunner(const Mdrunner&) = delete;
135     Mdrunner& operator=(const Mdrunner&) = delete;
136     /* \} */
137
138     /*!
139      * \brief Mdrunner objects can be passed by value via move semantics.
140      *
141      * \param handle runner instance to be moved from.
142      * \{
143      */
144     Mdrunner(Mdrunner&& handle) noexcept;
145     Mdrunner& operator=(Mdrunner&& handle) noexcept;
146     /* \} */
147
148     /*! \brief Driver routine, that calls the different simulation methods. */
149     /*!
150      * Currently, thread-MPI does not spawn threads until during mdrunner() and parallelism
151      * is not initialized until some time during this call...
152      */
153     int mdrunner();
154
155     /*!
156      * \brief Add a potential to be evaluated during MD integration.
157      *
158      * \param restraint MD restraint potential to apply
159      * \param name User-friendly plain-text name to uniquely identify the puller
160      *
161      * This implementation attaches an object providing the gmx::IRestraintPotential
162      * interface.
163      * \todo Mdrunner should fetch such resources from the SimulationContext
164      * rather than offering this public interface.
165      */
166     void addPotential(std::shared_ptr<IRestraintPotential> restraint, const std::string& name);
167
168     /*! \brief Prepare the thread-MPI communicator to have \c
169      * numThreadsToLaunch ranks, by spawning new thread-MPI
170      * threads.
171      *
172      * Called by mdrunner() to start a specific number of threads
173      * (including the main thread) for thread-parallel runs. This
174      * in turn calls mdrunner() for each thread. */
175     void spawnThreads(int numThreadsToLaunch);
176
177     /*! \brief Initializes a new Mdrunner from the master.
178      *
179      * Run this method in a new thread from a master runner to get additional
180      * workers on spawned threads.
181      *
182      * \returns New Mdrunner instance suitable for thread-MPI work on new ranks.
183      *
184      * \internal
185      * \todo clarify (multiple) invariants during MD runner start-up.
186      * The runner state before and after launching threads is distinct enough that
187      * it should be codified in the invariants of different classes. That would
188      * mean that the object returned by this method would be of a different type
189      * than the object held by the client up to the point of call, and its name
190      * would be changed to "launchOnSpawnedThread" or something not including the
191      * word "clone".
192      */
193     Mdrunner cloneOnSpawnedThread() const;
194
195 private:
196     /*! \brief Constructor. */
197     explicit Mdrunner(std::unique_ptr<MDModules> mdModules);
198
199     //! Parallelism-related user options.
200     gmx_hw_opt_t hw_opt;
201
202     //! Filenames and properties from command-line argument values.
203     ArrayRef<const t_filenm> filenames;
204
205     /*! \brief Output context for writing text files
206      *
207      * \internal
208      * \todo push this data member down when the information can be queried from an encapsulated resource.
209      */
210     gmx_output_env_t* oenv = nullptr;
211     //! Ongoing collection of mdrun options
212     MdrunOptions mdrunOptions;
213     //! Options for the domain decomposition.
214     DomdecOptions domdecOptions;
215
216     /*! \brief Target short-range interations for "cpu", "gpu", or "auto". Default is "auto".
217      *
218      * \internal
219      * \todo replace with string or enum class and initialize with sensible value.
220      */
221     const char* nbpu_opt = nullptr;
222
223     /*! \brief Target long-range interactions for "cpu", "gpu", or "auto". Default is "auto".
224      *
225      * \internal
226      * \todo replace with string or enum class and initialize with sensible value.
227      */
228     const char* pme_opt = nullptr;
229
230     /*! \brief Target long-range interactions FFT/solve stages for "cpu", "gpu", or "auto". Default is "auto".
231      *
232      * \internal
233      * \todo replace with string or enum class and initialize with sensible value.
234      */
235     const char* pme_fft_opt = nullptr;
236
237     /*! \brief Target bonded interations for "cpu", "gpu", or "auto". Default is "auto".
238      *
239      * \internal
240      * \todo replace with string or enum class and initialize with sensible value.
241      */
242     const char* bonded_opt = nullptr;
243
244     /*! \brief Target update calculation for "cpu", "gpu", or "auto". Default is "auto".
245      *
246      * \internal
247      * \todo replace with string or enum class and initialize with sensible value.
248      */
249     const char* update_opt = nullptr;
250
251     //! Command-line override for the duration of a neighbor list with the Verlet scheme.
252     int nstlist_cmdline = 0;
253     //! Parameters for replica-exchange simulations.
254     ReplicaExchangeParameters replExParams;
255     //! Print a warning if any force is larger than this (in kJ/mol nm).
256     real pforce = -1;
257
258     //! Handle to file used for logging.
259     LogFilePtr logFileGuard = nullptr;
260     //! \brief Non-owning handle to file used for logging.
261     t_fileio* logFileHandle = nullptr;
262
263     /*! \brief Non-owning handle to communication data structure.
264      *
265      * With real MPI, gets a value from the SimulationContext
266      * supplied to the MdrunnerBuilder. With thread-MPI gets a
267      * value after threads have been spawned. */
268     MPI_Comm communicator = MPI_COMM_NULL;
269
270     //! \brief Non-owning handle to multi-simulation handler.
271     gmx_multisim_t* ms = nullptr;
272
273     //! Whether the simulation will start afresh, or restart with/without appending.
274     StartingBehavior startingBehavior = StartingBehavior::NewSimulation;
275
276     /*!
277      * \brief Handle to restraints manager for the current process.
278      *
279      * \internal
280      * Use opaque pointer for this implementation detail.
281      */
282     std::unique_ptr<RestraintManager> restraintManager_;
283
284     /*!
285      * \brief Builder for stop signal handler
286      *
287      * Optionally provided through MdrunnerBuilder. Client may create a
288      * StopHandlerBuilder and register any number of signal providers before
289      * launching the Mdrunner.
290      *
291      * Default is an empty signal handler that will have local signal issuers
292      * added after being passed into the integrator.
293      *
294      * \internal
295      * We do not need a full type specification here, so we use an opaque pointer.
296      */
297     std::unique_ptr<StopHandlerBuilder> stopHandlerBuilder_;
298     //! The modules that comprise mdrun.
299     std::unique_ptr<MDModules> mdModules_;
300 };
301
302 /*! \libinternal
303  * \brief Build a gmx::Mdrunner.
304  *
305  * Client code (such as `gmx mdrun`) uses this builder to get an initialized Mdrunner.
306  *
307  * A builder allows the library to ensure that client code cannot obtain an
308  * uninitialized or partially initialized runner by refusing to build() if the
309  * client has not provided sufficient or self-consistent direction. Director
310  * code can be implemented for different user interfaces, encapsulating any
311  * run-time functionality that does not belong in the library MD code, such
312  * as command-line option processing or interfacing to external libraries.
313  *
314  * \ingroup module_mdrun
315  *
316  * \internal
317  *
318  * The initial Builder implementation is neither extensible at run time nor
319  * at compile time. Future implementations should evolve to compose the runner,
320  * rather than just consolidating the parameters for initialization, but there
321  * is not yet a firm design for how flexibly module code will be coupled to
322  * the builder and how much of the client interface will be in this Builder
323  * versus Builders provided by the various modules.
324  *
325  * The named components for the initial builder implementation are descriptive
326  * of the state of mdrun at the time, and are not intended to be prescriptive of
327  * future design.
328  * The probable course of GROMACS development is for the modular components that
329  * support MD simulation to independently express their input parameters (required
330  * and optional) and to provide some sort of help to the UI for input preparation.
331  * If each module provides or aids the instantiation of a Director
332  * for the client code, the Directors could be constructed with a handle to this
333  * Builder and it would not need a public interface.
334  *
335  * As the modules are more clearly encapsulated, each module can provide its own
336  * builder, user interface helpers, and/or composable Director code.
337  * The runner and client code will also have to be updated as appropriate
338  * default behavior is clarified for
339  * (a) default behavior of client when user does not provide input,
340  * (b) default behavior of builder when client does not provide input, and
341  * (c) default behavior of runner when builder does not provide input.
342  */
343 class MdrunnerBuilder final
344 {
345 public:
346     /*!
347      * \brief Constructor requires a handle to a SimulationContext to share.
348      *
349      * \param mdModules  The handle to the set of modules active in mdrun
350      * \param context    Required handle to simulation context
351      *
352      * The calling code must guarantee that the
353      * pointer remains valid for the lifetime of the builder, and that the
354      * resources retrieved from the context remain valid for the lifetime of
355      * the runner produced.
356      */
357     explicit MdrunnerBuilder(std::unique_ptr<MDModules>           mdModules,
358                              compat::not_null<SimulationContext*> context);
359
360     //! \cond
361     MdrunnerBuilder()                       = delete;
362     MdrunnerBuilder(const MdrunnerBuilder&) = delete;
363     MdrunnerBuilder& operator=(const MdrunnerBuilder&) = delete;
364     //! \endcond
365
366     /*! \brief Allow transfer of ownership with move semantics.
367      *
368      * \param builder source object to transfer.
369      *
370      * \{
371      */
372     MdrunnerBuilder(MdrunnerBuilder&& builder) noexcept;
373     MdrunnerBuilder& operator=(MdrunnerBuilder&& builder) noexcept;
374     //! \}
375
376     /*!
377      * \brief Get ownership of an initialized gmx::Mdrunner.
378      *
379      * After build() is called, the Builder object should not be used
380      * again. It is an error to call build without first calling all builder
381      * methods described as "required."
382      *
383      * \return A new Mdrunner.
384      *
385      * \throws APIError if a required component has not been added before calling build().
386      */
387     Mdrunner build();
388
389     /*!
390      * \brief Set up non-bonded short-range force calculations.
391      *
392      * Required. Director code must provide valid options for the non-bonded
393      * interaction code. The builder does not apply any defaults.
394      *
395      * \param nbpu_opt Target short-range interactions for "cpu", "gpu", or "auto".
396      *
397      * Calling must guarantee that the pointed-to C string is valid through
398      * simulation launch.
399      *
400      * \internal
401      * \todo Replace with string or enum that we can have sensible defaults for.
402      * \todo Either the Builder or modular Director code should provide sensible defaults.
403      */
404     MdrunnerBuilder& addNonBonded(const char* nbpu_opt);
405
406     /*!
407      * \brief Set up long-range electrostatics calculations.
408      *
409      * Required. Director code should provide valid options for PME electrostatics,
410      * whether or not PME electrostatics are used. The builder does not apply
411      * any defaults, so client code should be prepared to provide (e.g.) "auto"
412      * in the event no user input or logic provides an alternative argument.
413      *
414      * \param pme_opt Target long-range interactions for "cpu", "gpu", or "auto".
415      * \param pme_fft_opt Target long-range interactions FFT/solve stages for "cpu", "gpu", or "auto".
416      *
417      * Calling must guarantee that the pointed-to C strings are valid through
418      * simulation launch.
419      *
420      * \internal
421      * The arguments are passed as references to elements of arrays of C strings.
422      * \todo Replace with modern strings or (better) enum classes.
423      * \todo Make optional and/or encapsulate into electrostatics module.
424      */
425     MdrunnerBuilder& addElectrostatics(const char* pme_opt, const char* pme_fft_opt);
426
427     /*!
428      * \brief Assign responsibility for tasks for bonded interactions.
429      *
430      * Required. Director code should provide valid options for
431      * bonded interaction task assignment, whether or not such
432      * interactions are present. The builder does not apply any
433      * defaults, so client code should be prepared to provide
434      * (e.g.) "auto" in the event no user input or logic provides
435      * an alternative argument.
436      *
437      * \param bonded_opt Target bonded interactions for "cpu", "gpu", or "auto".
438      *
439      * Calling must guarantee that the pointed-to C strings are valid through
440      * simulation launch.
441      *
442      * \internal
443      * The arguments are passed as references to elements of arrays of C strings.
444      * \todo Replace with modern strings or (better) enum classes.
445      * \todo Make optional and/or encapsulate into task assignment module.
446      */
447     MdrunnerBuilder& addBondedTaskAssignment(const char* bonded_opt);
448
449     /*! \brief
450      * Assign responsibility for tasks for update and constrain calculation.
451      *
452      * Required. Director code should provide valid options for
453      * update and constraint task assignment. The builder does not apply any
454      * defaults, so client code should be prepared to provide
455      * (e.g.) "auto" in the event no user input or logic provides
456      * an alternative argument.
457      *
458      * \param[in] update_opt Target update calculation for "cpu", "gpu", or "auto".
459      *
460      * Calling must guarantee that the pointed-to C strings are valid through
461      * simulation launch.
462      *
463      * \internal
464      * The arguments are passed as references to elements of arrays of C strings.
465      * \todo Replace with modern strings or (better) enum classes.
466      * \todo Make optional and/or encapsulate into task assignment module.
467      */
468     MdrunnerBuilder& addUpdateTaskAssignment(const char* update_opt);
469
470     /*!
471      * \brief Set MD options not owned by some other module.
472      *
473      * Optional. Override simulation parameters
474      *
475      * \param options structure to copy
476      * \param forceWarningThreshold Print a warning if any force is larger than this (in kJ/mol nm) (default -1)
477      * \param startingBehavior Whether the simulation will start afresh, or restart with/without appending.
478      *
479      * \internal
480      * \todo Map these parameters to more appropriate encapsulating types.
481      * Find a better way to indicate "unspecified" than a magic value of the parameter type.
482      */
483     MdrunnerBuilder& addSimulationMethod(const MdrunOptions& options,
484                                          real                forceWarningThreshold,
485                                          StartingBehavior    startingBehavior);
486
487     /*!
488      * \brief Set the domain decomposition module.
489      *
490      * Optional. Overrides default constructed DomdecOptions if provided.
491      *
492      * \param options options with which to construct domain decomposition.
493      *
494      * \internal
495      * \todo revisit whether we should be passing this parameter struct or a higher-level handle of some sort.
496      */
497     MdrunnerBuilder& addDomainDecomposition(const DomdecOptions& options);
498
499     /*!
500      * \brief Set Verlet list manager.
501      *
502      * Optional. Neighbor list existence, type, and parameters are mostly determined
503      * by the simulation parameters loaded elsewhere. This is just an override.
504      *
505      * \param rebuildInterval override for the duration of a neighbor list with the Verlet scheme.
506      */
507     MdrunnerBuilder& addNeighborList(int rebuildInterval);
508
509     /*!
510      * \brief Set replica exchange manager.
511      *
512      * Optional. For guidance on preparing a valid ReplicaExchangeParameters
513      * value, refer to the details in mdrun.cpp, the `t_pargs pa[]` defined there,
514      * and the action of parse_common_args() with regards to that structure.
515      * If not provided by client, a default constructed ReplicaExchangeParameters
516      * is used.
517      *
518      * \param params parameters with which to set up replica exchange.
519      *
520      * \internal
521      * \todo revisit whether we should be passing this parameter struct or a higher-level handle of some sort.
522      */
523     MdrunnerBuilder& addReplicaExchange(const ReplicaExchangeParameters& params);
524
525     /*!
526      * \brief Specify parameters determining hardware resource allocation.
527      *
528      * Optional. If not provided, default-constructed gmx_hw_opt_t will be used.
529      *
530      * \param hardwareOptions Parallelism-related user options.
531      */
532     MdrunnerBuilder& addHardwareOptions(const gmx_hw_opt_t& hardwareOptions);
533
534     /*!
535      * \brief Provide the filenames options structure with option values chosen
536      *
537      * Required. The object is assumed to have been updated by
538      * parse_common_args or equivalent.
539      *
540      * \param filenames Filenames and properties from command-line argument values or defaults.
541      *
542      * \internal
543      * \todo Modules should manage their own filename options and defaults.
544      */
545     MdrunnerBuilder& addFilenames(ArrayRef<const t_filenm> filenames);
546
547     /*!
548      * \brief Provide parameters for setting up output environment.
549      *
550      * Required. Handle is assumed to have been produced by output_env_init
551      * as in parse_common_args.
552      *
553      * \param outputEnvironment Output context for writing text files.
554      *
555      * \internal
556      * \todo Allow client code to set up output environment and provide as a resource.
557      * This parameter is used to set up resources that are dependent on the execution
558      * environment and API context. Such resources should be retrieved by the simulator
559      * from a client-provided resource, but currently the resources are only fully
560      * initialized in Mdrunner.
561      */
562     MdrunnerBuilder& addOutputEnvironment(gmx_output_env_t* outputEnvironment);
563
564     /*!
565      * \brief Provide the filehandle pointer to be used for the MD log.
566      *
567      * Required. Either nullptr if no log should be written, or
568      * valid and open reading for writing.
569      *
570      * \param logFileHandle Non-owning handle to file used for logging.
571      * \internal
572      */
573     MdrunnerBuilder& addLogFile(t_fileio* logFileHandle);
574
575     /*!
576      * \brief Provide a StopHandlerBuilder for the MD stop signal handling.
577      *
578      * Optional. Defaults to empty.
579      *
580      * Client may provide additional (non-default) issuers of simulation stop
581      * signals by preconfiguring the StopHandlerBuilder used later when the
582      * simulation runs.
583      *
584      * \param builder
585      */
586     MdrunnerBuilder& addStopHandlerBuilder(std::unique_ptr<StopHandlerBuilder> builder);
587
588     ~MdrunnerBuilder();
589
590 private:
591     std::unique_ptr<Mdrunner::BuilderImplementation> impl_;
592 };
593
594 } // namespace gmx
595
596 #endif // GMX_MDRUN_RUNNER_H