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 (haveDDAtomOrdering(*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->state,
432 legacySimulatorData->fr->nbv->useGpu(),
433 legacySimulatorData->fr->bMolPBC,
434 legacySimulatorData->mdrunOptions.writeConfout,
435 opt2fn("-c", legacySimulatorData->nfile, legacySimulatorData->fnm),
436 legacySimulatorData->inputrec,
437 legacySimulatorData->mdAtoms->mdatoms(),
438 legacySimulatorData->top_global);
439 registerExistingElement(statePropagatorData_->element());
441 // Multi sim is turned off
442 const bool simulationsShareState = false;
444 energyData_ = std::make_unique<EnergyData>(statePropagatorData_.get(),
445 freeEnergyPerturbationData_.get(),
446 legacySimulatorData->top_global,
447 legacySimulatorData->inputrec,
448 legacySimulatorData->mdAtoms,
449 legacySimulatorData->enerd,
450 legacySimulatorData->ekind,
451 legacySimulatorData->constr,
452 legacySimulatorData->fplog,
453 legacySimulatorData->fr->fcdata.get(),
454 legacySimulatorData->mdModulesNotifiers,
455 MASTER(legacySimulatorData->cr),
456 legacySimulatorData->observablesHistory,
457 legacySimulatorData->startingBehavior,
458 simulationsShareState);
459 registerExistingElement(energyData_->element());
461 // This is the only modular simulator object which changes the inputrec
462 // TODO: Avoid changing inputrec (#3854)
464 "ReferenceTemperatureManager",
465 ReferenceTemperatureManager(const_cast<t_inputrec*>(legacySimulatorData->inputrec)));
466 auto* referenceTemperatureManager =
467 simulationData<ReferenceTemperatureManager>("ReferenceTemperatureManager").value();
469 // State propagator data is scaling velocities if reference temperature is updated
470 auto* statePropagatorDataPtr = statePropagatorData_.get();
471 referenceTemperatureManager->registerUpdateCallback(
472 [statePropagatorDataPtr](ArrayRef<const real> temperatures,
473 ReferenceTemperatureChangeAlgorithm algorithm) {
474 statePropagatorDataPtr->updateReferenceTemperature(temperatures, algorithm);
478 ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build()
480 if (algorithmHasBeenBuilt_)
482 GMX_THROW(SimulationAlgorithmSetupError(
483 "Tried to build ModularSimulationAlgorithm more than once."));
485 algorithmHasBeenBuilt_ = true;
487 // Connect propagators with thermostat / barostat
488 for (const auto& registrationFunction : pressureTemperatureControlRegistrationFunctions_)
490 for (const auto& connection : propagatorConnections_)
492 registrationFunction(connection);
496 ModularSimulatorAlgorithm algorithm(*(legacySimulatorData_->top_global.name),
497 legacySimulatorData_->fplog,
498 legacySimulatorData_->cr,
499 legacySimulatorData_->mdlog,
500 legacySimulatorData_->mdrunOptions,
501 legacySimulatorData_->inputrec,
502 legacySimulatorData_->nrnb,
503 legacySimulatorData_->wcycle,
504 legacySimulatorData_->fr,
505 legacySimulatorData_->walltime_accounting);
506 registerWithInfrastructureAndSignallers(algorithm.signalHelper_.get());
507 algorithm.statePropagatorData_ = std::move(statePropagatorData_);
508 algorithm.energyData_ = std::move(energyData_);
509 algorithm.freeEnergyPerturbationData_ = std::move(freeEnergyPerturbationData_);
510 algorithm.signals_ = std::move(signals_);
511 algorithm.simulationData_ = std::move(simulationData_);
513 // Multi sim is turned off
514 const bool simulationsShareState = false;
516 // Build stop handler
517 algorithm.stopHandler_ = legacySimulatorData_->stopHandlerBuilder->getStopHandlerMD(
518 compat::not_null<SimulationSignal*>(
519 &(*globalCommunicationHelper_.simulationSignals())[eglsSTOPCOND]),
520 simulationsShareState,
521 MASTER(legacySimulatorData_->cr),
522 legacySimulatorData_->inputrec->nstlist,
523 legacySimulatorData_->mdrunOptions.reproducible,
524 globalCommunicationHelper_.nstglobalcomm(),
525 legacySimulatorData_->mdrunOptions.maximumHoursToRun,
526 legacySimulatorData_->inputrec->nstlist == 0,
527 legacySimulatorData_->fplog,
528 algorithm.stophandlerCurrentStep_,
529 algorithm.stophandlerIsNSStep_,
530 legacySimulatorData_->walltime_accounting);
532 // Build reset handler
533 const bool simulationsShareResetCounters = false;
534 algorithm.resetHandler_ = std::make_unique<ResetHandler>(
535 compat::make_not_null<SimulationSignal*>(
536 &(*globalCommunicationHelper_.simulationSignals())[eglsRESETCOUNTERS]),
537 simulationsShareResetCounters,
538 legacySimulatorData_->inputrec->nsteps,
539 MASTER(legacySimulatorData_->cr),
540 legacySimulatorData_->mdrunOptions.timingOptions.resetHalfway,
541 legacySimulatorData_->mdrunOptions.maximumHoursToRun,
542 legacySimulatorData_->mdlog,
543 legacySimulatorData_->wcycle,
544 legacySimulatorData_->walltime_accounting);
546 // Build topology holder
547 algorithm.topologyHolder_ = topologyHolderBuilder_.build(legacySimulatorData_->top_global,
548 legacySimulatorData_->top,
549 legacySimulatorData_->cr,
550 legacySimulatorData_->inputrec,
551 legacySimulatorData_->fr,
552 legacySimulatorData_->mdAtoms,
553 legacySimulatorData_->constr,
554 legacySimulatorData_->vsite);
555 registerWithInfrastructureAndSignallers(algorithm.topologyHolder_.get());
557 // Build PME load balance helper
558 if (PmeLoadBalanceHelper::doPmeLoadBalancing(legacySimulatorData_->mdrunOptions,
559 legacySimulatorData_->inputrec,
560 legacySimulatorData_->fr))
562 algorithm.pmeLoadBalanceHelper_ =
563 std::make_unique<PmeLoadBalanceHelper>(legacySimulatorData_->mdrunOptions.verbose,
564 algorithm.statePropagatorData_.get(),
565 legacySimulatorData_->fplog,
566 legacySimulatorData_->cr,
567 legacySimulatorData_->mdlog,
568 legacySimulatorData_->inputrec,
569 legacySimulatorData_->wcycle,
570 legacySimulatorData_->fr);
571 registerWithInfrastructureAndSignallers(algorithm.pmeLoadBalanceHelper_.get());
574 // Build trajectory element
575 auto trajectoryElement = trajectoryElementBuilder_.build(legacySimulatorData_->fplog,
576 legacySimulatorData_->nfile,
577 legacySimulatorData_->fnm,
578 legacySimulatorData_->mdrunOptions,
579 legacySimulatorData_->cr,
580 legacySimulatorData_->outputProvider,
581 legacySimulatorData_->mdModulesNotifiers,
582 legacySimulatorData_->inputrec,
583 legacySimulatorData_->top_global,
584 legacySimulatorData_->oenv,
585 legacySimulatorData_->wcycle,
586 legacySimulatorData_->startingBehavior,
587 simulationsShareState);
588 registerWithInfrastructureAndSignallers(trajectoryElement.get());
590 // Build domdec helper (free energy element is a client, so keep this after it is built)
591 if (haveDDAtomOrdering(*legacySimulatorData_->cr))
593 algorithm.domDecHelper_ =
594 domDecHelperBuilder_.build(legacySimulatorData_->mdrunOptions.verbose,
595 legacySimulatorData_->mdrunOptions.verboseStepPrintInterval,
596 algorithm.statePropagatorData_.get(),
597 algorithm.topologyHolder_.get(),
598 globalCommunicationHelper_.nstglobalcomm(),
599 legacySimulatorData_->fplog,
600 legacySimulatorData_->cr,
601 legacySimulatorData_->mdlog,
602 legacySimulatorData_->constr,
603 legacySimulatorData_->inputrec,
604 legacySimulatorData_->mdAtoms,
605 legacySimulatorData_->nrnb,
606 legacySimulatorData_->wcycle,
607 legacySimulatorData_->fr,
608 legacySimulatorData_->vsite,
609 legacySimulatorData_->imdSession,
610 legacySimulatorData_->pull_work);
611 registerWithInfrastructureAndSignallers(algorithm.domDecHelper_.get());
613 // Build checkpoint helper (do this last so everyone else can be a checkpoint client!)
615 checkpointHelperBuilder_.setCheckpointHandler(std::make_unique<CheckpointHandler>(
616 compat::make_not_null<SimulationSignal*>(&(*algorithm.signals_)[eglsCHKPT]),
617 simulationsShareState,
618 legacySimulatorData_->inputrec->nstlist == 0,
619 MASTER(legacySimulatorData_->cr),
620 legacySimulatorData_->mdrunOptions.writeConfout,
621 legacySimulatorData_->mdrunOptions.checkpointOptions.period));
622 algorithm.checkpointHelper_ =
623 checkpointHelperBuilder_.build(legacySimulatorData_->inputrec->init_step,
624 trajectoryElement.get(),
625 legacySimulatorData_->fplog,
626 legacySimulatorData_->cr,
627 legacySimulatorData_->observablesHistory,
628 legacySimulatorData_->walltime_accounting,
629 legacySimulatorData_->state_global,
630 legacySimulatorData_->mdrunOptions.writeConfout);
631 registerWithInfrastructureAndSignallers(algorithm.checkpointHelper_.get());
636 /* Signallers need to be called in an exact order. Some signallers are clients
637 * of other signallers, which requires the clients signallers to be called
638 * _after_ any signaller they are registered to - otherwise, they couldn't
639 * adapt their behavior to the information they got signalled.
641 * Signallers being clients of other signallers require registration.
642 * That registration happens during construction, which in turn means that
643 * we want to construct the signallers in the reverse order of their later
646 * For the above reasons, the `addSignaller` lambda defined below emplaces
647 * added signallers at the beginning of the signaller list, which will yield
648 * a signaller list which is inverse to the build order (and hence equal to
649 * the intended call order).
651 auto addSignaller = [this, &algorithm](auto signaller) {
652 registerWithInfrastructureAndSignallers(signaller.get());
653 algorithm.signallerList_.emplace(algorithm.signallerList_.begin(), std::move(signaller));
655 const auto* inputrec = legacySimulatorData_->inputrec;
656 auto virialMode = EnergySignallerVirialMode::Off;
657 if (inputrec->epc != PressureCoupling::No)
659 if (EI_VV(inputrec->eI))
661 virialMode = EnergySignallerVirialMode::OnStepAndNext;
665 virialMode = EnergySignallerVirialMode::OnStep;
668 addSignaller(energySignallerBuilder_.build(
669 inputrec->nstcalcenergy,
670 computeFepPeriod(*inputrec, legacySimulatorData_->replExParams),
671 inputrec->nstpcouple,
673 addSignaller(trajectorySignallerBuilder_.build(inputrec->nstxout,
676 inputrec->nstxout_compressed,
677 trajectoryElement->tngBoxOut(),
678 trajectoryElement->tngLambdaOut(),
679 trajectoryElement->tngBoxOutCompressed(),
680 trajectoryElement->tngLambdaOutCompressed(),
681 inputrec->nstenergy));
682 addSignaller(loggingSignallerBuilder_.build(
683 inputrec->nstlog, inputrec->init_step, legacySimulatorData_->startingBehavior));
684 addSignaller(lastStepSignallerBuilder_.build(
685 inputrec->nsteps, inputrec->init_step, algorithm.stopHandler_.get()));
686 addSignaller(neighborSearchSignallerBuilder_.build(
687 inputrec->nstlist, inputrec->init_step, inputrec->init_t));
690 // Move setup / teardown list
691 algorithm.elementSetupTeardownList_ = std::move(setupAndTeardownList_);
692 // Move pre- / post-step scheduling lists
693 algorithm.preStepScheduling_ = std::move(preStepScheduling_);
694 algorithm.postStepScheduling_ = std::move(postStepScheduling_);
696 // Create element list
697 // Checkpoint helper needs to be in the call list (as first element!) to react to last step
698 algorithm.elementCallList_.emplace_back(algorithm.checkpointHelper_.get());
699 // Next, update the free energy lambda vector if needed
700 if (algorithm.freeEnergyPerturbationData_)
702 algorithm.elementCallList_.emplace_back(algorithm.freeEnergyPerturbationData_->element());
704 // Then, move the built algorithm
705 algorithm.elementsOwnershipList_.insert(algorithm.elementsOwnershipList_.end(),
706 std::make_move_iterator(elements_.begin()),
707 std::make_move_iterator(elements_.end()));
708 algorithm.elementCallList_.insert(algorithm.elementCallList_.end(),
709 std::make_move_iterator(callList_.begin()),
710 std::make_move_iterator(callList_.end()));
711 // Finally, all trajectory writing is happening after the step
712 // (relevant data was stored by elements through energy signaller)
713 algorithm.elementsOwnershipList_.emplace_back(std::move(trajectoryElement));
714 algorithm.elementCallList_.emplace_back(algorithm.elementsOwnershipList_.back().get());
715 algorithm.elementSetupTeardownList_.emplace_back(algorithm.elementsOwnershipList_.back().get());
721 bool ModularSimulatorAlgorithmBuilder::elementExists(const ISimulatorElement* element) const
723 // Check whether element exists in element list
724 if (std::any_of(elements_.begin(), elements_.end(), [element](auto& existingElement) {
725 return element == existingElement.get();
730 // Check whether element exists in other places controlled by *this
731 return ((statePropagatorData_ && statePropagatorData_->element() == element)
732 || (energyData_ && energyData_->element() == element)
733 || (freeEnergyPerturbationData_ && freeEnergyPerturbationData_->element() == element));
736 std::optional<SignallerCallback> ModularSimulatorAlgorithm::SignalHelper::registerLastStepCallback()
738 return [this](Step step, Time gmx_unused time) { this->lastStep_ = step; };
741 std::optional<SignallerCallback> ModularSimulatorAlgorithm::SignalHelper::registerNSCallback()
743 return [this](Step step, Time gmx_unused time) { this->nextNSStep_ = step; };
746 GlobalCommunicationHelper::GlobalCommunicationHelper(int nstglobalcomm, SimulationSignals* simulationSignals) :
747 nstglobalcomm_(nstglobalcomm), simulationSignals_(simulationSignals)
751 int GlobalCommunicationHelper::nstglobalcomm() const
753 return nstglobalcomm_;
756 SimulationSignals* GlobalCommunicationHelper::simulationSignals()
758 return simulationSignals_;
761 ModularSimulatorAlgorithmBuilderHelper::ModularSimulatorAlgorithmBuilderHelper(
762 ModularSimulatorAlgorithmBuilder* builder) :
767 bool ModularSimulatorAlgorithmBuilderHelper::elementIsStored(const ISimulatorElement* element) const
769 return builder_->elementExists(element);
772 [[maybe_unused]] void ModularSimulatorAlgorithmBuilderHelper::registerPreStepScheduling(SchedulingFunction schedulingFunction)
774 builder_->preStepScheduling_.emplace_back(std::move(schedulingFunction));
777 [[maybe_unused]] void ModularSimulatorAlgorithmBuilderHelper::registerPostStepScheduling(SchedulingFunction schedulingFunction)
779 builder_->postStepScheduling_.emplace_back(std::move(schedulingFunction));
782 std::optional<std::any> ModularSimulatorAlgorithmBuilderHelper::builderData(const std::string& key) const
784 const auto iter = builder_->builderData_.find(key);
785 if (iter == builder_->builderData_.end())
795 void ModularSimulatorAlgorithmBuilderHelper::registerTemperaturePressureControl(
796 std::function<void(const PropagatorConnection&)> registrationFunction)
798 builder_->pressureTemperatureControlRegistrationFunctions_.emplace_back(std::move(registrationFunction));
801 void ModularSimulatorAlgorithmBuilderHelper::registerPropagator(PropagatorConnection connectionData)
803 builder_->propagatorConnections_.emplace_back(std::move(connectionData));
806 void ModularSimulatorAlgorithmBuilderHelper::registerReferenceTemperatureUpdate(
807 ReferenceTemperatureCallback referenceTemperatureCallback)
809 auto* referenceTemperatureManager =
810 simulationData<ReferenceTemperatureManager>("ReferenceTemperatureManager").value();
811 referenceTemperatureManager->registerUpdateCallback(std::move(referenceTemperatureCallback));
814 ReferenceTemperatureCallback ModularSimulatorAlgorithmBuilderHelper::changeReferenceTemperatureCallback()
816 // Capture is safe because SimulatorAlgorithm will manage life time of both the
817 // recipient of the callback and the reference temperature manager
818 auto* referenceTemperatureManager =
819 simulationData<ReferenceTemperatureManager>("ReferenceTemperatureManager").value();
820 return [referenceTemperatureManager](ArrayRef<const real> temperatures,
821 ReferenceTemperatureChangeAlgorithm algorithm) {
822 referenceTemperatureManager->setReferenceTemperature(temperatures, algorithm);