2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
36 * \brief Implementation details of gmxapi::Context
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.
42 * \author M. Eric Irrgang <ericirrgang@gmail.com>
46 #include "gmxapi/context.h"
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"
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"
76 #include "context_impl.h"
77 #include "createsession.h"
78 #include "session_impl.h"
84 // Support some tag dispatch. Warning: These are just aliases (not strong types).
86 * \brief Logical helper alias to convert preprocessor constant to type.
88 * \tparam Value Provide the GMX\_LIB\_MPI macro.
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.
97 using gmxThreadMpi = hasLibraryMpi<false>;
98 using gmxLibMpi = hasLibraryMpi<true>;
99 using MpiType = std::conditional_t<GMX_LIB_MPI, gmxLibMpi, gmxThreadMpi>;
101 using MpiContextInitializationError = BasicException<struct MpiContextInitialization>;
105 * \brief Helpers to evaluate the correct precondition for the library build.
107 * TODO: (#3650) Consider distinct MpiContextManager types for clearer definition of preconditions.
112 [[maybe_unused]] MPI_Comm validCommunicator(const MPI_Comm& communicator, const gmxThreadMpi&)
114 if (communicator != MPI_COMM_NULL)
116 throw MpiContextInitializationError(
117 "Provided communicator must be MPI_COMM_NULL for GROMACS built without MPI "
123 [[maybe_unused]] MPI_Comm validCommunicator(const MPI_Comm& communicator, const gmxLibMpi&)
125 if (communicator == MPI_COMM_NULL)
127 throw MpiContextInitializationError("MPI-enabled GROMACS requires a valid communicator.");
133 * \brief Return the communicator if it is appropriate for the environment.
135 * \throws MpiContextInitializationError if communicator does not match the
136 * MpiContextManager precondition for the current library configuration.
138 MPI_Comm validCommunicator(const MPI_Comm& communicator)
140 return validCommunicator(communicator, MpiType());
143 //! \brief Provide a reasonable default value.
144 MPI_Comm validCommunicator()
146 return GMX_LIB_MPI ? MPI_COMM_WORLD : MPI_COMM_NULL;
149 } // anonymous namespace
151 MpiContextManager::MpiContextManager(MPI_Comm communicator) :
152 communicator_(std::make_unique<MPI_Comm>(validCommunicator(communicator)))
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)
162 // Synchronise at the point of acquiring a MpiContextManager.
163 gmx_barrier(this->communicator());
167 MpiContextManager::~MpiContextManager()
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.
178 MpiContextManager::MpiContextManager() : MpiContextManager(validCommunicator()) {}
180 MPI_Comm MpiContextManager::communicator() const
184 throw UsageError("Invalid MpiContextManager. Accessed after `move`?");
186 return *communicator_;
189 ContextImpl::~ContextImpl() = default;
191 [[maybe_unused]] static Context createContext(const ResourceAssignment& resources, const gmxLibMpi&)
194 resources.applyCommunicator(&handle);
195 if (handle.communicator == MPI_COMM_NULL)
197 throw UsageError("MPI-enabled Simulator contexts require a valid communicator.");
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);
206 [[maybe_unused]] static Context createContext(const ResourceAssignment& resources, const gmxThreadMpi&)
208 if (resources.size() > 1)
210 throw UsageError("Only one thread-MPI Simulation per Context is supported.");
212 // Thread-MPI Context does not yet have a need for user-provided resources.
213 // However, see #3650.
214 return createContext();
217 Context createContext(const ResourceAssignment& resources)
219 return createContext(resources, hasLibraryMpi<GMX_LIB_MPI>());
222 Context createContext()
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);
231 ContextImpl::ContextImpl(MpiContextManager&& mpi) noexcept(std::is_nothrow_constructible_v<gmx::LegacyMdrunOptions>) :
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.");
242 std::shared_ptr<ContextImpl> ContextImpl::create(MpiContextManager&& mpi)
244 std::shared_ptr<ContextImpl> impl;
245 impl.reset(new ContextImpl(std::move(mpi)));
249 std::shared_ptr<Session> ContextImpl::launch(const Workflow& work)
252 // Much of this implementation is not easily testable: we need tools to inspect simulation
253 // results and to modify simulation inputs.
255 std::shared_ptr<Session> launchedSession = nullptr;
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())
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)
267 filename = mdNode->params();
270 /* Mock up the argv interface used by option processing infrastructure.
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,
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.
280 * TODO: Remove `-s` and `-cpi` arguments.
281 * Ref: https://gitlab.com/gromacs/gromacs/-/issues/3652
284 // Set input TPR name
285 mdArgs_.emplace_back("-s");
286 mdArgs_.emplace_back(filename);
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
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];
308 for (size_t argvIndex = offset; argvIndex < argc; ++argvIndex)
310 const auto& mdArg = mdArgs_[argvIndex - offset];
311 argv[argvIndex] = new char[mdArg.length() + 1];
312 strcpy(argv[argvIndex], mdArg.c_str());
315 auto mdModules = std::make_unique<MDModules>();
317 const char* desc[] = { "gmxapi placeholder text" };
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)
327 ArrayRef<const std::string> multiSimDirectoryNames =
328 opt2fnsIfOptionSet("-multidir", ssize(options.filenames), options.filenames.data());
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
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);
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());
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);
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);
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());
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));
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)
387 if (string != nullptr)
396 throw gmxapi::ProtocolError("Tried to launch a session while a session is still active.");
399 if (launchedSession != nullptr)
401 // Update weak reference.
402 session_ = launchedSession;
404 return launchedSession;
407 std::shared_ptr<Session> Context::launch(const Workflow& work)
409 return impl_->launch(work);
412 Context::Context(std::shared_ptr<ContextImpl> impl) : impl_{ std::move(impl) }
416 throw UsageError("Context requires a non-null implementation member.");
420 void Context::setMDArgs(const MDArgs& mdArgs)
422 impl_->mdArgs_ = mdArgs;
425 Context::~Context() = default;
427 } // end namespace gmxapi