589ae10b8adb77c9f07e803fba0f478f2ccd9d10
[alexxy/gromacs.git] / src / api / cpp / context.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2018, 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 /*! \file
36  * \brief Implementation details of gmxapi::Context
37  *
38  * \todo Share mdrun input handling implementation via modernized modular options framework.
39  * Initial implementation of `launch` relies on borrowed code from the mdrun command
40  * line input processing.
41  *
42  * \author M. Eric Irrgang <ericirrgang@gmail.com>
43  * \ingroup gmxapi
44  */
45
46 #include "gmxapi/context.h"
47
48 #include <cstring>
49
50 #include <memory>
51 #include <utility>
52 #include <vector>
53
54 #include "gromacs/commandline/pargs.h"
55 #include "gromacs/commandline/filenm.h"
56 #include "gromacs/commandline/pargs.h"
57 #include "gromacs/gmxlib/network.h"
58 #include "gromacs/mdlib/stophandler.h"
59 #include "gromacs/mdrunutility/logging.h"
60 #include "gromacs/mdrunutility/multisim.h"
61 #include "gromacs/mdrun/runner.h"
62 #include "gromacs/mdrunutility/handlerestart.h"
63 #include "gromacs/mdtypes/commrec.h"
64 #include "gromacs/utility/arraysize.h"
65 #include "gromacs/utility/fatalerror.h"
66 #include "gromacs/utility/smalloc.h"
67
68 #include "gmxapi/exceptions.h"
69 #include "gmxapi/session.h"
70 #include "gmxapi/status.h"
71 #include "gmxapi/version.h"
72
73 #include "context_impl.h"
74 #include "createsession.h"
75 #include "session_impl.h"
76 #include "workflow.h"
77
78 namespace gmxapi
79 {
80
81 ContextImpl::ContextImpl()
82 {
83     GMX_ASSERT(session_.expired(), "This implementation assumes an expired weak_ptr at initialization.");
84 }
85
86 std::shared_ptr<gmxapi::ContextImpl> ContextImpl::create()
87 {
88     std::shared_ptr<ContextImpl> impl = std::make_shared<ContextImpl>();
89     return impl;
90 }
91
92 std::shared_ptr<Session> ContextImpl::launch(const Workflow &work)
93 {
94     using namespace gmx;
95     // Much of this implementation is not easily testable: we need tools to inspect simulation results and to modify
96     // simulation inputs.
97
98     std::shared_ptr<Session> launchedSession = nullptr;
99
100     // This implementation can only run one workflow at a time.
101     // Check whether we are already aware of an active session.
102     if (session_.expired())
103     {
104         // Check workflow spec, build graph for current context, launch and return new session.
105         // \todo This is specific to the session implementation...
106         auto        mdNode = work.getNode("MD");
107         std::string filename {};
108         if (mdNode != nullptr)
109         {
110             filename = mdNode->params();
111         }
112
113         /* As default behavior, automatically extend trajectories from the checkpoint file.
114          * In the future, our API for objects used to initialize a simulation needs to address the fact that currently a
115          * microstate requires data from both the TPR and checkpoint file to be fully specified. Put another way,
116          * current
117          * GROMACS simulations can take a "configuration" as input that does not constitute a complete microstate in
118          * terms of hidden degrees of freedom (integrator/thermostat/barostat/PRNG state), but we want a clear notion of
119          * a microstate for gmxapi interfaces.
120          */
121
122         // Set input TPR name
123         mdArgs_.emplace_back("-s");
124         mdArgs_.emplace_back(filename);
125
126         // Set checkpoint file name
127         mdArgs_.emplace_back("-cpi");
128         mdArgs_.emplace_back("state.cpt");
129         /* Note: we normalize the checkpoint file name, but not its full path.
130          * Through version 0.0.8, gmxapi clients change working directory
131          * for each session, so relative path(s) below are appropriate.
132          * A future gmxapi version should avoid changing directories once the
133          * process starts and instead manage files (paths) in an absolute and
134          * immutable way, with abstraction provided through the Context chain-of-responsibility.
135          * TODO: API abstractions for initializing simulations that may be new or partially complete.
136          * Reference gmxapi milestone 13 at https://redmine.gromacs.org/issues/2585
137          */
138
139         // Create a mock argv. Note that argv[0] is expected to hold the program name.
140         const int  offset = 1;
141         const auto argc   = static_cast<size_t>(mdArgs_.size() + offset);
142         auto       argv   = std::vector<char *>(argc, nullptr);
143         // argv[0] is ignored, but should be a valid string (e.g. null terminated array of char)
144         argv[0]  = new char[1];
145         *argv[0] = '\0';
146         for (size_t argvIndex = offset; argvIndex < argc; ++argvIndex)
147         {
148             const auto &mdArg = mdArgs_[argvIndex - offset];
149             argv[argvIndex] = new char[mdArg.length() + 1];
150             strcpy(argv[argvIndex], mdArg.c_str());
151         }
152
153         auto mdModules = std::make_unique<MDModules>();
154
155         // pointer-to-t_commrec is the de facto handle type for communications record.
156         // Complete shared / borrowed ownership requires a reference to this stack variable
157         // (or pointer-to-pointer-to-t_commrec) since borrowing code may update the pointer.
158         // \todo Define the ownership and lifetime management semantics for a communication record, handle or value type.
159
160         // Note: this communications record initialization acts directly on
161         // MPI_COMM_WORLD and is incompatible with MPI environment sharing in
162         // gmxapi through 0.0.7, at least.
163         options_.cr = init_commrec();
164
165         const char *desc[]  = {"gmxapi placeholder text"};
166         if (options_.updateFromCommandLine(argc, argv.data(), desc) == 0)
167         {
168             return nullptr;
169         }
170
171         StartingBehavior startingBehavior = StartingBehavior::NewSimulation;
172         LogFilePtr       logFileGuard     = nullptr;
173         std::tie(startingBehavior,
174                  logFileGuard) = handleRestart(options_.cr.get(),
175                                                options_.ms.get(),
176                                                options_.mdrunOptions.appendingBehavior,
177                                                ssize(options_.filenames),
178                                                options_.filenames.data());
179         auto simulationContext = createSimulationContext(std::move(options_.cr));
180
181         auto builder = MdrunnerBuilder(std::move(mdModules));
182         builder.addSimulationMethod(options_.mdrunOptions, options_.pforce, startingBehavior);
183         builder.addDomainDecomposition(options_.domdecOptions);
184         // \todo pass by value
185         builder.addNonBonded(options_.nbpu_opt_choices[0]);
186         // \todo pass by value
187         builder.addElectrostatics(options_.pme_opt_choices[0], options_.pme_fft_opt_choices[0]);
188         builder.addBondedTaskAssignment(options_.bonded_opt_choices[0]);
189         builder.addNeighborList(options_.nstlist_cmdline);
190         builder.addReplicaExchange(options_.replExParams);
191         // \todo take ownership of multisim resources (ms)
192         builder.addMultiSim(options_.ms.get());
193         // \todo Provide parallelism resources through SimulationContext.
194         // Need to establish run-time values from various inputs to provide a resource handle to Mdrunner
195         builder.addHardwareOptions(options_.hw_opt);
196         // \todo File names are parameters that should be managed modularly through further factoring.
197         builder.addFilenames(options_.filenames);
198         // Note: The gmx_output_env_t life time is not managed after the call to parse_common_args.
199         // \todo Implement lifetime management for gmx_output_env_t.
200         // \todo Output environment should be configured outside of Mdrunner and provided as a resource.
201         builder.addOutputEnvironment(options_.oenv);
202         builder.addLogFile(logFileGuard.get());
203
204         // Note, creation is not mature enough to be exposed in the external API yet.
205         launchedSession = createSession(shared_from_this(),
206                                         std::move(builder),
207                                         std::move(simulationContext),
208                                         std::move(logFileGuard),
209                                         options_.ms.get());
210
211         // Clean up argv once builder is no longer in use
212         for (auto && string : argv)
213         {
214             if (string != nullptr)
215             {
216                 delete[] string;
217                 string = nullptr;
218             }
219         }
220
221     }
222     else
223     {
224         throw gmxapi::ProtocolError("Tried to launch a session while a session is still active.");
225     }
226
227     if (launchedSession != nullptr)
228     {
229         // Update weak reference.
230         session_ = launchedSession;
231     }
232     return launchedSession;
233 }
234
235 // As of gmxapi 0.0.3 there is only one Context type
236 Context::Context() :
237     Context {ContextImpl::create()}
238 {
239     GMX_ASSERT(impl_, "Context requires a non-null implementation member.");
240 }
241
242 std::shared_ptr<Session> Context::launch(const Workflow &work)
243 {
244     return impl_->launch(work);
245 }
246
247 Context::Context(std::shared_ptr<ContextImpl> impl) :
248     impl_ {std::move(impl)}
249 {
250     GMX_ASSERT(impl_, "Context requires a non-null implementation member.");
251 }
252
253 void Context::setMDArgs(const MDArgs &mdArgs)
254 {
255     impl_->mdArgs_ = mdArgs;
256 }
257
258 Context::~Context() = default;
259
260 } // end namespace gmxapi