1b5cb813d14bbf0812796d074280f99e0b66ac99
[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/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/utility/arraysize.h"
64 #include "gromacs/utility/basenetwork.h"
65 #include "gromacs/utility/fatalerror.h"
66 #include "gromacs/utility/gmxmpi.h"
67 #include "gromacs/utility/init.h"
68 #include "gromacs/utility/smalloc.h"
69
70 #include "gmxapi/mpi/resourceassignment.h"
71 #include "gmxapi/exceptions.h"
72 #include "gmxapi/session.h"
73 #include "gmxapi/status.h"
74 #include "gmxapi/version.h"
75
76 #include "context_impl.h"
77 #include "createsession.h"
78 #include "session_impl.h"
79 #include "workflow.h"
80
81 namespace gmxapi
82 {
83
84 // Support some tag dispatch. Warning: These are just aliases (not strong types).
85 /*!
86  * \brief Logical helper alias to convert preprocessor constant to type.
87  *
88  * \tparam Value Provide the GMX\_LIB\_MPI macro.
89  */
90 template<bool Value>
91 using hasLibraryMpi = std::bool_constant<Value>;
92 /* Note that a no-MPI build still uses the tMPI headers to define MPI_Comm for the
93  * gmx::SimulationContext definition. The dispatching in this file accounts for
94  * these two definitions of SimulationContext. gmxThreadMpi here does not imply
95  * that the library was necessarily compiled with thread-MPI enabled.
96  */
97 using gmxThreadMpi = hasLibraryMpi<false>;
98 using gmxLibMpi    = hasLibraryMpi<true>;
99 using MpiType      = std::conditional_t<GMX_LIB_MPI, gmxLibMpi, gmxThreadMpi>;
100
101 using MpiContextInitializationError = BasicException<struct MpiContextInitialization>;
102
103
104 /*!
105  * \brief Helpers to evaluate the correct precondition for the library build.
106  *
107  * TODO: (#3650) Consider distinct MpiContextManager types for clearer definition of preconditions.
108  */
109 namespace
110 {
111
112 [[maybe_unused]] MPI_Comm validCommunicator(const MPI_Comm& communicator, const gmxThreadMpi&)
113 {
114     if (communicator != MPI_COMM_NULL)
115     {
116         throw MpiContextInitializationError(
117                 "Provided communicator must be MPI_COMM_NULL for GROMACS built without MPI "
118                 "library.");
119     }
120     return communicator;
121 }
122
123 [[maybe_unused]] MPI_Comm validCommunicator(const MPI_Comm& communicator, const gmxLibMpi&)
124 {
125     if (communicator == MPI_COMM_NULL)
126     {
127         throw MpiContextInitializationError("MPI-enabled GROMACS requires a valid communicator.");
128     }
129     return communicator;
130 }
131
132 /*!
133  * \brief Return the communicator if it is appropriate for the environment.
134  *
135  * \throws MpiContextInitializationError if communicator does not match the
136  *  MpiContextManager precondition for the current library configuration.
137  */
138 MPI_Comm validCommunicator(const MPI_Comm& communicator)
139 {
140     return validCommunicator(communicator, MpiType());
141 }
142
143 //! \brief Provide a reasonable default value.
144 MPI_Comm validCommunicator()
145 {
146     return GMX_LIB_MPI ? MPI_COMM_WORLD : MPI_COMM_NULL;
147 }
148
149 } // anonymous namespace
150
151 MpiContextManager::MpiContextManager(MPI_Comm communicator) :
152     communicator_(std::make_unique<MPI_Comm>(validCommunicator(communicator)))
153 {
154     // Safely increments the GROMACS MPI initialization counter after checking
155     // whether the MPI library is already initialized. After this call, MPI_Init
156     // or MPI_Init_thread has been called exactly once.
157     gmx::init(nullptr, nullptr);
158     GMX_RELEASE_ASSERT(!GMX_LIB_MPI || gmx_mpi_initialized(),
159                        "MPI should be initialized before reaching this point.");
160     if (this->communicator() != MPI_COMM_NULL)
161     {
162         // Synchronise at the point of acquiring a MpiContextManager.
163         gmx_barrier(this->communicator());
164     }
165 };
166
167 MpiContextManager::~MpiContextManager()
168 {
169     if (communicator_)
170     {
171         // This is always safe to call. It is a no-op if
172         // thread-MPI, and if the constructor completed then the
173         // MPI library is initialized with reference counting.
174         gmx::finalize();
175     }
176 }
177
178 MpiContextManager::MpiContextManager() : MpiContextManager(validCommunicator()) {}
179
180 MPI_Comm MpiContextManager::communicator() const
181 {
182     if (!communicator_)
183     {
184         throw UsageError("Invalid MpiContextManager. Accessed after `move`?");
185     }
186     return *communicator_;
187 }
188
189 ContextImpl::~ContextImpl() = default;
190
191 [[maybe_unused]] static Context createContext(const ResourceAssignment& resources, const gmxLibMpi&)
192 {
193     CommHandle handle;
194     resources.applyCommunicator(&handle);
195     if (handle.communicator == MPI_COMM_NULL)
196     {
197         throw UsageError("MPI-enabled Simulator contexts require a valid communicator.");
198     }
199     auto contextmanager = MpiContextManager(handle.communicator);
200     auto impl           = ContextImpl::create(std::move(contextmanager));
201     GMX_ASSERT(impl, "ContextImpl creation method should not be able to return null.");
202     auto context = Context(impl);
203     return context;
204 }
205
206 [[maybe_unused]] static Context createContext(const ResourceAssignment& resources, const gmxThreadMpi&)
207 {
208     if (resources.size() > 1)
209     {
210         throw UsageError("Only one thread-MPI Simulation per Context is supported.");
211     }
212     // Thread-MPI Context does not yet have a need for user-provided resources.
213     // However, see #3650.
214     return createContext();
215 }
216
217 Context createContext(const ResourceAssignment& resources)
218 {
219     return createContext(resources, hasLibraryMpi<GMX_LIB_MPI>());
220 }
221
222 Context createContext()
223 {
224     MpiContextManager contextmanager;
225     auto              impl = ContextImpl::create(std::move(contextmanager));
226     GMX_ASSERT(impl, "ContextImpl creation method should not be able to return null.");
227     auto context = Context(impl);
228     return context;
229 }
230
231 ContextImpl::ContextImpl(MpiContextManager&& mpi) noexcept(std::is_nothrow_constructible_v<gmx::LegacyMdrunOptions>) :
232     mpi_(std::move(mpi))
233 {
234     // Confirm our understanding of the MpiContextManager invariant.
235     GMX_ASSERT(mpi_.communicator() == MPI_COMM_NULL ? !GMX_LIB_MPI : GMX_LIB_MPI,
236                "Precondition violated: inappropriate communicator for the library environment.");
237     // Make sure we didn't change the data members and overlook implementation details.
238     GMX_ASSERT(session_.expired(),
239                "This implementation assumes an expired weak_ptr at initialization.");
240 }
241
242 std::shared_ptr<ContextImpl> ContextImpl::create(MpiContextManager&& mpi)
243 {
244     std::shared_ptr<ContextImpl> impl;
245     impl.reset(new ContextImpl(std::move(mpi)));
246     return impl;
247 }
248
249 std::shared_ptr<Session> ContextImpl::launch(const Workflow& work)
250 {
251     using namespace gmx;
252     // Much of this implementation is not easily testable: we need tools to inspect simulation
253     // results and to modify simulation inputs.
254
255     std::shared_ptr<Session> launchedSession = nullptr;
256
257     // This implementation can only run one workflow at a time.
258     // Check whether we are already aware of an active session.
259     if (session_.expired())
260     {
261         // Check workflow spec, build graph for current context, launch and return new session.
262         // \todo This is specific to the session implementation...
263         auto        mdNode = work.getNode("MD");
264         std::string filename{};
265         if (mdNode != nullptr)
266         {
267             filename = mdNode->params();
268         }
269
270         /* Mock up the argv interface used by option processing infrastructure.
271          *
272          * As default behavior, automatically extend trajectories from the checkpoint file.
273          * In the future, our API for objects used to initialize a simulation needs to address the fact that currently a
274          * microstate requires data from both the TPR and checkpoint file to be fully specified. Put another way,
275          * current
276          * GROMACS simulations can take a "configuration" as input that does not constitute a complete microstate in
277          * terms of hidden degrees of freedom (integrator/thermostat/barostat/PRNG state), but we want a clear notion of
278          * a microstate for gmxapi interfaces.
279          *
280          * TODO: Remove `-s` and `-cpi` arguments.
281          *       Ref: https://gitlab.com/gromacs/gromacs/-/issues/3652
282          */
283
284         // Set input TPR name
285         mdArgs_.emplace_back("-s");
286         mdArgs_.emplace_back(filename);
287
288         // Set checkpoint file name
289         mdArgs_.emplace_back("-cpi");
290         mdArgs_.emplace_back("state.cpt");
291         /* Note: we normalize the checkpoint file name, but not its full path.
292          * Through version 0.0.8, gmxapi clients change working directory
293          * for each session, so relative path(s) below are appropriate.
294          * A future gmxapi version should avoid changing directories once the
295          * process starts and instead manage files (paths) in an absolute and
296          * immutable way, with abstraction provided through the Context chain-of-responsibility.
297          * TODO: API abstractions for initializing simulations that may be new or partially
298          * complete. Reference gmxapi milestone 13 at https://gitlab.com/gromacs/gromacs/-/issues/2585
299          */
300
301         // Create a mock argv. Note that argv[0] is expected to hold the program name.
302         const int  offset = 1;
303         const auto argc   = static_cast<size_t>(mdArgs_.size() + offset);
304         auto       argv   = std::vector<char*>(argc, nullptr);
305         // argv[0] is ignored, but should be a valid string (e.g. null terminated array of char)
306         argv[0]  = new char[1];
307         *argv[0] = '\0';
308         for (size_t argvIndex = offset; argvIndex < argc; ++argvIndex)
309         {
310             const auto& mdArg = mdArgs_[argvIndex - offset];
311             argv[argvIndex]   = new char[mdArg.length() + 1];
312             strcpy(argv[argvIndex], mdArg.c_str());
313         }
314
315         auto mdModules = std::make_unique<MDModules>();
316
317         const char* desc[] = { "gmxapi placeholder text" };
318
319         // LegacyMdrunOptions needs to be kept alive for the life of ContextImpl,
320         // so we use a data member for now.
321         gmx::LegacyMdrunOptions& options = options_;
322         if (options.updateFromCommandLine(argc, argv.data(), desc) == 0)
323         {
324             return nullptr;
325         }
326
327         ArrayRef<const std::string> multiSimDirectoryNames =
328                 opt2fnsIfOptionSet("-multidir", ssize(options.filenames), options.filenames.data());
329
330
331         // The SimulationContext is necessary with gmxapi so that
332         // resources owned by the client code can have suitable
333         // lifetime. The gmx wrapper binary uses the same infrastructure,
334         // but the lifetime is now trivially that of the invocation of the
335         // wrapper binary.
336         auto communicator = mpi_.communicator();
337         // Confirm the precondition for simulationContext().
338         GMX_ASSERT(communicator == MPI_COMM_NULL ? !GMX_LIB_MPI : GMX_LIB_MPI,
339                    "Context communicator does not have an appropriate value for the environment.");
340         SimulationContext simulationContext(communicator, multiSimDirectoryNames);
341
342
343         StartingBehavior startingBehavior        = StartingBehavior::NewSimulation;
344         LogFilePtr       logFileGuard            = nullptr;
345         gmx_multisim_t*  ms                      = simulationContext.multiSimulation_.get();
346         std::tie(startingBehavior, logFileGuard) = handleRestart(
347                 findIsSimulationMasterRank(ms, simulationContext.simulationCommunicator_),
348                 simulationContext.simulationCommunicator_, ms, options.mdrunOptions.appendingBehavior,
349                 ssize(options.filenames), options.filenames.data());
350
351         auto builder = MdrunnerBuilder(std::move(mdModules),
352                                        compat::not_null<SimulationContext*>(&simulationContext));
353         builder.addSimulationMethod(options.mdrunOptions, options.pforce, startingBehavior);
354         builder.addDomainDecomposition(options.domdecOptions);
355         // \todo pass by value
356         builder.addNonBonded(options.nbpu_opt_choices[0]);
357         // \todo pass by value
358         builder.addElectrostatics(options.pme_opt_choices[0], options.pme_fft_opt_choices[0]);
359         builder.addBondedTaskAssignment(options.bonded_opt_choices[0]);
360         builder.addUpdateTaskAssignment(options.update_opt_choices[0]);
361         builder.addNeighborList(options.nstlist_cmdline);
362         builder.addReplicaExchange(options.replExParams);
363         // Need to establish run-time values from various inputs to provide a resource handle to Mdrunner
364         builder.addHardwareOptions(options.hw_opt);
365
366         // \todo File names are parameters that should be managed modularly through further factoring.
367         builder.addFilenames(options.filenames);
368         // TODO: Remove `s` and `-cpi` from LegacyMdrunOptions before launch(). #3652
369         auto simulationInput = makeSimulationInput(options);
370         builder.addInput(simulationInput);
371
372         // Note: The gmx_output_env_t life time is not managed after the call to parse_common_args.
373         // \todo Implement lifetime management for gmx_output_env_t.
374         // \todo Output environment should be configured outside of Mdrunner and provided as a resource.
375         builder.addOutputEnvironment(options.oenv);
376         builder.addLogFile(logFileGuard.get());
377
378         // Note, creation is not mature enough to be exposed in the external API yet.
379         launchedSession = createSession(shared_from_this(), std::move(builder),
380                                         std::move(simulationContext), std::move(logFileGuard));
381
382         // Clean up argv once builder is no longer in use
383         // TODO: Remove long-lived references to argv so this is no longer necessary.
384         //       Ref https://gitlab.com/gromacs/gromacs/-/issues/2877
385         for (auto&& string : argv)
386         {
387             if (string != nullptr)
388             {
389                 delete[] string;
390                 string = nullptr;
391             }
392         }
393     }
394     else
395     {
396         throw gmxapi::ProtocolError("Tried to launch a session while a session is still active.");
397     }
398
399     if (launchedSession != nullptr)
400     {
401         // Update weak reference.
402         session_ = launchedSession;
403     }
404     return launchedSession;
405 }
406
407 std::shared_ptr<Session> Context::launch(const Workflow& work)
408 {
409     return impl_->launch(work);
410 }
411
412 Context::Context(std::shared_ptr<ContextImpl> impl) : impl_{ std::move(impl) }
413 {
414     if (!impl_)
415     {
416         throw UsageError("Context requires a non-null implementation member.");
417     }
418 }
419
420 void Context::setMDArgs(const MDArgs& mdArgs)
421 {
422     impl_->mdArgs_ = mdArgs;
423 }
424
425 Context::~Context() = default;
426
427 } // end namespace gmxapi