2f9373882661bb8d0df94e6c857b2429d6ea5fc4
[alexxy/gromacs.git] / src / api / cpp / session_impl.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 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
36 #ifndef GMXAPI_SESSION_IMPL_H
37 #define GMXAPI_SESSION_IMPL_H
38 /*! \file
39  * \brief Declare implementation interface for Session API class(es).
40  *
41  * \ingroup gmxapi
42  */
43
44 #include <map>
45
46 #include "gromacs/mdrun/logging.h"
47 #include "gromacs/mdrun/runner.h"
48 #include "gromacs/mdrun/simulationcontext.h"
49
50 #include "gmxapi/context.h"
51 #include "gmxapi/md.h"
52 #include "gmxapi/md/mdmodule.h"
53 #include "gmxapi/session/resources.h"
54 #include "gmxapi/status.h"
55
56 namespace gmxapi
57 {
58
59 // Forward declaration
60 class MpiContextManager; // Locally defined in session.cpp
61 class ContextImpl;       // locally defined in context.cpp
62 class SignalManager;     // defined in mdsignals_impl.h
63
64 /*!
65  * \brief Implementation class for executing sessions.
66  *
67  * Since 0.0.3, there is only one context and only one session type. This may
68  * change at some point to allow templating on different resource types or
69  * implementations provided by different libraries.
70  * \ingroup gmxapi
71  */
72 class SessionImpl
73 {
74     public:
75         //! Use create() factory to get an object.
76         SessionImpl() = delete;
77         ~SessionImpl();
78
79         /*!
80          * \brief Check if the session is (still) running.
81          *
82          * When a session is launched, it should be returned in an "open" state by the launcher function.
83          * \return True if running, false if already closed.
84          */
85         bool isOpen() const noexcept;
86
87         /*!
88          * \brief Explicitly close the session.
89          *
90          * Sessions should be explicitly `close()`ed to allow for exceptions to be caught by the client
91          * and because closing a session involves a more significant state change in the program than
92          * implied by a typical destructor. If close() can be shown to be exception safe, this protocol may be removed.
93          *
94          * \return On closing a session, a status object is transferred to the caller.
95          */
96         Status close();
97
98         /*!
99          * \brief Run the configured workflow to completion or error.
100          *
101          * \return copy of the resulting status.
102          *
103          * \internal
104          * By the time we get to the run() we shouldn't have any unanticipated exceptions.
105          * If there are, they can be incorporated into richer future Status implementations
106          * or some other more appropriate output type.
107          */
108         Status run() noexcept;
109
110         /*!
111          * \brief Create a new implementation object and transfer ownership.
112          *
113          * \param context Shared ownership of a Context implementation instance.
114          * \param runnerBuilder MD simulation builder to take ownership of.
115          * \param simulationContext Take ownership of the simulation resources.
116          * \param logFilehandle Take ownership of filehandle for MD logging
117          * \param multiSim Take ownership of resources for Mdrunner multi-sim.
118          *
119          * \todo Log file management will be updated soon.
120          *
121          * \return Ownership of new Session implementation instance.
122          */
123         static std::unique_ptr<SessionImpl> create(std::shared_ptr<ContextImpl>  context,
124                                                    gmx::MdrunnerBuilder        &&runnerBuilder,
125                                                    const gmx::SimulationContext &simulationContext,
126                                                    gmx::LogFilePtr               logFilehandle,
127                                                    gmx_multisim_t              * multiSim);
128
129         /*!
130          * \brief Add a restraint to the simulation.
131          *
132          * \param module
133          * \return
134          */
135         Status addRestraint(std::shared_ptr<gmxapi::MDModule> module);
136
137         /*!
138          * \brief Get a handle to the resources for the named session operation.
139          *
140          * \param name unique name of element in workflow
141          * \return temporary access to the resources.
142          *
143          * If called on a non-const Session, creates the resource if it does not yet exist.
144          * If called on a const Session,
145          * returns nullptr if the resource does not exist.
146          */
147         gmxapi::SessionResources* getResources(const std::string &name) const noexcept;
148
149         /*!
150          * \brief Create SessionResources for a module and bind the module.
151          *
152          * Adds a new managed resources object to the Session for the uniquely named module.
153          * Allows the module to bind to the SignalManager and to the resources object.
154          *
155          * \param module
156          * \return non-owning pointer to created resources or nullptr for error.
157          *
158          * If the named module is already registered, calling createResources again is considered an
159          * error and nullptr is returned.
160          */
161         gmxapi::SessionResources* createResources(std::shared_ptr<gmxapi::MDModule> module) noexcept;
162
163         /*! \internal
164          * \brief API implementation function to retrieve the current runner.
165          *
166          * \return non-owning pointer to the current runner or nullptr if none.
167          */
168         gmx::Mdrunner* getRunner();
169
170         /*!
171          * \brief Get a non-owning handle to the SignalManager for the active MD runner.
172          *
173          * Calling code is responsible for ensuring that the SessionImpl is kept alive and "open"
174          * while the returned SignalManager handle is in use.
175          *
176          * \return non-owning pointer if runner and signal manager are active, else nullptr.
177          */
178         SignalManager* getSignalManager();
179
180         /*!
181          * \brief Constructor for use by create()
182          *
183          * \param context specific context to keep alive during session.
184          * \param runnerBuilder ownership of the MdrunnerBuilder object.
185          * \param simulationContext take ownership of a SimulationContext
186          * \param logFilehandle Take ownership of filehandle for MD logging
187          * \param multiSim Take ownership of resources for Mdrunner multi-sim.
188          *
189          */
190         SessionImpl(std::shared_ptr<ContextImpl>  context,
191                     gmx::MdrunnerBuilder        &&runnerBuilder,
192                     const gmx::SimulationContext &simulationContext,
193                     gmx::LogFilePtr               logFilehandle,
194                     gmx_multisim_t              * multiSim);
195
196     private:
197         /*!
198          * \brief Manage session resources for named workflow elements.
199          */
200         std::map< std::string, std::unique_ptr<SessionResources> > resources_;
201
202         /*!
203          * \brief Extend the life of the owning context.
204          *
205          * The session will get handles for logging, UI status messages,
206          * and other facilities through this interface.
207          */
208         std::shared_ptr<ContextImpl> context_;
209
210         /*!
211          * \brief RAII management of gmx::init() and gmx::finalize()
212          *
213          * Uses smart pointer to avoid exposing type definition.
214          * \todo Not fully implemented.
215          */
216         std::unique_ptr<MpiContextManager> mpiContextManager_;
217
218         /*!
219          * \brief Simulation runner object.
220          *
221          * If a simulation Session is active, points to a valid Mdrunner object.
222          * Null if simulation is inactive.
223          */
224         std::unique_ptr<gmx::Mdrunner>     runner_;
225
226         /*!
227          * \brief An active session owns the resources it is using.
228          */
229         gmx::SimulationContext simulationContext_;
230
231         /*! \brief Handle to file used for logging.
232          *
233          * \todo Move to RAII filehandle management; open and close in one place.
234          */
235         gmx::LogFilePtr logFilePtr_;
236
237         /*!
238          * \brief MultiSim resources for Mdrunner instance.
239          *
240          * May be null for no multi-simulation management at the Mdrunner level.
241          *
242          * \todo Lifetime of the multi-simulation handle is currently
243          * managed by LegacyMdrunOptions, but in the long term,
244          * session needs to manage it.
245          */
246         gmx_multisim_t* multiSim_;
247
248         /*!
249          * \brief Own and manager the signalling pathways for the current session.
250          *
251          * Registers a stop signal issuer with the stopConditionBuilder that is
252          * passed to the Mdrunner at launch. Session members issuing stop signals
253          * are proxied through this resource.
254          */
255         std::unique_ptr<SignalManager>     signalManager_;
256
257         /*!
258          * \brief Restraints active in this session.
259          *
260          * Client owns these restraint objects, but session has the ability to
261          * lock the resource to take temporary ownership in case the client
262          * releases its handle.
263          * \todo clarify and update object lifetime management
264          * A restraint module manager and / or a mapping of factory functions with
265          * which the runner can get objects at run time can encapsulate object management.
266          */
267         std::map<std::string, std::weak_ptr<gmx::IRestraintPotential> > restraints_;
268 };
269
270 }      //end namespace gmxapi
271
272 #endif //GMXAPI_SESSION_IMPL_H