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