2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2019,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 Defines the modular simulator
38 * \author Pascal Merz <pascal.merz@me.com>
39 * \ingroup module_modularsimulator
44 #include "modularsimulator.h"
46 #include "gromacs/commandline/filenm.h"
47 #include "gromacs/domdec/domdec.h"
48 #include "gromacs/ewald/pme.h"
49 #include "gromacs/ewald/pme_load_balancing.h"
50 #include "gromacs/gmxlib/network.h"
51 #include "gromacs/gmxlib/nrnb.h"
52 #include "gromacs/math/vec.h"
53 #include "gromacs/mdlib/checkpointhandler.h"
54 #include "gromacs/mdlib/constr.h"
55 #include "gromacs/mdlib/energyoutput.h"
56 #include "gromacs/mdlib/mdatoms.h"
57 #include "gromacs/mdlib/resethandler.h"
58 #include "gromacs/mdlib/stat.h"
59 #include "gromacs/mdlib/update.h"
60 #include "gromacs/mdrun/replicaexchange.h"
61 #include "gromacs/mdrun/shellfc.h"
62 #include "gromacs/mdrunutility/handlerestart.h"
63 #include "gromacs/mdrunutility/printtime.h"
64 #include "gromacs/mdtypes/commrec.h"
65 #include "gromacs/mdtypes/fcdata.h"
66 #include "gromacs/mdtypes/inputrec.h"
67 #include "gromacs/mdtypes/mdrunoptions.h"
68 #include "gromacs/mdtypes/observableshistory.h"
69 #include "gromacs/mdtypes/state.h"
70 #include "gromacs/nbnxm/nbnxm.h"
71 #include "gromacs/timing/walltime_accounting.h"
72 #include "gromacs/topology/topology.h"
73 #include "gromacs/utility/cstringutil.h"
74 #include "gromacs/utility/fatalerror.h"
76 #include "compositesimulatorelement.h"
77 #include "computeglobalselement.h"
78 #include "constraintelement.h"
79 #include "energyelement.h"
80 #include "forceelement.h"
81 #include "freeenergyperturbationelement.h"
82 #include "parrinellorahmanbarostat.h"
83 #include "propagator.h"
84 #include "shellfcelement.h"
85 #include "signallers.h"
86 #include "statepropagatordata.h"
87 #include "trajectoryelement.h"
88 #include "vrescalethermostat.h"
92 void ModularSimulator::run()
94 GMX_LOG(mdlog.info).asParagraph().appendText("Using the modular simulator.");
95 constructElementsAndSignallers();
97 for (auto& signaller : signallerCallList_)
99 signaller->signallerSetup();
103 domDecHelper_->setup();
106 for (auto& element : elementsOwnershipList_)
108 element->elementSetup();
110 if (pmeLoadBalanceHelper_)
112 // State must have been initialized so pmeLoadBalanceHelper_ gets a valid box
113 pmeLoadBalanceHelper_->setup();
116 while (step_ <= signalHelper_->lastStep_)
120 while (!taskQueue_.empty())
122 auto task = std::move(taskQueue_.front());
129 for (auto& element : elementsOwnershipList_)
131 element->elementTeardown();
133 if (pmeLoadBalanceHelper_)
135 pmeLoadBalanceHelper_->teardown();
140 void ModularSimulator::simulatorSetup()
142 if (!mdrunOptions.writeConfout)
144 // This is on by default, and the main known use case for
145 // turning it off is for convenience in benchmarking, which is
146 // something that should not show up in the general user
151 "The -noconfout functionality is deprecated, and "
152 "may be removed in a future version.");
157 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
158 std::string timeString;
159 fprintf(stderr, "starting mdrun '%s'\n", *(top_global->name));
160 if (inputrec->nsteps >= 0)
162 timeString = formatString("%8.1f", static_cast<double>(inputrec->init_step + inputrec->nsteps)
163 * inputrec->delta_t);
167 timeString = "infinite";
169 if (inputrec->init_step > 0)
171 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
172 gmx_step_str(inputrec->init_step + inputrec->nsteps, sbuf), timeString.c_str(),
173 gmx_step_str(inputrec->init_step, sbuf2), inputrec->init_step * inputrec->delta_t);
177 fprintf(stderr, "%s steps, %s ps.\n", gmx_step_str(inputrec->nsteps, sbuf),
180 fprintf(fplog, "\n");
183 walltime_accounting_start_time(walltime_accounting);
184 wallcycle_start(wcycle, ewcRUN);
185 print_start(fplog, cr, walltime_accounting, "mdrun");
187 step_ = inputrec->init_step;
190 void ModularSimulator::preStep(Step step, Time gmx_unused time, bool isNeighborSearchingStep)
192 if (stopHandler_->stoppingAfterCurrentStep(isNeighborSearchingStep) && step != signalHelper_->lastStep_)
195 * Stop handler wants to stop after the current step, which was
196 * not known when building the current task queue. This happens
197 * e.g. when a stop is signalled by OS. We therefore want to purge
198 * the task queue now, and re-schedule this step as last step.
201 std::queue<SimulatorRunFunctionPtr>().swap(taskQueue_);
207 resetHandler_->setSignal(walltime_accounting);
208 // This is a hack to avoid having to rewrite StopHandler to be a NeighborSearchSignaller
209 // and accept the step as input. Eventually, we want to do that, but currently this would
210 // require introducing NeighborSearchSignaller in the legacy do_md or a lot of code
212 stophandlerIsNSStep_ = isNeighborSearchingStep;
213 stophandlerCurrentStep_ = step;
214 stopHandler_->setSignal();
216 wallcycle_start(wcycle, ewcSTEP);
219 void ModularSimulator::postStep(Step step, Time gmx_unused time)
224 if (do_per_step(step, inputrec->nstlog))
226 if (fflush(fplog) != 0)
228 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
232 const bool do_verbose = mdrunOptions.verbose
233 && (step % mdrunOptions.verboseStepPrintInterval == 0
234 || step == inputrec->init_step || step == signalHelper_->lastStep_);
235 // Print the remaining wall clock time for the run
236 if (MASTER(cr) && (do_verbose || gmx_got_usr_signal())
237 && !(pmeLoadBalanceHelper_ && pmeLoadBalanceHelper_->pmePrinting()))
239 print_time(stderr, walltime_accounting, step, inputrec, cr);
242 double cycles = wallcycle_stop(wcycle, ewcSTEP);
243 if (DOMAINDECOMP(cr) && wcycle)
245 dd_cycles_add(cr->dd, static_cast<float>(cycles), ddCyclStep);
248 resetHandler_->resetCounters(
249 step, step - inputrec->init_step, mdlog, fplog, cr, fr->nbv.get(), nrnb, fr->pmedata,
250 pmeLoadBalanceHelper_ ? pmeLoadBalanceHelper_->loadBalancingObject() : nullptr, wcycle,
251 walltime_accounting);
254 void ModularSimulator::simulatorTeardown()
257 // Stop measuring walltime
258 walltime_accounting_end_time(walltime_accounting);
260 if (!thisRankHasDuty(cr, DUTY_PME))
262 /* Tell the PME only node to finish */
263 gmx_pme_send_finish(cr);
266 walltime_accounting_set_nsteps_done(walltime_accounting, step_ - inputrec->init_step);
269 void ModularSimulator::populateTaskQueue()
271 auto registerRunFunction = std::make_unique<RegisterRunFunction>(
272 [this](SimulatorRunFunctionPtr ptr) { taskQueue_.push(std::move(ptr)); });
274 Time startTime = inputrec->init_t;
275 Time timeStep = inputrec->delta_t;
276 Time time = startTime + step_ * timeStep;
278 // Run an initial call to the signallers
279 for (auto& signaller : signallerCallList_)
281 signaller->signal(step_, time);
284 if (checkpointHelper_)
286 checkpointHelper_->run(step_, time);
289 if (pmeLoadBalanceHelper_)
291 pmeLoadBalanceHelper_->run(step_, time);
295 domDecHelper_->run(step_, time);
300 // local variables for lambda capturing
301 const int step = step_;
302 const bool isNSStep = step == signalHelper_->nextNSStep_;
305 (*registerRunFunction)(std::make_unique<SimulatorRunFunction>(
306 [this, step, time, isNSStep]() { preStep(step, time, isNSStep); }));
307 // register elements for step
308 for (auto& element : elementCallList_)
310 element->scheduleTask(step_, time, registerRunFunction);
312 // register post-step
313 (*registerRunFunction)(
314 std::make_unique<SimulatorRunFunction>([this, step, time]() { postStep(step, time); }));
318 time = startTime + step_ * timeStep;
319 for (auto& signaller : signallerCallList_)
321 signaller->signal(step_, time);
323 } while (step_ != signalHelper_->nextNSStep_ && step_ <= signalHelper_->lastStep_);
326 void ModularSimulator::constructElementsAndSignallers()
328 /* When restarting from a checkpoint, it can be appropriate to
329 * initialize ekind from quantities in the checkpoint. Otherwise,
330 * compute_globals must initialize ekind before the simulation
331 * starts/restarts. However, only the master rank knows what was
332 * found in the checkpoint file, so we have to communicate in
333 * order to coordinate the restart.
335 * TODO (modular) This should become obsolete when checkpoint reading
336 * happens within the modular simulator framework: The energy
337 * element should read its data from the checkpoint file pointer,
338 * and signal to the compute globals element if it needs anything
341 * TODO (legacy) Consider removing this communication if/when checkpoint
342 * reading directly follows .tpr reading, because all ranks can
343 * agree on hasReadEkinState at that time.
345 bool hasReadEkinState = MASTER(cr) ? state_global->ekinstate.hasReadEkinState : false;
348 gmx_bcast(sizeof(hasReadEkinState), &hasReadEkinState, cr);
350 if (hasReadEkinState)
352 restore_ekinstate_from_state(cr, ekind, &state_global->ekinstate);
356 * Build data structures
359 std::make_unique<TopologyHolder>(*top_global, cr, inputrec, fr, mdAtoms, constr, vsite);
361 std::unique_ptr<FreeEnergyPerturbationElement> freeEnergyPerturbationElement = nullptr;
362 FreeEnergyPerturbationElement* freeEnergyPerturbationElementPtr = nullptr;
363 if (inputrec->efep != efepNO)
365 freeEnergyPerturbationElement =
366 std::make_unique<FreeEnergyPerturbationElement>(fplog, inputrec, mdAtoms);
367 freeEnergyPerturbationElementPtr = freeEnergyPerturbationElement.get();
370 auto statePropagatorData = std::make_unique<StatePropagatorData>(
371 top_global->natoms, fplog, cr, state_global, inputrec->nstxout, inputrec->nstvout,
372 inputrec->nstfout, inputrec->nstxout_compressed, fr->nbv->useGpu(),
373 freeEnergyPerturbationElementPtr, topologyHolder_.get(), fr->bMolPBC,
374 mdrunOptions.writeConfout, opt2fn("-c", nfile, fnm), inputrec, mdAtoms->mdatoms());
375 auto statePropagatorDataPtr = compat::make_not_null(statePropagatorData.get());
377 auto energyElement = std::make_unique<EnergyElement>(
378 statePropagatorDataPtr, freeEnergyPerturbationElementPtr, top_global, inputrec, mdAtoms,
379 enerd, ekind, constr, fplog, fcd, mdModulesNotifier, MASTER(cr), observablesHistory,
381 auto energyElementPtr = compat::make_not_null(energyElement.get());
386 const bool simulationsShareState = false;
387 stopHandler_ = stopHandlerBuilder->getStopHandlerMD(
388 compat::not_null<SimulationSignal*>(&signals_[eglsSTOPCOND]), simulationsShareState,
389 MASTER(cr), inputrec->nstlist, mdrunOptions.reproducible, nstglobalcomm_,
390 mdrunOptions.maximumHoursToRun, inputrec->nstlist == 0, fplog, stophandlerCurrentStep_,
391 stophandlerIsNSStep_, walltime_accounting);
394 * Create simulator builders
396 SignallerBuilder<NeighborSearchSignaller> neighborSearchSignallerBuilder;
397 SignallerBuilder<LastStepSignaller> lastStepSignallerBuilder;
398 SignallerBuilder<LoggingSignaller> loggingSignallerBuilder;
399 SignallerBuilder<EnergySignaller> energySignallerBuilder;
400 TrajectoryElementBuilder trajectoryElementBuilder;
403 * Register data structures to signallers
405 trajectoryElementBuilder.registerWriterClient(statePropagatorDataPtr);
406 trajectoryElementBuilder.registerSignallerClient(statePropagatorDataPtr);
407 lastStepSignallerBuilder.registerSignallerClient(statePropagatorDataPtr);
409 trajectoryElementBuilder.registerWriterClient(energyElementPtr);
410 trajectoryElementBuilder.registerSignallerClient(energyElementPtr);
411 energySignallerBuilder.registerSignallerClient(energyElementPtr);
413 // Register the simulator itself to the neighbor search / last step signaller
414 neighborSearchSignallerBuilder.registerSignallerClient(compat::make_not_null(signalHelper_.get()));
415 lastStepSignallerBuilder.registerSignallerClient(compat::make_not_null(signalHelper_.get()));
418 * Build integrator - this takes care of force calculation, propagation,
419 * constraining, and of the place the statePropagatorData and the energy element
420 * have a full timestep state.
422 // TODO: Make a CheckpointHelperBuilder
423 std::vector<ICheckpointHelperClient*> checkpointClients = { statePropagatorDataPtr, energyElementPtr,
424 freeEnergyPerturbationElementPtr };
425 CheckBondedInteractionsCallbackPtr checkBondedInteractionsCallback = nullptr;
427 buildIntegrator(&neighborSearchSignallerBuilder, &energySignallerBuilder,
428 &loggingSignallerBuilder, &trajectoryElementBuilder, &checkpointClients,
429 &checkBondedInteractionsCallback, statePropagatorDataPtr,
430 energyElementPtr, freeEnergyPerturbationElementPtr, hasReadEkinState);
433 * Build infrastructure elements
436 if (PmeLoadBalanceHelper::doPmeLoadBalancing(mdrunOptions, inputrec, fr))
438 pmeLoadBalanceHelper_ = std::make_unique<PmeLoadBalanceHelper>(
439 mdrunOptions.verbose, statePropagatorDataPtr, fplog, cr, mdlog, inputrec, wcycle, fr);
440 neighborSearchSignallerBuilder.registerSignallerClient(
441 compat::make_not_null(pmeLoadBalanceHelper_.get()));
444 if (DOMAINDECOMP(cr))
446 GMX_ASSERT(checkBondedInteractionsCallback,
447 "Domain decomposition needs a callback for check the number of bonded "
449 domDecHelper_ = std::make_unique<DomDecHelper>(
450 mdrunOptions.verbose, mdrunOptions.verboseStepPrintInterval, statePropagatorDataPtr,
451 topologyHolder_.get(), std::move(checkBondedInteractionsCallback), nstglobalcomm_, fplog,
452 cr, mdlog, constr, inputrec, mdAtoms, nrnb, wcycle, fr, vsite, imdSession, pull_work);
453 neighborSearchSignallerBuilder.registerSignallerClient(compat::make_not_null(domDecHelper_.get()));
456 const bool simulationsShareResetCounters = false;
457 resetHandler_ = std::make_unique<ResetHandler>(
458 compat::make_not_null<SimulationSignal*>(&signals_[eglsRESETCOUNTERS]),
459 simulationsShareResetCounters, inputrec->nsteps, MASTER(cr),
460 mdrunOptions.timingOptions.resetHalfway, mdrunOptions.maximumHoursToRun, mdlog, wcycle,
461 walltime_accounting);
464 * Build signaller list
466 * Note that as signallers depend on each others, the order of calling the signallers
467 * matters. It is the responsibility of this builder to ensure that the order is
470 auto energySignaller = energySignallerBuilder.build(
471 inputrec->nstcalcenergy, inputrec->fepvals->nstdhdl, inputrec->nstpcouple);
472 trajectoryElementBuilder.registerSignallerClient(compat::make_not_null(energySignaller.get()));
473 loggingSignallerBuilder.registerSignallerClient(compat::make_not_null(energySignaller.get()));
474 auto trajectoryElement = trajectoryElementBuilder.build(
475 fplog, nfile, fnm, mdrunOptions, cr, outputProvider, mdModulesNotifier, inputrec,
476 top_global, oenv, wcycle, startingBehavior);
477 loggingSignallerBuilder.registerSignallerClient(compat::make_not_null(trajectoryElement.get()));
479 // Add checkpoint helper here since we need a pointer to the trajectory element and
480 // need to register it with the lastStepSignallerBuilder
481 auto checkpointHandler = std::make_unique<CheckpointHandler>(
482 compat::make_not_null<SimulationSignal*>(&signals_[eglsCHKPT]), simulationsShareState,
483 inputrec->nstlist == 0, MASTER(cr), mdrunOptions.writeConfout,
484 mdrunOptions.checkpointOptions.period);
485 checkpointHelper_ = std::make_unique<CheckpointHelper>(
486 std::move(checkpointClients), std::move(checkpointHandler), inputrec->init_step,
487 trajectoryElement.get(), top_global->natoms, fplog, cr, observablesHistory,
488 walltime_accounting, state_global, mdrunOptions.writeConfout);
489 lastStepSignallerBuilder.registerSignallerClient(compat::make_not_null(checkpointHelper_.get()));
491 lastStepSignallerBuilder.registerSignallerClient(compat::make_not_null(trajectoryElement.get()));
492 auto loggingSignaller =
493 loggingSignallerBuilder.build(inputrec->nstlog, inputrec->init_step, inputrec->init_t);
494 lastStepSignallerBuilder.registerSignallerClient(compat::make_not_null(loggingSignaller.get()));
495 auto lastStepSignaller =
496 lastStepSignallerBuilder.build(inputrec->nsteps, inputrec->init_step, stopHandler_.get());
497 neighborSearchSignallerBuilder.registerSignallerClient(compat::make_not_null(lastStepSignaller.get()));
498 auto neighborSearchSignaller = neighborSearchSignallerBuilder.build(
499 inputrec->nstlist, inputrec->init_step, inputrec->init_t);
501 addToCallListAndMove(std::move(neighborSearchSignaller), signallerCallList_, signallersOwnershipList_);
502 addToCallListAndMove(std::move(lastStepSignaller), signallerCallList_, signallersOwnershipList_);
503 addToCallListAndMove(std::move(loggingSignaller), signallerCallList_, signallersOwnershipList_);
504 addToCallList(trajectoryElement, signallerCallList_);
505 addToCallListAndMove(std::move(energySignaller), signallerCallList_, signallersOwnershipList_);
508 * Build the element list
510 * This is the actual sequence of (non-infrastructure) elements to be run.
511 * For NVE, the trajectory element is used outside of the integrator
512 * (composite) element, as well as the checkpoint helper. The checkpoint
513 * helper should be on top of the loop, and is only part of the simulator
514 * call list to be able to react to the last step being signalled.
516 addToCallList(checkpointHelper_, elementCallList_);
517 if (freeEnergyPerturbationElement)
519 addToCallListAndMove(std::move(freeEnergyPerturbationElement), elementCallList_,
520 elementsOwnershipList_);
522 addToCallListAndMove(std::move(integrator), elementCallList_, elementsOwnershipList_);
523 addToCallListAndMove(std::move(trajectoryElement), elementCallList_, elementsOwnershipList_);
524 // for vv, we need to setup statePropagatorData after the compute
525 // globals so that we reset the right velocities
526 // TODO: Avoid this by getting rid of the need of resetting velocities in vv
527 elementsOwnershipList_.emplace_back(std::move(statePropagatorData));
528 elementsOwnershipList_.emplace_back(std::move(energyElement));
531 std::unique_ptr<ISimulatorElement>
532 ModularSimulator::buildForces(SignallerBuilder<NeighborSearchSignaller>* neighborSearchSignallerBuilder,
533 SignallerBuilder<EnergySignaller>* energySignallerBuilder,
534 StatePropagatorData* statePropagatorDataPtr,
535 EnergyElement* energyElementPtr,
536 FreeEnergyPerturbationElement* freeEnergyPerturbationElement)
538 const bool isVerbose = mdrunOptions.verbose;
539 const bool isDynamicBox = inputrecDynamicBox(inputrec);
540 // Check for polarizable models and flexible constraints
541 if (ShellFCElement::doShellsOrFlexConstraints(topologyHolder_->globalTopology(),
542 constr ? constr->numFlexibleConstraints() : 0))
544 auto shellFCElement = std::make_unique<ShellFCElement>(
545 statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElement, isVerbose,
546 isDynamicBox, fplog, cr, inputrec, mdAtoms, nrnb, fr, fcd, wcycle, runScheduleWork, vsite,
547 imdSession, pull_work, constr, &topologyHolder_->globalTopology(), enforcedRotation);
548 topologyHolder_->registerClient(shellFCElement.get());
549 neighborSearchSignallerBuilder->registerSignallerClient(
550 compat::make_not_null(shellFCElement.get()));
551 energySignallerBuilder->registerSignallerClient(compat::make_not_null(shellFCElement.get()));
553 // std::move *should* not be needed with c++-14, but clang-3.6 still requires it
554 return std::move(shellFCElement);
558 auto forceElement = std::make_unique<ForceElement>(
559 statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElement,
560 isDynamicBox, fplog, cr, inputrec, mdAtoms, nrnb, fr, fcd, wcycle, runScheduleWork,
561 vsite, imdSession, pull_work, enforcedRotation);
562 topologyHolder_->registerClient(forceElement.get());
563 neighborSearchSignallerBuilder->registerSignallerClient(compat::make_not_null(forceElement.get()));
564 energySignallerBuilder->registerSignallerClient(compat::make_not_null(forceElement.get()));
566 // std::move *should* not be needed with c++-14, but clang-3.6 still requires it
567 return std::move(forceElement);
571 std::unique_ptr<ISimulatorElement> ModularSimulator::buildIntegrator(
572 SignallerBuilder<NeighborSearchSignaller>* neighborSearchSignallerBuilder,
573 SignallerBuilder<EnergySignaller>* energySignallerBuilder,
574 SignallerBuilder<LoggingSignaller>* loggingSignallerBuilder,
575 TrajectoryElementBuilder* trajectoryElementBuilder,
576 std::vector<ICheckpointHelperClient*>* checkpointClients,
577 CheckBondedInteractionsCallbackPtr* checkBondedInteractionsCallback,
578 compat::not_null<StatePropagatorData*> statePropagatorDataPtr,
579 compat::not_null<EnergyElement*> energyElementPtr,
580 FreeEnergyPerturbationElement* freeEnergyPerturbationElementPtr,
581 bool hasReadEkinState)
584 buildForces(neighborSearchSignallerBuilder, energySignallerBuilder,
585 statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr);
587 // list of elements owned by the simulator composite object
588 std::vector<std::unique_ptr<ISimulatorElement>> elementsOwnershipList;
589 // call list of the simulator composite object
590 std::vector<compat::not_null<ISimulatorElement*>> elementCallList;
592 std::function<void()> needToCheckNumberOfBondedInteractions;
593 if (inputrec->eI == eiMD)
595 auto computeGlobalsElement =
596 std::make_unique<ComputeGlobalsElement<ComputeGlobalsAlgorithm::LeapFrog>>(
597 statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr,
598 &signals_, nstglobalcomm_, fplog, mdlog, cr, inputrec, mdAtoms, nrnb,
599 wcycle, fr, &topologyHolder_->globalTopology(), constr, hasReadEkinState);
600 topologyHolder_->registerClient(computeGlobalsElement.get());
601 energySignallerBuilder->registerSignallerClient(compat::make_not_null(computeGlobalsElement.get()));
602 trajectoryElementBuilder->registerSignallerClient(
603 compat::make_not_null(computeGlobalsElement.get()));
605 *checkBondedInteractionsCallback =
606 computeGlobalsElement->getCheckNumberOfBondedInteractionsCallback();
608 auto propagator = std::make_unique<Propagator<IntegrationStep::LeapFrog>>(
609 inputrec->delta_t, statePropagatorDataPtr, mdAtoms, wcycle);
611 addToCallListAndMove(std::move(forceElement), elementCallList, elementsOwnershipList);
612 addToCallList(statePropagatorDataPtr, elementCallList); // we have a full microstate at time t here!
613 if (inputrec->etc == etcVRESCALE)
615 // TODO: With increased complexity of the propagator, this will need further development,
616 // e.g. using propagators templated for velocity propagation policies and a builder
617 propagator->setNumVelocityScalingVariables(inputrec->opts.ngtc);
618 auto thermostat = std::make_unique<VRescaleThermostat>(
619 inputrec->nsttcouple, -1, false, inputrec->ld_seed, inputrec->opts.ngtc,
620 inputrec->delta_t * inputrec->nsttcouple, inputrec->opts.ref_t, inputrec->opts.tau_t,
621 inputrec->opts.nrdf, energyElementPtr, propagator->viewOnVelocityScaling(),
622 propagator->velocityScalingCallback(), state_global, cr, inputrec->bContinuation);
623 checkpointClients->emplace_back(thermostat.get());
624 energyElementPtr->setVRescaleThermostat(thermostat.get());
625 addToCallListAndMove(std::move(thermostat), elementCallList, elementsOwnershipList);
628 std::unique_ptr<ParrinelloRahmanBarostat> prBarostat = nullptr;
629 if (inputrec->epc == epcPARRINELLORAHMAN)
631 // Building the PR barostat here since it needs access to the propagator
632 // and we want to be able to move the propagator object
633 prBarostat = std::make_unique<ParrinelloRahmanBarostat>(
634 inputrec->nstpcouple, -1, inputrec->delta_t * inputrec->nstpcouple,
635 inputrec->init_step, propagator->viewOnPRScalingMatrix(),
636 propagator->prScalingCallback(), statePropagatorDataPtr, energyElementPtr,
637 fplog, inputrec, mdAtoms, state_global, cr, inputrec->bContinuation);
638 energyElementPtr->setParrinelloRahamnBarostat(prBarostat.get());
639 checkpointClients->emplace_back(prBarostat.get());
641 addToCallListAndMove(std::move(propagator), elementCallList, elementsOwnershipList);
644 auto constraintElement = std::make_unique<ConstraintsElement<ConstraintVariable::Positions>>(
645 constr, statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr,
646 MASTER(cr), fplog, inputrec, mdAtoms->mdatoms());
647 auto constraintElementPtr = compat::make_not_null(constraintElement.get());
648 energySignallerBuilder->registerSignallerClient(constraintElementPtr);
649 trajectoryElementBuilder->registerSignallerClient(constraintElementPtr);
650 loggingSignallerBuilder->registerSignallerClient(constraintElementPtr);
652 addToCallListAndMove(std::move(constraintElement), elementCallList, elementsOwnershipList);
655 addToCallListAndMove(std::move(computeGlobalsElement), elementCallList, elementsOwnershipList);
656 addToCallList(energyElementPtr, elementCallList); // we have the energies at time t here!
659 addToCallListAndMove(std::move(prBarostat), elementCallList, elementsOwnershipList);
662 else if (inputrec->eI == eiVV)
664 auto computeGlobalsElementAtFullTimeStep =
665 std::make_unique<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerletAtFullTimeStep>>(
666 statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr,
667 &signals_, nstglobalcomm_, fplog, mdlog, cr, inputrec, mdAtoms, nrnb,
668 wcycle, fr, &topologyHolder_->globalTopology(), constr, hasReadEkinState);
669 topologyHolder_->registerClient(computeGlobalsElementAtFullTimeStep.get());
670 energySignallerBuilder->registerSignallerClient(
671 compat::make_not_null(computeGlobalsElementAtFullTimeStep.get()));
672 trajectoryElementBuilder->registerSignallerClient(
673 compat::make_not_null(computeGlobalsElementAtFullTimeStep.get()));
675 auto computeGlobalsElementAfterCoordinateUpdate =
676 std::make_unique<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerletAfterCoordinateUpdate>>(
677 statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr,
678 &signals_, nstglobalcomm_, fplog, mdlog, cr, inputrec, mdAtoms, nrnb,
679 wcycle, fr, &topologyHolder_->globalTopology(), constr, hasReadEkinState);
680 topologyHolder_->registerClient(computeGlobalsElementAfterCoordinateUpdate.get());
681 energySignallerBuilder->registerSignallerClient(
682 compat::make_not_null(computeGlobalsElementAfterCoordinateUpdate.get()));
683 trajectoryElementBuilder->registerSignallerClient(
684 compat::make_not_null(computeGlobalsElementAfterCoordinateUpdate.get()));
686 *checkBondedInteractionsCallback =
687 computeGlobalsElementAfterCoordinateUpdate->getCheckNumberOfBondedInteractionsCallback();
689 auto propagatorVelocities = std::make_unique<Propagator<IntegrationStep::VelocitiesOnly>>(
690 inputrec->delta_t * 0.5, statePropagatorDataPtr, mdAtoms, wcycle);
691 auto propagatorVelocitiesAndPositions =
692 std::make_unique<Propagator<IntegrationStep::VelocityVerletPositionsAndVelocities>>(
693 inputrec->delta_t, statePropagatorDataPtr, mdAtoms, wcycle);
695 addToCallListAndMove(std::move(forceElement), elementCallList, elementsOwnershipList);
697 std::unique_ptr<ParrinelloRahmanBarostat> prBarostat = nullptr;
698 if (inputrec->epc == epcPARRINELLORAHMAN)
700 // Building the PR barostat here since it needs access to the propagator
701 // and we want to be able to move the propagator object
702 prBarostat = std::make_unique<ParrinelloRahmanBarostat>(
703 inputrec->nstpcouple, -1, inputrec->delta_t * inputrec->nstpcouple,
704 inputrec->init_step, propagatorVelocities->viewOnPRScalingMatrix(),
705 propagatorVelocities->prScalingCallback(), statePropagatorDataPtr, energyElementPtr,
706 fplog, inputrec, mdAtoms, state_global, cr, inputrec->bContinuation);
707 energyElementPtr->setParrinelloRahamnBarostat(prBarostat.get());
708 checkpointClients->emplace_back(prBarostat.get());
710 addToCallListAndMove(std::move(propagatorVelocities), elementCallList, elementsOwnershipList);
713 auto constraintElement = std::make_unique<ConstraintsElement<ConstraintVariable::Velocities>>(
714 constr, statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr,
715 MASTER(cr), fplog, inputrec, mdAtoms->mdatoms());
716 energySignallerBuilder->registerSignallerClient(compat::make_not_null(constraintElement.get()));
717 trajectoryElementBuilder->registerSignallerClient(
718 compat::make_not_null(constraintElement.get()));
719 loggingSignallerBuilder->registerSignallerClient(
720 compat::make_not_null(constraintElement.get()));
722 addToCallListAndMove(std::move(constraintElement), elementCallList, elementsOwnershipList);
724 addToCallListAndMove(std::move(computeGlobalsElementAtFullTimeStep), elementCallList,
725 elementsOwnershipList);
726 addToCallList(statePropagatorDataPtr, elementCallList); // we have a full microstate at time t here!
727 if (inputrec->etc == etcVRESCALE)
729 // TODO: With increased complexity of the propagator, this will need further development,
730 // e.g. using propagators templated for velocity propagation policies and a builder
731 propagatorVelocitiesAndPositions->setNumVelocityScalingVariables(inputrec->opts.ngtc);
732 auto thermostat = std::make_unique<VRescaleThermostat>(
733 inputrec->nsttcouple, 0, true, inputrec->ld_seed, inputrec->opts.ngtc,
734 inputrec->delta_t * inputrec->nsttcouple, inputrec->opts.ref_t,
735 inputrec->opts.tau_t, inputrec->opts.nrdf, energyElementPtr,
736 propagatorVelocitiesAndPositions->viewOnVelocityScaling(),
737 propagatorVelocitiesAndPositions->velocityScalingCallback(), state_global, cr,
738 inputrec->bContinuation);
739 checkpointClients->emplace_back(thermostat.get());
740 energyElementPtr->setVRescaleThermostat(thermostat.get());
741 addToCallListAndMove(std::move(thermostat), elementCallList, elementsOwnershipList);
743 addToCallListAndMove(std::move(propagatorVelocitiesAndPositions), elementCallList,
744 elementsOwnershipList);
747 auto constraintElement = std::make_unique<ConstraintsElement<ConstraintVariable::Positions>>(
748 constr, statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr,
749 MASTER(cr), fplog, inputrec, mdAtoms->mdatoms());
750 energySignallerBuilder->registerSignallerClient(compat::make_not_null(constraintElement.get()));
751 trajectoryElementBuilder->registerSignallerClient(
752 compat::make_not_null(constraintElement.get()));
753 loggingSignallerBuilder->registerSignallerClient(
754 compat::make_not_null(constraintElement.get()));
756 addToCallListAndMove(std::move(constraintElement), elementCallList, elementsOwnershipList);
758 addToCallListAndMove(std::move(computeGlobalsElementAfterCoordinateUpdate), elementCallList,
759 elementsOwnershipList);
760 addToCallList(energyElementPtr, elementCallList); // we have the energies at time t here!
763 addToCallListAndMove(std::move(prBarostat), elementCallList, elementsOwnershipList);
768 gmx_fatal(FARGS, "Integrator not implemented for the modular simulator.");
771 auto integrator = std::make_unique<CompositeSimulatorElement>(std::move(elementCallList),
772 std::move(elementsOwnershipList));
773 // std::move *should* not be needed with c++-14, but clang-3.6 still requires it
774 return std::move(integrator);
777 bool ModularSimulator::isInputCompatible(bool exitOnFailure,
778 const t_inputrec* inputrec,
780 const gmx_vsite_t* vsite,
781 const gmx_multisim_t* ms,
782 const ReplicaExchangeParameters& replExParams,
786 ObservablesHistory* observablesHistory,
787 const gmx_membed_t* membed)
789 auto conditionalAssert = [exitOnFailure](bool condition, const char* message) {
792 GMX_RELEASE_ASSERT(condition, message);
797 bool isInputCompatible = true;
799 // GMX_USE_MODULAR_SIMULATOR allows to use modular simulator also for non-standard uses,
800 // such as the leap-frog integrator
801 const auto modularSimulatorExplicitlyTurnedOn = (getenv("GMX_USE_MODULAR_SIMULATOR") != nullptr);
802 // GMX_USE_MODULAR_SIMULATOR allows to use disable modular simulator for all uses,
803 // including the velocity-verlet integrator used by default
804 const auto modularSimulatorExplicitlyTurnedOff = (getenv("GMX_DISABLE_MODULAR_SIMULATOR") != nullptr);
807 !(modularSimulatorExplicitlyTurnedOn && modularSimulatorExplicitlyTurnedOff),
808 "Cannot have both GMX_USE_MODULAR_SIMULATOR=ON and GMX_DISABLE_MODULAR_SIMULATOR=ON. "
809 "Unset one of the two environment variables to explicitly chose which simulator to "
811 "or unset both to recover default behavior.");
814 !(modularSimulatorExplicitlyTurnedOff && inputrec->eI == eiVV
815 && inputrec->epc == epcPARRINELLORAHMAN),
816 "Cannot use a Parrinello-Rahman barostat with md-vv and "
817 "GMX_DISABLE_MODULAR_SIMULATOR=ON, "
818 "as the Parrinello-Rahman barostat is not implemented in the legacy simulator. Unset "
819 "GMX_DISABLE_MODULAR_SIMULATOR or use a different pressure control algorithm.");
823 && conditionalAssert(
824 inputrec->eI == eiMD || inputrec->eI == eiVV,
825 "Only integrators md and md-vv are supported by the modular simulator.");
826 isInputCompatible = isInputCompatible
827 && conditionalAssert(inputrec->eI != eiMD || modularSimulatorExplicitlyTurnedOn,
828 "Set GMX_USE_MODULAR_SIMULATOR=ON to use the modular "
829 "simulator with integrator md.");
832 && conditionalAssert(!doRerun, "Rerun is not supported by the modular simulator.");
835 && conditionalAssert(
836 inputrec->etc == etcNO || inputrec->etc == etcVRESCALE,
837 "Only v-rescale thermostat is supported by the modular simulator.");
840 && conditionalAssert(
841 inputrec->epc == epcNO || inputrec->epc == epcPARRINELLORAHMAN,
842 "Only Parrinello-Rahman barostat is supported by the modular simulator.");
845 && conditionalAssert(
846 !(inputrecNptTrotter(inputrec) || inputrecNphTrotter(inputrec)
847 || inputrecNvtTrotter(inputrec)),
848 "Legacy Trotter decomposition is not supported by the modular simulator.");
849 isInputCompatible = isInputCompatible
850 && conditionalAssert(inputrec->efep == efepNO || inputrec->efep == efepYES
851 || inputrec->efep == efepSLOWGROWTH,
852 "Expanded ensemble free energy calculation is not "
853 "supported by the modular simulator.");
854 isInputCompatible = isInputCompatible
855 && conditionalAssert(!inputrec->bPull,
856 "Pulling is not supported by the modular simulator.");
859 && conditionalAssert(inputrec->opts.ngacc == 1 && inputrec->opts.acc[0][XX] == 0.0
860 && inputrec->opts.acc[0][YY] == 0.0
861 && inputrec->opts.acc[0][ZZ] == 0.0 && inputrec->cos_accel == 0.0,
862 "Acceleration is not supported by the modular simulator.");
865 && conditionalAssert(inputrec->opts.ngfrz == 1 && inputrec->opts.nFreeze[0][XX] == 0
866 && inputrec->opts.nFreeze[0][YY] == 0
867 && inputrec->opts.nFreeze[0][ZZ] == 0,
868 "Freeze groups are not supported by the modular simulator.");
871 && conditionalAssert(
872 inputrec->deform[XX][XX] == 0.0 && inputrec->deform[XX][YY] == 0.0
873 && inputrec->deform[XX][ZZ] == 0.0 && inputrec->deform[YY][XX] == 0.0
874 && inputrec->deform[YY][YY] == 0.0 && inputrec->deform[YY][ZZ] == 0.0
875 && inputrec->deform[ZZ][XX] == 0.0 && inputrec->deform[ZZ][YY] == 0.0
876 && inputrec->deform[ZZ][ZZ] == 0.0,
877 "Deformation is not supported by the modular simulator.");
880 && conditionalAssert(vsite == nullptr,
881 "Virtual sites are not supported by the modular simulator.");
882 isInputCompatible = isInputCompatible
883 && conditionalAssert(!inputrec->bDoAwh,
884 "AWH is not supported by the modular simulator.");
887 && conditionalAssert(ms == nullptr,
888 "Multi-sim are not supported by the modular simulator.");
891 && conditionalAssert(replExParams.exchangeInterval == 0,
892 "Replica exchange is not supported by the modular simulator.");
895 && conditionalAssert(fcd->disres.nsystems <= 1,
896 "Ensemble restraints are not supported by the modular simulator.");
899 && conditionalAssert(!doSimulatedAnnealing(inputrec),
900 "Simulated annealing is not supported by the modular simulator.");
903 && conditionalAssert(!inputrec->bSimTemp,
904 "Simulated tempering is not supported by the modular simulator.");
905 isInputCompatible = isInputCompatible
906 && conditionalAssert(!inputrec->bExpanded,
907 "Expanded ensemble simulations are not supported by "
908 "the modular simulator.");
911 && conditionalAssert(
912 !(opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr),
913 "Essential dynamics is not supported by the modular simulator.");
914 isInputCompatible = isInputCompatible
915 && conditionalAssert(inputrec->eSwapCoords == eswapNO,
916 "Ion / water position swapping is not supported by "
917 "the modular simulator.");
920 && conditionalAssert(!inputrec->bIMD,
921 "Interactive MD is not supported by the modular simulator.");
924 && conditionalAssert(membed == nullptr,
925 "Membrane embedding is not supported by the modular simulator.");
926 // TODO: Change this to the boolean passed when we merge the user interface change for the GPU update.
929 && conditionalAssert(
930 getenv("GMX_FORCE_UPDATE_DEFAULT_GPU") == nullptr,
931 "Integration on the GPU is not supported by the modular simulator.");
932 // Modular simulator is centered around NS updates
933 // TODO: think how to handle nstlist == 0
934 isInputCompatible = isInputCompatible
935 && conditionalAssert(inputrec->nstlist != 0,
936 "Simulations without neighbor list update are not "
937 "supported by the modular simulator.");
938 isInputCompatible = isInputCompatible
939 && conditionalAssert(!GMX_FAHCORE,
940 "GMX_FAHCORE not supported by the modular simulator.");
942 return isInputCompatible;
945 void ModularSimulator::checkInputForDisabledFunctionality()
947 isInputCompatible(true, inputrec, doRerun, vsite, ms, replExParams, fcd, nfile, fnm,
948 observablesHistory, membed);
951 SignallerCallbackPtr ModularSimulator::SignalHelper::registerLastStepCallback()
953 return std::make_unique<SignallerCallback>(
954 [this](Step step, Time gmx_unused time) { this->lastStep_ = step; });
957 SignallerCallbackPtr ModularSimulator::SignalHelper::registerNSCallback()
959 return std::make_unique<SignallerCallback>(
960 [this](Step step, Time gmx_unused time) { this->nextNSStep_ = step; });