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