2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2020,2021, 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 algorithm
38 * \author Pascal Merz <pascal.merz@me.com>
39 * \ingroup module_modularsimulator
44 #include "simulatoralgorithm.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/ewald/pme_pp.h"
51 #include "gromacs/gmxlib/nrnb.h"
52 #include "gromacs/listed_forces/listed_forces.h"
53 #include "gromacs/mdlib/checkpointhandler.h"
54 #include "gromacs/mdlib/constr.h"
55 #include "gromacs/mdlib/energyoutput.h"
56 #include "gromacs/mdlib/md_support.h"
57 #include "gromacs/mdlib/mdatoms.h"
58 #include "gromacs/mdlib/resethandler.h"
59 #include "gromacs/mdlib/stat.h"
60 #include "gromacs/mdrun/replicaexchange.h"
61 #include "gromacs/mdrun/shellfc.h"
62 #include "gromacs/mdrunutility/freeenergy.h"
63 #include "gromacs/mdrunutility/handlerestart.h"
64 #include "gromacs/mdrunutility/printtime.h"
65 #include "gromacs/mdtypes/commrec.h"
66 #include "gromacs/mdtypes/fcdata.h"
67 #include "gromacs/mdtypes/forcerec.h"
68 #include "gromacs/mdtypes/inputrec.h"
69 #include "gromacs/mdtypes/mdatom.h"
70 #include "gromacs/mdtypes/mdrunoptions.h"
71 #include "gromacs/mdtypes/observableshistory.h"
72 #include "gromacs/nbnxm/nbnxm.h"
73 #include "gromacs/timing/walltime_accounting.h"
74 #include "gromacs/topology/topology.h"
75 #include "gromacs/utility/cstringutil.h"
76 #include "gromacs/utility/fatalerror.h"
78 #include "checkpointhelper.h"
79 #include "domdechelper.h"
80 #include "energydata.h"
81 #include "firstorderpressurecoupling.h"
82 #include "freeenergyperturbationdata.h"
83 #include "modularsimulator.h"
84 #include "pmeloadbalancehelper.h"
85 #include "propagator.h"
86 #include "referencetemperaturemanager.h"
87 #include "statepropagatordata.h"
91 ModularSimulatorAlgorithm::ModularSimulatorAlgorithm(std::string topologyName,
94 const MDLogger& mdlog,
95 const MdrunOptions& mdrunOptions,
96 const t_inputrec* inputrec,
98 gmx_wallcycle* wcycle,
100 gmx_walltime_accounting* walltime_accounting) :
101 taskIterator_(taskQueue_.end()),
102 statePropagatorData_(nullptr),
103 energyData_(nullptr),
104 freeEnergyPerturbationData_(nullptr),
107 topologyName_(std::move(topologyName)),
111 mdrunOptions(mdrunOptions),
116 walltime_accounting(walltime_accounting)
118 signalHelper_ = std::make_unique<SignalHelper>();
121 void ModularSimulatorAlgorithm::setup()
124 for (auto& signaller : signallerList_)
130 domDecHelper_->setup();
133 for (auto& element : elementSetupTeardownList_)
135 element->elementSetup();
137 statePropagatorData_->setup();
138 if (pmeLoadBalanceHelper_)
140 // State must have been initialized so pmeLoadBalanceHelper_ gets a valid box
141 pmeLoadBalanceHelper_->setup();
145 const SimulatorRunFunction* ModularSimulatorAlgorithm::getNextTask()
147 if (!taskQueue_.empty())
151 if (taskIterator_ == taskQueue_.end())
158 taskIterator_ = taskQueue_.begin();
160 return &*taskIterator_;
163 void ModularSimulatorAlgorithm::updateTaskQueue()
165 // For now, we'll just clean the task queue and then re-populate
166 // TODO: If tasks are periodic around updates of the task queue,
167 // we should reuse it instead
172 void ModularSimulatorAlgorithm::teardown()
174 for (auto& element : elementSetupTeardownList_)
176 element->elementTeardown();
178 energyData_->teardown();
179 if (pmeLoadBalanceHelper_)
181 pmeLoadBalanceHelper_->teardown();
186 void ModularSimulatorAlgorithm::simulatorSetup()
188 if (!mdrunOptions.writeConfout)
190 // This is on by default, and the main known use case for
191 // turning it off is for convenience in benchmarking, which is
192 // something that should not show up in the general user
197 "The -noconfout functionality is deprecated, and "
198 "may be removed in a future version.");
203 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
204 std::string timeString;
205 fprintf(stderr, "starting mdrun '%s'\n", topologyName_.c_str());
206 if (inputrec->nsteps >= 0)
208 timeString = formatString(
209 "%8.1f", static_cast<double>(inputrec->init_step + inputrec->nsteps) * inputrec->delta_t);
213 timeString = "infinite";
215 if (inputrec->init_step > 0)
218 "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
219 gmx_step_str(inputrec->init_step + inputrec->nsteps, sbuf),
221 gmx_step_str(inputrec->init_step, sbuf2),
222 inputrec->init_step * inputrec->delta_t);
226 fprintf(stderr, "%s steps, %s ps.\n", gmx_step_str(inputrec->nsteps, sbuf), timeString.c_str());
228 fprintf(fplog, "\n");
231 walltime_accounting_start_time(walltime_accounting);
232 wallcycle_start(wcycle, WallCycleCounter::Run);
233 print_start(fplog, cr, walltime_accounting, "mdrun");
235 step_ = inputrec->init_step;
238 void ModularSimulatorAlgorithm::simulatorTeardown()
241 // Stop measuring walltime
242 walltime_accounting_end_time(walltime_accounting);
244 if (!thisRankHasDuty(cr, DUTY_PME))
246 /* Tell the PME only node to finish */
247 gmx_pme_send_finish(cr);
250 walltime_accounting_set_nsteps_done(walltime_accounting, step_ - inputrec->init_step);
253 void ModularSimulatorAlgorithm::preStep(Step step, Time gmx_unused time, bool isNeighborSearchingStep)
255 if (stopHandler_->stoppingAfterCurrentStep(isNeighborSearchingStep) && step != signalHelper_->lastStep_)
258 * Stop handler wants to stop after the current step, which was
259 * not known when building the current task queue. This happens
260 * e.g. when a stop is signalled by OS. We therefore want to purge
261 * the task queue now, and re-schedule this step as last step.
270 resetHandler_->setSignal(walltime_accounting);
271 // This is a hack to avoid having to rewrite StopHandler to be a NeighborSearchSignaller
272 // and accept the step as input. Eventually, we want to do that, but currently this would
273 // require introducing NeighborSearchSignaller in the legacy do_md or a lot of code
275 stophandlerIsNSStep_ = isNeighborSearchingStep;
276 stophandlerCurrentStep_ = step;
277 stopHandler_->setSignal();
279 wallcycle_start(wcycle, WallCycleCounter::Step);
282 void ModularSimulatorAlgorithm::postStep(Step step, Time gmx_unused time)
287 if (do_per_step(step, inputrec->nstlog))
289 if (fflush(fplog) != 0)
291 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
295 const bool do_verbose = mdrunOptions.verbose
296 && (step % mdrunOptions.verboseStepPrintInterval == 0
297 || step == inputrec->init_step || step == signalHelper_->lastStep_);
298 // Print the remaining wall clock time for the run
299 if (MASTER(cr) && (do_verbose || gmx_got_usr_signal())
300 && !(pmeLoadBalanceHelper_ && pmeLoadBalanceHelper_->pmePrinting()))
302 print_time(stderr, walltime_accounting, step, inputrec, cr);
305 double cycles = wallcycle_stop(wcycle, WallCycleCounter::Step);
306 if (DOMAINDECOMP(cr) && wcycle)
308 dd_cycles_add(cr->dd, static_cast<float>(cycles), ddCyclStep);
311 resetHandler_->resetCounters(step,
312 step - inputrec->init_step,
319 pmeLoadBalanceHelper_ ? pmeLoadBalanceHelper_->loadBalancingObject() : nullptr,
321 walltime_accounting);
324 void ModularSimulatorAlgorithm::populateTaskQueue()
327 * The registerRunFunction emplaces functions to the task queue.
328 * All elements are owned by the ModularSimulatorAlgorithm, as is the task queue.
329 * Elements can hence register lambdas capturing their `this` pointers without expecting
330 * life time issues, as the task queue and the elements are in the same scope.
332 auto registerRunFunction = [this](SimulatorRunFunction function) {
333 taskQueue_.emplace_back(std::move(function));
336 Time startTime = inputrec->init_t;
337 Time timeStep = inputrec->delta_t;
338 Time time = startTime + step_ * timeStep;
340 // Run an initial call to the signallers
341 for (auto& signaller : signallerList_)
343 signaller->signal(step_, time);
346 if (checkpointHelper_)
348 checkpointHelper_->run(step_, time);
351 if (pmeLoadBalanceHelper_)
353 pmeLoadBalanceHelper_->run(step_, time);
357 domDecHelper_->run(step_, time);
362 // local variables for lambda capturing
363 const int step = step_;
364 const bool isNSStep = step == signalHelper_->nextNSStep_;
366 // register pre-step (task queue is local, so no problem with `this`)
367 registerRunFunction([this, step, time, isNSStep]() { preStep(step, time, isNSStep); });
368 // register pre step functions
369 for (const auto& schedulingFunction : preStepScheduling_)
371 schedulingFunction(step_, time, registerRunFunction);
373 // register elements for step
374 for (auto& element : elementCallList_)
376 element->scheduleTask(step_, time, registerRunFunction);
378 // register post step functions
379 for (const auto& schedulingFunction : postStepScheduling_)
381 schedulingFunction(step_, time, registerRunFunction);
383 // register post-step (task queue is local, so no problem with `this`)
384 registerRunFunction([this, step, time]() { postStep(step, time); });
388 time = startTime + step_ * timeStep;
389 for (auto& signaller : signallerList_)
391 signaller->signal(step_, time);
393 } while (step_ != signalHelper_->nextNSStep_ && step_ <= signalHelper_->lastStep_);
395 runFinished_ = (step_ > signalHelper_->lastStep_);
399 // task queue is local, so no problem with `this`
400 registerRunFunction([this]() { teardown(); });
404 ModularSimulatorAlgorithmBuilder::ModularSimulatorAlgorithmBuilder(
405 compat::not_null<LegacySimulatorData*> legacySimulatorData,
406 std::unique_ptr<ReadCheckpointDataHolder> checkpointDataHolder) :
407 legacySimulatorData_(legacySimulatorData),
408 signals_(std::make_unique<SimulationSignals>()),
409 elementAdditionHelper_(this),
410 globalCommunicationHelper_(computeGlobalCommunicationPeriod(legacySimulatorData->mdlog,
411 legacySimulatorData->inputrec,
412 legacySimulatorData->cr),
414 observablesReducer_(legacySimulatorData->observablesReducerBuilder->build()),
415 checkpointHelperBuilder_(std::move(checkpointDataHolder),
416 legacySimulatorData->startingBehavior,
417 legacySimulatorData->cr)
419 if (legacySimulatorData->inputrec->efep != FreeEnergyPerturbationType::No)
421 freeEnergyPerturbationData_ = std::make_unique<FreeEnergyPerturbationData>(
422 legacySimulatorData->fplog, *legacySimulatorData->inputrec, legacySimulatorData->mdAtoms);
423 registerExistingElement(freeEnergyPerturbationData_->element());
426 statePropagatorData_ = std::make_unique<StatePropagatorData>(
427 legacySimulatorData->top_global.natoms,
428 legacySimulatorData->fplog,
429 legacySimulatorData->cr,
430 legacySimulatorData->state_global,
431 legacySimulatorData->fr->nbv->useGpu(),
432 legacySimulatorData->fr->bMolPBC,
433 legacySimulatorData->mdrunOptions.writeConfout,
434 opt2fn("-c", legacySimulatorData->nfile, legacySimulatorData->fnm),
435 legacySimulatorData->inputrec,
436 legacySimulatorData->mdAtoms->mdatoms(),
437 legacySimulatorData->top_global);
438 registerExistingElement(statePropagatorData_->element());
440 // Multi sim is turned off
441 const bool simulationsShareState = false;
443 energyData_ = std::make_unique<EnergyData>(statePropagatorData_.get(),
444 freeEnergyPerturbationData_.get(),
445 legacySimulatorData->top_global,
446 legacySimulatorData->inputrec,
447 legacySimulatorData->mdAtoms,
448 legacySimulatorData->enerd,
449 legacySimulatorData->ekind,
450 legacySimulatorData->constr,
451 legacySimulatorData->fplog,
452 legacySimulatorData->fr->fcdata.get(),
453 legacySimulatorData->mdModulesNotifiers,
454 MASTER(legacySimulatorData->cr),
455 legacySimulatorData->observablesHistory,
456 legacySimulatorData->startingBehavior,
457 simulationsShareState);
458 registerExistingElement(energyData_->element());
460 // This is the only modular simulator object which changes the inputrec
461 // TODO: Avoid changing inputrec (#3854)
463 "ReferenceTemperatureManager",
464 ReferenceTemperatureManager(const_cast<t_inputrec*>(legacySimulatorData->inputrec)));
465 auto* referenceTemperatureManager =
466 simulationData<ReferenceTemperatureManager>("ReferenceTemperatureManager").value();
468 // State propagator data is scaling velocities if reference temperature is updated
469 auto* statePropagatorDataPtr = statePropagatorData_.get();
470 referenceTemperatureManager->registerUpdateCallback(
471 [statePropagatorDataPtr](ArrayRef<const real> temperatures,
472 ReferenceTemperatureChangeAlgorithm algorithm) {
473 statePropagatorDataPtr->updateReferenceTemperature(temperatures, algorithm);
477 ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build()
479 if (algorithmHasBeenBuilt_)
481 GMX_THROW(SimulationAlgorithmSetupError(
482 "Tried to build ModularSimulationAlgorithm more than once."));
484 algorithmHasBeenBuilt_ = true;
486 // Connect propagators with thermostat / barostat
487 for (const auto& registrationFunction : pressureTemperatureControlRegistrationFunctions_)
489 for (const auto& connection : propagatorConnections_)
491 registrationFunction(connection);
495 ModularSimulatorAlgorithm algorithm(*(legacySimulatorData_->top_global.name),
496 legacySimulatorData_->fplog,
497 legacySimulatorData_->cr,
498 legacySimulatorData_->mdlog,
499 legacySimulatorData_->mdrunOptions,
500 legacySimulatorData_->inputrec,
501 legacySimulatorData_->nrnb,
502 legacySimulatorData_->wcycle,
503 legacySimulatorData_->fr,
504 legacySimulatorData_->walltime_accounting);
505 registerWithInfrastructureAndSignallers(algorithm.signalHelper_.get());
506 algorithm.statePropagatorData_ = std::move(statePropagatorData_);
507 algorithm.energyData_ = std::move(energyData_);
508 algorithm.freeEnergyPerturbationData_ = std::move(freeEnergyPerturbationData_);
509 algorithm.signals_ = std::move(signals_);
510 algorithm.simulationData_ = std::move(simulationData_);
512 // Multi sim is turned off
513 const bool simulationsShareState = false;
515 // Build stop handler
516 algorithm.stopHandler_ = legacySimulatorData_->stopHandlerBuilder->getStopHandlerMD(
517 compat::not_null<SimulationSignal*>(
518 &(*globalCommunicationHelper_.simulationSignals())[eglsSTOPCOND]),
519 simulationsShareState,
520 MASTER(legacySimulatorData_->cr),
521 legacySimulatorData_->inputrec->nstlist,
522 legacySimulatorData_->mdrunOptions.reproducible,
523 globalCommunicationHelper_.nstglobalcomm(),
524 legacySimulatorData_->mdrunOptions.maximumHoursToRun,
525 legacySimulatorData_->inputrec->nstlist == 0,
526 legacySimulatorData_->fplog,
527 algorithm.stophandlerCurrentStep_,
528 algorithm.stophandlerIsNSStep_,
529 legacySimulatorData_->walltime_accounting);
531 // Build reset handler
532 const bool simulationsShareResetCounters = false;
533 algorithm.resetHandler_ = std::make_unique<ResetHandler>(
534 compat::make_not_null<SimulationSignal*>(
535 &(*globalCommunicationHelper_.simulationSignals())[eglsRESETCOUNTERS]),
536 simulationsShareResetCounters,
537 legacySimulatorData_->inputrec->nsteps,
538 MASTER(legacySimulatorData_->cr),
539 legacySimulatorData_->mdrunOptions.timingOptions.resetHalfway,
540 legacySimulatorData_->mdrunOptions.maximumHoursToRun,
541 legacySimulatorData_->mdlog,
542 legacySimulatorData_->wcycle,
543 legacySimulatorData_->walltime_accounting);
545 // Build topology holder
546 algorithm.topologyHolder_ = topologyHolderBuilder_.build(legacySimulatorData_->top_global,
547 legacySimulatorData_->cr,
548 legacySimulatorData_->inputrec,
549 legacySimulatorData_->fr,
550 legacySimulatorData_->mdAtoms,
551 legacySimulatorData_->constr,
552 legacySimulatorData_->vsite);
553 registerWithInfrastructureAndSignallers(algorithm.topologyHolder_.get());
555 // Build PME load balance helper
556 if (PmeLoadBalanceHelper::doPmeLoadBalancing(legacySimulatorData_->mdrunOptions,
557 legacySimulatorData_->inputrec,
558 legacySimulatorData_->fr))
560 algorithm.pmeLoadBalanceHelper_ =
561 std::make_unique<PmeLoadBalanceHelper>(legacySimulatorData_->mdrunOptions.verbose,
562 algorithm.statePropagatorData_.get(),
563 legacySimulatorData_->fplog,
564 legacySimulatorData_->cr,
565 legacySimulatorData_->mdlog,
566 legacySimulatorData_->inputrec,
567 legacySimulatorData_->wcycle,
568 legacySimulatorData_->fr);
569 registerWithInfrastructureAndSignallers(algorithm.pmeLoadBalanceHelper_.get());
572 // Build trajectory element
573 auto trajectoryElement = trajectoryElementBuilder_.build(legacySimulatorData_->fplog,
574 legacySimulatorData_->nfile,
575 legacySimulatorData_->fnm,
576 legacySimulatorData_->mdrunOptions,
577 legacySimulatorData_->cr,
578 legacySimulatorData_->outputProvider,
579 legacySimulatorData_->mdModulesNotifiers,
580 legacySimulatorData_->inputrec,
581 legacySimulatorData_->top_global,
582 legacySimulatorData_->oenv,
583 legacySimulatorData_->wcycle,
584 legacySimulatorData_->startingBehavior,
585 simulationsShareState);
586 registerWithInfrastructureAndSignallers(trajectoryElement.get());
588 // Build domdec helper (free energy element is a client, so keep this after it is built)
589 if (DOMAINDECOMP(legacySimulatorData_->cr))
591 algorithm.domDecHelper_ =
592 domDecHelperBuilder_.build(legacySimulatorData_->mdrunOptions.verbose,
593 legacySimulatorData_->mdrunOptions.verboseStepPrintInterval,
594 algorithm.statePropagatorData_.get(),
595 algorithm.topologyHolder_.get(),
596 globalCommunicationHelper_.nstglobalcomm(),
597 legacySimulatorData_->fplog,
598 legacySimulatorData_->cr,
599 legacySimulatorData_->mdlog,
600 legacySimulatorData_->constr,
601 legacySimulatorData_->inputrec,
602 legacySimulatorData_->mdAtoms,
603 legacySimulatorData_->nrnb,
604 legacySimulatorData_->wcycle,
605 legacySimulatorData_->fr,
606 legacySimulatorData_->vsite,
607 legacySimulatorData_->imdSession,
608 legacySimulatorData_->pull_work);
609 registerWithInfrastructureAndSignallers(algorithm.domDecHelper_.get());
611 // Build checkpoint helper (do this last so everyone else can be a checkpoint client!)
613 checkpointHelperBuilder_.setCheckpointHandler(std::make_unique<CheckpointHandler>(
614 compat::make_not_null<SimulationSignal*>(&(*algorithm.signals_)[eglsCHKPT]),
615 simulationsShareState,
616 legacySimulatorData_->inputrec->nstlist == 0,
617 MASTER(legacySimulatorData_->cr),
618 legacySimulatorData_->mdrunOptions.writeConfout,
619 legacySimulatorData_->mdrunOptions.checkpointOptions.period));
620 algorithm.checkpointHelper_ =
621 checkpointHelperBuilder_.build(legacySimulatorData_->inputrec->init_step,
622 trajectoryElement.get(),
623 legacySimulatorData_->fplog,
624 legacySimulatorData_->cr,
625 legacySimulatorData_->observablesHistory,
626 legacySimulatorData_->walltime_accounting,
627 legacySimulatorData_->state_global,
628 legacySimulatorData_->mdrunOptions.writeConfout);
629 registerWithInfrastructureAndSignallers(algorithm.checkpointHelper_.get());
634 /* Signallers need to be called in an exact order. Some signallers are clients
635 * of other signallers, which requires the clients signallers to be called
636 * _after_ any signaller they are registered to - otherwise, they couldn't
637 * adapt their behavior to the information they got signalled.
639 * Signallers being clients of other signallers require registration.
640 * That registration happens during construction, which in turn means that
641 * we want to construct the signallers in the reverse order of their later
644 * For the above reasons, the `addSignaller` lambda defined below emplaces
645 * added signallers at the beginning of the signaller list, which will yield
646 * a signaller list which is inverse to the build order (and hence equal to
647 * the intended call order).
649 auto addSignaller = [this, &algorithm](auto signaller) {
650 registerWithInfrastructureAndSignallers(signaller.get());
651 algorithm.signallerList_.emplace(algorithm.signallerList_.begin(), std::move(signaller));
653 const auto* inputrec = legacySimulatorData_->inputrec;
654 auto virialMode = EnergySignallerVirialMode::Off;
655 if (inputrec->epc != PressureCoupling::No)
657 if (EI_VV(inputrec->eI))
659 virialMode = EnergySignallerVirialMode::OnStepAndNext;
663 virialMode = EnergySignallerVirialMode::OnStep;
666 addSignaller(energySignallerBuilder_.build(
667 inputrec->nstcalcenergy,
668 computeFepPeriod(*inputrec, legacySimulatorData_->replExParams),
669 inputrec->nstpcouple,
671 addSignaller(trajectorySignallerBuilder_.build(inputrec->nstxout,
674 inputrec->nstxout_compressed,
675 trajectoryElement->tngBoxOut(),
676 trajectoryElement->tngLambdaOut(),
677 trajectoryElement->tngBoxOutCompressed(),
678 trajectoryElement->tngLambdaOutCompressed(),
679 inputrec->nstenergy));
680 addSignaller(loggingSignallerBuilder_.build(
681 inputrec->nstlog, inputrec->init_step, legacySimulatorData_->startingBehavior));
682 addSignaller(lastStepSignallerBuilder_.build(
683 inputrec->nsteps, inputrec->init_step, algorithm.stopHandler_.get()));
684 addSignaller(neighborSearchSignallerBuilder_.build(
685 inputrec->nstlist, inputrec->init_step, inputrec->init_t));
688 // Move setup / teardown list
689 algorithm.elementSetupTeardownList_ = std::move(setupAndTeardownList_);
690 // Move pre- / post-step scheduling lists
691 algorithm.preStepScheduling_ = std::move(preStepScheduling_);
692 algorithm.postStepScheduling_ = std::move(postStepScheduling_);
694 // Create element list
695 // Checkpoint helper needs to be in the call list (as first element!) to react to last step
696 algorithm.elementCallList_.emplace_back(algorithm.checkpointHelper_.get());
697 // Next, update the free energy lambda vector if needed
698 if (algorithm.freeEnergyPerturbationData_)
700 algorithm.elementCallList_.emplace_back(algorithm.freeEnergyPerturbationData_->element());
702 // Then, move the built algorithm
703 algorithm.elementsOwnershipList_.insert(algorithm.elementsOwnershipList_.end(),
704 std::make_move_iterator(elements_.begin()),
705 std::make_move_iterator(elements_.end()));
706 algorithm.elementCallList_.insert(algorithm.elementCallList_.end(),
707 std::make_move_iterator(callList_.begin()),
708 std::make_move_iterator(callList_.end()));
709 // Finally, all trajectory writing is happening after the step
710 // (relevant data was stored by elements through energy signaller)
711 algorithm.elementsOwnershipList_.emplace_back(std::move(trajectoryElement));
712 algorithm.elementCallList_.emplace_back(algorithm.elementsOwnershipList_.back().get());
713 algorithm.elementSetupTeardownList_.emplace_back(algorithm.elementsOwnershipList_.back().get());
719 bool ModularSimulatorAlgorithmBuilder::elementExists(const ISimulatorElement* element) const
721 // Check whether element exists in element list
722 if (std::any_of(elements_.begin(), elements_.end(), [element](auto& existingElement) {
723 return element == existingElement.get();
728 // Check whether element exists in other places controlled by *this
729 return ((statePropagatorData_ && statePropagatorData_->element() == element)
730 || (energyData_ && energyData_->element() == element)
731 || (freeEnergyPerturbationData_ && freeEnergyPerturbationData_->element() == element));
734 std::optional<SignallerCallback> ModularSimulatorAlgorithm::SignalHelper::registerLastStepCallback()
736 return [this](Step step, Time gmx_unused time) { this->lastStep_ = step; };
739 std::optional<SignallerCallback> ModularSimulatorAlgorithm::SignalHelper::registerNSCallback()
741 return [this](Step step, Time gmx_unused time) { this->nextNSStep_ = step; };
744 GlobalCommunicationHelper::GlobalCommunicationHelper(int nstglobalcomm, SimulationSignals* simulationSignals) :
745 nstglobalcomm_(nstglobalcomm), simulationSignals_(simulationSignals)
749 int GlobalCommunicationHelper::nstglobalcomm() const
751 return nstglobalcomm_;
754 SimulationSignals* GlobalCommunicationHelper::simulationSignals()
756 return simulationSignals_;
759 ModularSimulatorAlgorithmBuilderHelper::ModularSimulatorAlgorithmBuilderHelper(
760 ModularSimulatorAlgorithmBuilder* builder) :
765 bool ModularSimulatorAlgorithmBuilderHelper::elementIsStored(const ISimulatorElement* element) const
767 return builder_->elementExists(element);
770 [[maybe_unused]] void ModularSimulatorAlgorithmBuilderHelper::registerPreStepScheduling(SchedulingFunction schedulingFunction)
772 builder_->preStepScheduling_.emplace_back(std::move(schedulingFunction));
775 [[maybe_unused]] void ModularSimulatorAlgorithmBuilderHelper::registerPostStepScheduling(SchedulingFunction schedulingFunction)
777 builder_->postStepScheduling_.emplace_back(std::move(schedulingFunction));
780 std::optional<std::any> ModularSimulatorAlgorithmBuilderHelper::builderData(const std::string& key) const
782 const auto iter = builder_->builderData_.find(key);
783 if (iter == builder_->builderData_.end())
793 void ModularSimulatorAlgorithmBuilderHelper::registerTemperaturePressureControl(
794 std::function<void(const PropagatorConnection&)> registrationFunction)
796 builder_->pressureTemperatureControlRegistrationFunctions_.emplace_back(std::move(registrationFunction));
799 void ModularSimulatorAlgorithmBuilderHelper::registerPropagator(PropagatorConnection connectionData)
801 builder_->propagatorConnections_.emplace_back(std::move(connectionData));
804 void ModularSimulatorAlgorithmBuilderHelper::registerReferenceTemperatureUpdate(
805 ReferenceTemperatureCallback referenceTemperatureCallback)
807 auto* referenceTemperatureManager =
808 simulationData<ReferenceTemperatureManager>("ReferenceTemperatureManager").value();
809 referenceTemperatureManager->registerUpdateCallback(std::move(referenceTemperatureCallback));
812 ReferenceTemperatureCallback ModularSimulatorAlgorithmBuilderHelper::changeReferenceTemperatureCallback()
814 // Capture is safe because SimulatorAlgorithm will manage life time of both the
815 // recipient of the callback and the reference temperature manager
816 auto* referenceTemperatureManager =
817 simulationData<ReferenceTemperatureManager>("ReferenceTemperatureManager").value();
818 return [referenceTemperatureManager](ArrayRef<const real> temperatures,
819 ReferenceTemperatureChangeAlgorithm algorithm) {
820 referenceTemperatureManager->setReferenceTemperature(temperatures, algorithm);