b116f29b2cfc8029a035dd396ea493017ec4fa03
[alexxy/gromacs.git] / src / gromacs / modularsimulator / modularsimulator.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
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.
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 /*! \internal \file
36  * \brief Defines the modular simulator
37  *
38  * \author Pascal Merz <pascal.merz@me.com>
39  * \ingroup module_modularsimulator
40  */
41
42 #include "gmxpre.h"
43
44 #include "modularsimulator.h"
45
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"
75
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"
89
90 namespace gmx
91 {
92 void ModularSimulator::run()
93 {
94     GMX_LOG(mdlog.info).asParagraph().appendText("Using the modular simulator.");
95     constructElementsAndSignallers();
96     simulatorSetup();
97     for (auto& signaller : signallerCallList_)
98     {
99         signaller->signallerSetup();
100     }
101     if (domDecHelper_)
102     {
103         domDecHelper_->setup();
104     }
105
106     for (auto& element : elementsOwnershipList_)
107     {
108         element->elementSetup();
109     }
110     if (pmeLoadBalanceHelper_)
111     {
112         // State must have been initialized so pmeLoadBalanceHelper_ gets a valid box
113         pmeLoadBalanceHelper_->setup();
114     }
115
116     while (step_ <= signalHelper_->lastStep_)
117     {
118         populateTaskQueue();
119
120         while (!taskQueue_.empty())
121         {
122             auto task = std::move(taskQueue_.front());
123             taskQueue_.pop();
124             // run function
125             (*task)();
126         }
127     }
128
129     for (auto& element : elementsOwnershipList_)
130     {
131         element->elementTeardown();
132     }
133     if (pmeLoadBalanceHelper_)
134     {
135         pmeLoadBalanceHelper_->teardown();
136     }
137     simulatorTeardown();
138 }
139
140 void ModularSimulator::simulatorSetup()
141 {
142     if (!mdrunOptions.writeConfout)
143     {
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
147         // interface.
148         GMX_LOG(mdlog.info)
149                 .asParagraph()
150                 .appendText(
151                         "The -noconfout functionality is deprecated, and "
152                         "may be removed in a future version.");
153     }
154
155     if (MASTER(cr))
156     {
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)
161         {
162             timeString = formatString("%8.1f", static_cast<double>(inputrec->init_step + inputrec->nsteps)
163                                                        * inputrec->delta_t);
164         }
165         else
166         {
167             timeString = "infinite";
168         }
169         if (inputrec->init_step > 0)
170         {
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);
174         }
175         else
176         {
177             fprintf(stderr, "%s steps, %s ps.\n", gmx_step_str(inputrec->nsteps, sbuf),
178                     timeString.c_str());
179         }
180         fprintf(fplog, "\n");
181     }
182
183     walltime_accounting_start_time(walltime_accounting);
184     wallcycle_start(wcycle, ewcRUN);
185     print_start(fplog, cr, walltime_accounting, "mdrun");
186
187     step_ = inputrec->init_step;
188 }
189
190 void ModularSimulator::preStep(Step step, Time gmx_unused time, bool isNeighborSearchingStep)
191 {
192     if (stopHandler_->stoppingAfterCurrentStep(isNeighborSearchingStep) && step != signalHelper_->lastStep_)
193     {
194         /*
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.
199          */
200         // clear task queue
201         std::queue<SimulatorRunFunctionPtr>().swap(taskQueue_);
202         // rewind step
203         step_ = step;
204         return;
205     }
206
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
211     // duplication.
212     stophandlerIsNSStep_    = isNeighborSearchingStep;
213     stophandlerCurrentStep_ = step;
214     stopHandler_->setSignal();
215
216     wallcycle_start(wcycle, ewcSTEP);
217 }
218
219 void ModularSimulator::postStep(Step step, Time gmx_unused time)
220 {
221     // Output stuff
222     if (MASTER(cr))
223     {
224         if (do_per_step(step, inputrec->nstlog))
225         {
226             if (fflush(fplog) != 0)
227             {
228                 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
229             }
230         }
231     }
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()))
238     {
239         print_time(stderr, walltime_accounting, step, inputrec, cr);
240     }
241
242     double cycles = wallcycle_stop(wcycle, ewcSTEP);
243     if (DOMAINDECOMP(cr) && wcycle)
244     {
245         dd_cycles_add(cr->dd, static_cast<float>(cycles), ddCyclStep);
246     }
247
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);
252 }
253
254 void ModularSimulator::simulatorTeardown()
255 {
256
257     // Stop measuring walltime
258     walltime_accounting_end_time(walltime_accounting);
259
260     if (!thisRankHasDuty(cr, DUTY_PME))
261     {
262         /* Tell the PME only node to finish */
263         gmx_pme_send_finish(cr);
264     }
265
266     walltime_accounting_set_nsteps_done(walltime_accounting, step_ - inputrec->init_step);
267 }
268
269 void ModularSimulator::populateTaskQueue()
270 {
271     auto registerRunFunction = std::make_unique<RegisterRunFunction>(
272             [this](SimulatorRunFunctionPtr ptr) { taskQueue_.push(std::move(ptr)); });
273
274     Time startTime = inputrec->init_t;
275     Time timeStep  = inputrec->delta_t;
276     Time time      = startTime + step_ * timeStep;
277
278     // Run an initial call to the signallers
279     for (auto& signaller : signallerCallList_)
280     {
281         signaller->signal(step_, time);
282     }
283
284     if (checkpointHelper_)
285     {
286         checkpointHelper_->run(step_, time);
287     }
288
289     if (pmeLoadBalanceHelper_)
290     {
291         pmeLoadBalanceHelper_->run(step_, time);
292     }
293     if (domDecHelper_)
294     {
295         domDecHelper_->run(step_, time);
296     }
297
298     do
299     {
300         // local variables for lambda capturing
301         const int  step     = step_;
302         const bool isNSStep = step == signalHelper_->nextNSStep_;
303
304         // register pre-step
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_)
309         {
310             element->scheduleTask(step_, time, registerRunFunction);
311         }
312         // register post-step
313         (*registerRunFunction)(
314                 std::make_unique<SimulatorRunFunction>([this, step, time]() { postStep(step, time); }));
315
316         // prepare next step
317         step_++;
318         time = startTime + step_ * timeStep;
319         for (auto& signaller : signallerCallList_)
320         {
321             signaller->signal(step_, time);
322         }
323     } while (step_ != signalHelper_->nextNSStep_ && step_ <= signalHelper_->lastStep_);
324 }
325
326 void ModularSimulator::constructElementsAndSignallers()
327 {
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.
334      *
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
339      *      reduced.
340      *
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.
344      */
345     bool hasReadEkinState = MASTER(cr) ? state_global->ekinstate.hasReadEkinState : false;
346     if (PAR(cr))
347     {
348         gmx_bcast(sizeof(hasReadEkinState), &hasReadEkinState, cr);
349     }
350     if (hasReadEkinState)
351     {
352         restore_ekinstate_from_state(cr, ekind, &state_global->ekinstate);
353     }
354
355     /*
356      * Build data structures
357      */
358     topologyHolder_ =
359             std::make_unique<TopologyHolder>(*top_global, cr, inputrec, fr, mdAtoms, constr, vsite);
360
361     std::unique_ptr<FreeEnergyPerturbationElement> freeEnergyPerturbationElement    = nullptr;
362     FreeEnergyPerturbationElement*                 freeEnergyPerturbationElementPtr = nullptr;
363     if (inputrec->efep != efepNO)
364     {
365         freeEnergyPerturbationElement =
366                 std::make_unique<FreeEnergyPerturbationElement>(fplog, inputrec, mdAtoms);
367         freeEnergyPerturbationElementPtr = freeEnergyPerturbationElement.get();
368     }
369
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());
376
377     auto energyElement = std::make_unique<EnergyElement>(
378             statePropagatorDataPtr, freeEnergyPerturbationElementPtr, top_global, inputrec, mdAtoms,
379             enerd, ekind, constr, fplog, fcd, mdModulesNotifier, MASTER(cr), observablesHistory,
380             startingBehavior);
381     auto energyElementPtr = compat::make_not_null(energyElement.get());
382
383     /*
384      * Build stop handler
385      */
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);
392
393     /*
394      * Create simulator builders
395      */
396     SignallerBuilder<NeighborSearchSignaller> neighborSearchSignallerBuilder;
397     SignallerBuilder<LastStepSignaller>       lastStepSignallerBuilder;
398     SignallerBuilder<LoggingSignaller>        loggingSignallerBuilder;
399     SignallerBuilder<EnergySignaller>         energySignallerBuilder;
400     TrajectoryElementBuilder                  trajectoryElementBuilder;
401
402     /*
403      * Register data structures to signallers
404      */
405     trajectoryElementBuilder.registerWriterClient(statePropagatorDataPtr);
406     trajectoryElementBuilder.registerSignallerClient(statePropagatorDataPtr);
407     lastStepSignallerBuilder.registerSignallerClient(statePropagatorDataPtr);
408
409     trajectoryElementBuilder.registerWriterClient(energyElementPtr);
410     trajectoryElementBuilder.registerSignallerClient(energyElementPtr);
411     energySignallerBuilder.registerSignallerClient(energyElementPtr);
412
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()));
416
417     /*
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.
421      */
422     // TODO: Make a CheckpointHelperBuilder
423     std::vector<ICheckpointHelperClient*> checkpointClients = { statePropagatorDataPtr, energyElementPtr,
424                                                                 freeEnergyPerturbationElementPtr };
425     CheckBondedInteractionsCallbackPtr checkBondedInteractionsCallback = nullptr;
426     auto                               integrator =
427             buildIntegrator(&neighborSearchSignallerBuilder, &energySignallerBuilder,
428                             &loggingSignallerBuilder, &trajectoryElementBuilder, &checkpointClients,
429                             &checkBondedInteractionsCallback, statePropagatorDataPtr,
430                             energyElementPtr, freeEnergyPerturbationElementPtr, hasReadEkinState);
431
432     /*
433      * Build infrastructure elements
434      */
435
436     if (PmeLoadBalanceHelper::doPmeLoadBalancing(mdrunOptions, inputrec, fr))
437     {
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()));
442     }
443
444     if (DOMAINDECOMP(cr))
445     {
446         GMX_ASSERT(checkBondedInteractionsCallback,
447                    "Domain decomposition needs a callback for check the number of bonded "
448                    "interactions.");
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()));
454     }
455
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);
462
463     /*
464      * Build signaller list
465      *
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
468      * maintained.
469      */
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()));
478
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()));
490
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);
500
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_);
506
507     /*
508      * Build the element list
509      *
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.
515      */
516     addToCallList(checkpointHelper_, elementCallList_);
517     if (freeEnergyPerturbationElement)
518     {
519         addToCallListAndMove(std::move(freeEnergyPerturbationElement), elementCallList_,
520                              elementsOwnershipList_);
521     }
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));
529 }
530
531 std::unique_ptr<ISimulatorElement>
532 ModularSimulator::buildForces(SignallerBuilder<NeighborSearchSignaller>* neighborSearchSignallerBuilder,
533                               SignallerBuilder<EnergySignaller>*         energySignallerBuilder,
534                               StatePropagatorData*                       statePropagatorDataPtr,
535                               EnergyElement*                             energyElementPtr,
536                               FreeEnergyPerturbationElement* freeEnergyPerturbationElement)
537 {
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))
543     {
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()));
552
553         // std::move *should* not be needed with c++-14, but clang-3.6 still requires it
554         return std::move(shellFCElement);
555     }
556     else
557     {
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()));
565
566         // std::move *should* not be needed with c++-14, but clang-3.6 still requires it
567         return std::move(forceElement);
568     }
569 }
570
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)
582 {
583     auto forceElement =
584             buildForces(neighborSearchSignallerBuilder, energySignallerBuilder,
585                         statePropagatorDataPtr, energyElementPtr, freeEnergyPerturbationElementPtr);
586
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;
591
592     std::function<void()> needToCheckNumberOfBondedInteractions;
593     if (inputrec->eI == eiMD)
594     {
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()));
604
605         *checkBondedInteractionsCallback =
606                 computeGlobalsElement->getCheckNumberOfBondedInteractionsCallback();
607
608         auto propagator = std::make_unique<Propagator<IntegrationStep::LeapFrog>>(
609                 inputrec->delta_t, statePropagatorDataPtr, mdAtoms, wcycle);
610
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)
614         {
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);
626         }
627
628         std::unique_ptr<ParrinelloRahmanBarostat> prBarostat = nullptr;
629         if (inputrec->epc == epcPARRINELLORAHMAN)
630         {
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());
640         }
641         addToCallListAndMove(std::move(propagator), elementCallList, elementsOwnershipList);
642         if (constr)
643         {
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);
651
652             addToCallListAndMove(std::move(constraintElement), elementCallList, elementsOwnershipList);
653         }
654
655         addToCallListAndMove(std::move(computeGlobalsElement), elementCallList, elementsOwnershipList);
656         addToCallList(energyElementPtr, elementCallList); // we have the energies at time t here!
657         if (prBarostat)
658         {
659             addToCallListAndMove(std::move(prBarostat), elementCallList, elementsOwnershipList);
660         }
661     }
662     else if (inputrec->eI == eiVV)
663     {
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()));
674
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()));
685
686         *checkBondedInteractionsCallback =
687                 computeGlobalsElementAfterCoordinateUpdate->getCheckNumberOfBondedInteractionsCallback();
688
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);
694
695         addToCallListAndMove(std::move(forceElement), elementCallList, elementsOwnershipList);
696
697         std::unique_ptr<ParrinelloRahmanBarostat> prBarostat = nullptr;
698         if (inputrec->epc == epcPARRINELLORAHMAN)
699         {
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());
709         }
710         addToCallListAndMove(std::move(propagatorVelocities), elementCallList, elementsOwnershipList);
711         if (constr)
712         {
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()));
721
722             addToCallListAndMove(std::move(constraintElement), elementCallList, elementsOwnershipList);
723         }
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)
728         {
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);
742         }
743         addToCallListAndMove(std::move(propagatorVelocitiesAndPositions), elementCallList,
744                              elementsOwnershipList);
745         if (constr)
746         {
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()));
755
756             addToCallListAndMove(std::move(constraintElement), elementCallList, elementsOwnershipList);
757         }
758         addToCallListAndMove(std::move(computeGlobalsElementAfterCoordinateUpdate), elementCallList,
759                              elementsOwnershipList);
760         addToCallList(energyElementPtr, elementCallList); // we have the energies at time t here!
761         if (prBarostat)
762         {
763             addToCallListAndMove(std::move(prBarostat), elementCallList, elementsOwnershipList);
764         }
765     }
766     else
767     {
768         gmx_fatal(FARGS, "Integrator not implemented for the modular simulator.");
769     }
770
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);
775 }
776
777 bool ModularSimulator::isInputCompatible(bool                             exitOnFailure,
778                                          const t_inputrec*                inputrec,
779                                          bool                             doRerun,
780                                          const gmx_vsite_t*               vsite,
781                                          const gmx_multisim_t*            ms,
782                                          const ReplicaExchangeParameters& replExParams,
783                                          const t_fcdata*                  fcd,
784                                          int                              nfile,
785                                          const t_filenm*                  fnm,
786                                          ObservablesHistory*              observablesHistory,
787                                          const gmx_membed_t*              membed)
788 {
789     auto conditionalAssert = [exitOnFailure](bool condition, const char* message) {
790         if (exitOnFailure)
791         {
792             GMX_RELEASE_ASSERT(condition, message);
793         }
794         return condition;
795     };
796
797     bool isInputCompatible = true;
798
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);
805
806     GMX_RELEASE_ASSERT(
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 "
810             "use, "
811             "or unset both to recover default behavior.");
812
813     GMX_RELEASE_ASSERT(
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.");
820
821     isInputCompatible =
822             isInputCompatible
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.");
830     isInputCompatible =
831             isInputCompatible
832             && conditionalAssert(!doRerun, "Rerun is not supported by the modular simulator.");
833     isInputCompatible =
834             isInputCompatible
835             && conditionalAssert(
836                        inputrec->etc == etcNO || inputrec->etc == etcVRESCALE,
837                        "Only v-rescale thermostat is supported by the modular simulator.");
838     isInputCompatible =
839             isInputCompatible
840             && conditionalAssert(
841                        inputrec->epc == epcNO || inputrec->epc == epcPARRINELLORAHMAN,
842                        "Only Parrinello-Rahman barostat is supported by the modular simulator.");
843     isInputCompatible =
844             isInputCompatible
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.");
857     isInputCompatible =
858             isInputCompatible
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.");
863     isInputCompatible =
864             isInputCompatible
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.");
869     isInputCompatible =
870             isInputCompatible
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.");
878     isInputCompatible =
879             isInputCompatible
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.");
885     isInputCompatible =
886             isInputCompatible
887             && conditionalAssert(ms == nullptr,
888                                  "Multi-sim are not supported by the modular simulator.");
889     isInputCompatible =
890             isInputCompatible
891             && conditionalAssert(replExParams.exchangeInterval == 0,
892                                  "Replica exchange is not supported by the modular simulator.");
893     isInputCompatible =
894             isInputCompatible
895             && conditionalAssert(fcd->disres.nsystems <= 1,
896                                  "Ensemble restraints are not supported by the modular simulator.");
897     isInputCompatible =
898             isInputCompatible
899             && conditionalAssert(!doSimulatedAnnealing(inputrec),
900                                  "Simulated annealing is not supported by the modular simulator.");
901     isInputCompatible =
902             isInputCompatible
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.");
909     isInputCompatible =
910             isInputCompatible
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.");
918     isInputCompatible =
919             isInputCompatible
920             && conditionalAssert(!inputrec->bIMD,
921                                  "Interactive MD is not supported by the modular simulator.");
922     isInputCompatible =
923             isInputCompatible
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.
927     isInputCompatible =
928             isInputCompatible
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.");
941
942     return isInputCompatible;
943 }
944
945 void ModularSimulator::checkInputForDisabledFunctionality()
946 {
947     isInputCompatible(true, inputrec, doRerun, vsite, ms, replExParams, fcd, nfile, fnm,
948                       observablesHistory, membed);
949 }
950
951 SignallerCallbackPtr ModularSimulator::SignalHelper::registerLastStepCallback()
952 {
953     return std::make_unique<SignallerCallback>(
954             [this](Step step, Time gmx_unused time) { this->lastStep_ = step; });
955 }
956
957 SignallerCallbackPtr ModularSimulator::SignalHelper::registerNSCallback()
958 {
959     return std::make_unique<SignallerCallback>(
960             [this](Step step, Time gmx_unused time) { this->nextNSStep_ = step; });
961 }
962 } // namespace gmx