6a168087f45e17d25dd7bd0b6559430eedca5d6c
[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, 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/domdec/options.h"
52 #include "gromacs/hardware/hw_info.h"
53 #include "gromacs/math/vec.h"
54 #include "gromacs/mdrun/mdmodules.h"
55 #include "gromacs/mdrunutility/handlerestart.h"
56 #include "gromacs/mdtypes/mdrunoptions.h"
57 #include "gromacs/utility/basedefinitions.h"
58 #include "gromacs/utility/real.h"
59
60 #include "replicaexchange.h"
61
62 struct gmx_output_env_t;
63 struct ReplicaExchangeParameters;
64 struct t_commrec;
65 struct t_fileio;
66
67 namespace gmx
68 {
69
70 // Todo: move to forward declaration headers...
71 class MDModules;
72 class IRestraintPotential; // defined in restraint/restraintpotential.h
73 class RestraintManager;
74 class SimulationContext;
75 class StopHandlerBuilder;
76
77 //! Work-around for GCC bug 58265
78 constexpr bool BUGFREE_NOEXCEPT_STRING = std::is_nothrow_move_assignable<std::string>::value;
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         //NOLINTNEXTLINE(performance-noexcept-move-constructor) working around GCC bug 58265
146         Mdrunner &operator=(Mdrunner &&handle) noexcept(BUGFREE_NOEXCEPT_STRING);
147         /* \} */
148
149         /*! \brief Driver routine, that calls the different simulation methods. */
150         /*!
151          * Currently, thread-MPI does not spawn threads until during mdrunner() and parallelism
152          * is not initialized until some time during this call...
153          */
154         int mdrunner();
155
156         /*!
157          * \brief Add a potential to be evaluated during MD integration.
158          *
159          * \param restraint MD restraint potential to apply
160          * \param name User-friendly plain-text name to uniquely identify the puller
161          *
162          * This implementation attaches an object providing the gmx::IRestraintPotential
163          * interface.
164          * \todo Mdrunner should fetch such resources from the SimulationContext
165          * rather than offering this public interface.
166          */
167         void addPotential(std::shared_ptr<IRestraintPotential> restraint,
168                           const std::string                   &name);
169
170         //! Called when thread-MPI spawns threads.
171         t_commrec *spawnThreads(int numThreadsToLaunch) const;
172
173         /*! \brief Initializes a new Mdrunner from the master.
174          *
175          * Run this method in a new thread from a master runner to get additional
176          * workers on spawned threads.
177          *
178          * \returns New Mdrunner instance suitable for thread-MPI work on new ranks.
179          *
180          * \internal
181          * \todo clarify (multiple) invariants during MD runner start-up.
182          * The runner state before and after launching threads is distinct enough that
183          * it should be codified in the invariants of different classes. That would
184          * mean that the object returned by this method would be of a different type
185          * than the object held by the client up to the point of call, and its name
186          * would be changed to "launchOnSpawnedThread" or something not including the
187          * word "clone".
188          */
189         Mdrunner cloneOnSpawnedThread() const;
190
191     private:
192         /*! \brief Constructor. */
193         explicit Mdrunner(std::unique_ptr<MDModules> mdModules);
194
195         //! Parallelism-related user options.
196         gmx_hw_opt_t             hw_opt;
197
198         //! Filenames and properties from command-line argument values.
199         ArrayRef<const t_filenm> filenames;
200
201         /*! \brief Output context for writing text files
202          *
203          * \internal
204          * \todo push this data member down when the information can be queried from an encapsulated resource.
205          */
206         gmx_output_env_t                       *oenv = nullptr;
207         //! Ongoing collection of mdrun options
208         MdrunOptions                            mdrunOptions;
209         //! Options for the domain decomposition.
210         DomdecOptions                           domdecOptions;
211
212         /*! \brief Target short-range interations for "cpu", "gpu", or "auto". Default is "auto".
213          *
214          * \internal
215          * \todo replace with string or enum class and initialize with sensible value.
216          */
217         const char                             *nbpu_opt = nullptr;
218
219         /*! \brief Target long-range interactions for "cpu", "gpu", or "auto". Default is "auto".
220          *
221          * \internal
222          * \todo replace with string or enum class and initialize with sensible value.
223          */
224         const char                             *pme_opt = nullptr;
225
226         /*! \brief Target long-range interactions FFT/solve stages for "cpu", "gpu", or "auto". Default is "auto".
227          *
228          * \internal
229          * \todo replace with string or enum class and initialize with sensible value.
230          */
231         const char                             *pme_fft_opt = nullptr;
232
233         /*! \brief Target bonded interations for "cpu", "gpu", or "auto". Default is "auto".
234          *
235          * \internal
236          * \todo replace with string or enum class and initialize with sensible value.
237          */
238         const char                             *bonded_opt = nullptr;
239
240         //! Command-line override for the duration of a neighbor list with the Verlet scheme.
241         int                                     nstlist_cmdline = 0;
242         //! Parameters for replica-exchange simulations.
243         ReplicaExchangeParameters               replExParams;
244         //! Print a warning if any force is larger than this (in kJ/mol nm).
245         real                                    pforce = -1;
246
247         //! Handle to file used for logging.
248         LogFilePtr logFileGuard = nullptr;
249         //! \brief Non-owning handle to file used for logging.
250         t_fileio                               *logFileHandle = nullptr;
251
252         //! \brief Non-owning handle to communication data structure.
253         t_commrec                              *cr = nullptr;
254
255         //! \brief Non-owning handle to multi-simulation handler.
256         gmx_multisim_t                         *ms = nullptr;
257
258         //! Whether the simulation will start afresh, or restart with/without appending.
259         StartingBehavior startingBehavior = StartingBehavior::NewSimulation;
260
261         /*!
262          * \brief Handle to restraints manager for the current process.
263          *
264          * \internal
265          * Use opaque pointer for this implementation detail.
266          */
267         std::unique_ptr<RestraintManager>     restraintManager_;
268
269         /*!
270          * \brief Builder for stop signal handler
271          *
272          * Optionally provided through MdrunnerBuilder. Client may create a
273          * StopHandlerBuilder and register any number of signal providers before
274          * launching the Mdrunner.
275          *
276          * Default is an empty signal handler that will have local signal issuers
277          * added after being passed into the integrator.
278          *
279          * \internal
280          * We do not need a full type specification here, so we use an opaque pointer.
281          */
282         std::unique_ptr<StopHandlerBuilder>    stopHandlerBuilder_;
283         //! The modules that comprise mdrun.
284         std::unique_ptr<MDModules>             mdModules_;
285 };
286
287 /*! \libinternal
288  * \brief Build a gmx::Mdrunner.
289  *
290  * Client code (such as `gmx mdrun`) uses this builder to get an initialized Mdrunner.
291  *
292  * A builder allows the library to ensure that client code cannot obtain an
293  * uninitialized or partially initialized runner by refusing to build() if the
294  * client has not provided sufficient or self-consistent direction. Director
295  * code can be implemented for different user interfaces, encapsulating any
296  * run-time functionality that does not belong in the library MD code, such
297  * as command-line option processing or interfacing to external libraries.
298  *
299  * \ingroup module_mdrun
300  *
301  * \internal
302  *
303  * The initial Builder implementation is neither extensible at run time nor
304  * at compile time. Future implementations should evolve to compose the runner,
305  * rather than just consolidating the parameters for initialization, but there
306  * is not yet a firm design for how flexibly module code will be coupled to
307  * the builder and how much of the client interface will be in this Builder
308  * versus Builders provided by the various modules.
309  *
310  * The named components for the initial builder implementation are descriptive
311  * of the state of mdrun at the time, and are not intended to be prescriptive of
312  * future design.
313  * The probable course of GROMACS development is for the modular components that
314  * support MD simulation to independently express their input parameters (required
315  * and optional) and to provide some sort of help to the UI for input preparation.
316  * If each module provides or aids the instantiation of a Director
317  * for the client code, the Directors could be constructed with a handle to this
318  * Builder and it would not need a public interface.
319  *
320  * As the modules are more clearly encapsulated, each module can provide its own
321  * builder, user interface helpers, and/or composable Director code.
322  * The runner and client code will also have to be updated as appropriate
323  * default behavior is clarified for
324  * (a) default behavior of client when user does not provide input,
325  * (b) default behavior of builder when client does not provide input, and
326  * (c) default behavior of runner when builder does not provide input.
327  */
328 class MdrunnerBuilder final
329 {
330     public:
331         /*!
332          * \brief Constructor requires a handle to a SimulationContext to share.
333          *
334          * \param mdModules  The handle to the set of modules active in mdrun
335          *
336          * The calling code must guarantee that the
337          * pointer remains valid for the lifetime of the builder, and that the
338          * resources retrieved from the context remain valid for the lifetime of
339          * the runner produced.
340          */
341         explicit MdrunnerBuilder(std::unique_ptr<MDModules> mdModules);
342
343         //! \cond
344         MdrunnerBuilder() = delete;
345         MdrunnerBuilder(const MdrunnerBuilder&)             = delete;
346         MdrunnerBuilder &operator=(const MdrunnerBuilder &) = delete;
347         //! \endcond
348
349         /*! \brief Allow transfer of ownership with move semantics.
350          *
351          * \param builder source object to transfer.
352          *
353          * \{
354          */
355         MdrunnerBuilder(MdrunnerBuilder && builder) noexcept;
356         MdrunnerBuilder &operator=(MdrunnerBuilder &&builder) noexcept;
357         //! \}
358
359         /*!
360          * \brief Get ownership of an initialized gmx::Mdrunner.
361          *
362          * After build() is called, the Builder object should not be used
363          * again. It is an error to call build without first calling all builder
364          * methods described as "required."
365          *
366          * \return A new Mdrunner.
367          *
368          * \throws APIError if a required component has not been added before calling build().
369          */
370         Mdrunner build();
371
372         /*!
373          * \brief Set up non-bonded short-range force calculations.
374          *
375          * Required. Director code must provide valid options for the non-bonded
376          * interaction code. The builder does not apply any defaults.
377          *
378          * \param nbpu_opt Target short-range interactions for "cpu", "gpu", or "auto".
379          *
380          * Calling must guarantee that the pointed-to C string is valid through
381          * simulation launch.
382          *
383          * \internal
384          * \todo Replace with string or enum that we can have sensible defaults for.
385          * \todo Either the Builder or modular Director code should provide sensible defaults.
386          */
387         MdrunnerBuilder &addNonBonded(const char* nbpu_opt);
388
389         /*!
390          * \brief Set up long-range electrostatics calculations.
391          *
392          * Required. Director code should provide valid options for PME electrostatics,
393          * whether or not PME electrostatics are used. The builder does not apply
394          * any defaults, so client code should be prepared to provide (e.g.) "auto"
395          * in the event no user input or logic provides an alternative argument.
396          *
397          * \param pme_opt Target long-range interactions for "cpu", "gpu", or "auto".
398          * \param pme_fft_opt Target long-range interactions FFT/solve stages for "cpu", "gpu", or "auto".
399          *
400          * Calling must guarantee that the pointed-to C strings are valid through
401          * simulation launch.
402          *
403          * \internal
404          * The arguments are passed as references to elements of arrays of C strings.
405          * \todo Replace with modern strings or (better) enum classes.
406          * \todo Make optional and/or encapsulate into electrostatics module.
407          */
408         MdrunnerBuilder &addElectrostatics(const char* pme_opt,
409                                            const char* pme_fft_opt);
410
411         /*!
412          * \brief Assign responsibility for tasks for bonded interactions.
413          *
414          * Required. Director code should provide valid options for
415          * bonded interaction task assignment, whether or not such
416          * interactions are present. The builder does not apply any
417          * defaults, so client code should be prepared to provide
418          * (e.g.) "auto" in the event no user input or logic provides
419          * an alternative argument.
420          *
421          * \param bonded_opt Target bonded interactions for "cpu", "gpu", or "auto".
422          *
423          * Calling must guarantee that the pointed-to C strings are valid through
424          * simulation launch.
425          *
426          * \internal
427          * The arguments are passed as references to elements of arrays of C strings.
428          * \todo Replace with modern strings or (better) enum classes.
429          * \todo Make optional and/or encapsulate into task assignment module.
430          */
431         MdrunnerBuilder &addBondedTaskAssignment(const char *bonded_opt);
432
433         /*!
434          * \brief Provide access to the multisim communicator to use.
435          *
436          * \param multisim borrowed handle to multisim record.
437          *
438          * Required. Client should create a `gmx_multisim_t` and pass its address.
439          * Client is responsible for calling done_multisim() on the handle after
440          * simulation.
441          *
442          * \internal Pointer is copied, but calling code retains ownership and
443          * responsibility for multisim. Mdrunner must not do anything that would
444          * invalidate the original copied-from pointer.
445          *
446          * \todo Clarify semantics of specifying optional multisim work
447          * \todo Clarify ownership and management of multisim resources.
448          */
449         MdrunnerBuilder &addMultiSim(gmx_multisim_t* multisim);
450
451         /*!
452          * \brief Provide a commrec for mdrun to use.
453          *
454          * This will come from the simulation context, but differently
455          * for command-line gmx and a gmxapi Context. */
456         MdrunnerBuilder &addCommunicationRecord(t_commrec *cr);
457
458         /*!
459          * \brief Set MD options not owned by some other module.
460          *
461          * Optional. Override simulation parameters
462          *
463          * \param options structure to copy
464          * \param forceWarningThreshold Print a warning if any force is larger than this (in kJ/mol nm) (default -1)
465          * \param startingBehavior Whether the simulation will start afresh, or restart with/without appending.
466          *
467          * \internal
468          * \todo Map these parameters to more appropriate encapsulating types.
469          * Find a better way to indicate "unspecified" than a magic value of the parameter type.
470          */
471         MdrunnerBuilder &addSimulationMethod(const MdrunOptions &options,
472                                              real                forceWarningThreshold,
473                                              StartingBehavior    startingBehavior);
474
475         /*!
476          * \brief Set the domain decomposition module.
477          *
478          * Optional. Overrides default constructed DomdecOptions if provided.
479          *
480          * \param options options with which to construct domain decomposition.
481          *
482          * \internal
483          * \todo revisit whether we should be passing this parameter struct or a higher-level handle of some sort.
484          */
485         MdrunnerBuilder &addDomainDecomposition(const DomdecOptions &options);
486
487         /*!
488          * \brief Set Verlet list manager.
489          *
490          * Optional. Neighbor list existence, type, and parameters are mostly determined
491          * by the simulation parameters loaded elsewhere. This is just an override.
492          *
493          * \param rebuildInterval override for the duration of a neighbor list with the Verlet scheme.
494          */
495         MdrunnerBuilder &addNeighborList(int rebuildInterval);
496
497         /*!
498          * \brief Set replica exchange manager.
499          *
500          * Optional. For guidance on preparing a valid ReplicaExchangeParameters
501          * value, refer to the details in mdrun.cpp, the `t_pargs pa[]` defined there,
502          * and the action of parse_common_args() with regards to that structure.
503          * If not provided by client, a default constructed ReplicaExchangeParameters
504          * is used.
505          *
506          * \param params parameters with which to set up replica exchange.
507          *
508          * \internal
509          * \todo revisit whether we should be passing this parameter struct or a higher-level handle of some sort.
510          */
511         MdrunnerBuilder &addReplicaExchange(const ReplicaExchangeParameters &params);
512
513         /*!
514          * \brief Specify parameters determining hardware resource allocation.
515          *
516          * Optional. If not provided, default-constructed gmx_hw_opt_t will be used.
517          *
518          * \param hardwareOptions Parallelism-related user options.
519          */
520         MdrunnerBuilder &addHardwareOptions(const gmx_hw_opt_t &hardwareOptions);
521
522         /*!
523          * \brief Provide the filenames options structure with option values chosen
524          *
525          * Required. The object is assumed to have been updated by
526          * parse_common_args or equivalent.
527          *
528          * \param filenames Filenames and properties from command-line argument values or defaults.
529          *
530          * \internal
531          * \todo Modules should manage their own filename options and defaults.
532          */
533         MdrunnerBuilder &addFilenames(ArrayRef<const t_filenm> filenames);
534
535         /*!
536          * \brief Provide parameters for setting up output environment.
537          *
538          * Required. Handle is assumed to have been produced by output_env_init
539          * as in parse_common_args.
540          *
541          * \param outputEnvironment Output context for writing text files.
542          *
543          * \internal
544          * \todo Allow client code to set up output environment and provide as a resource.
545          * This parameter is used to set up resources that are dependent on the execution
546          * environment and API context. Such resources should be retrieved by the simulator
547          * from a client-provided resource, but currently the resources are only fully
548          * initialized in Mdrunner.
549          */
550         MdrunnerBuilder &addOutputEnvironment(gmx_output_env_t* outputEnvironment);
551
552         /*!
553          * \brief Provide the filehandle pointer to be used for the MD log.
554          *
555          * Required. Either nullptr if no log should be written, or
556          * valid and open reading for writing.
557          *
558          * \param logFileHandle Non-owning handle to file used for logging.
559          * \internal
560          */
561         MdrunnerBuilder &addLogFile(t_fileio *logFileHandle);
562
563         /*!
564          * \brief Provide a StopHandlerBuilder for the MD stop signal handling.
565          *
566          * Optional. Defaults to empty.
567          *
568          * Client may provide additional (non-default) issuers of simulation stop
569          * signals by preconfiguring the StopHandlerBuilder used later when the
570          * simulation runs.
571          *
572          * \param builder
573          */
574         MdrunnerBuilder &addStopHandlerBuilder(std::unique_ptr<StopHandlerBuilder> builder);
575
576         ~MdrunnerBuilder();
577
578     private:
579         std::unique_ptr<Mdrunner::BuilderImplementation> impl_;
580 };
581
582 }      // namespace gmx
583
584 #endif // GMX_MDRUN_RUNNER_H