2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2019,2020, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
36 * \brief Defines the microstate for the modular simulator
38 * \author Pascal Merz <pascal.merz@me.com>
39 * \ingroup module_modularsimulator
44 #include "energydata.h"
46 #include "gromacs/gmxlib/network.h"
47 #include "gromacs/math/vec.h"
48 #include "gromacs/mdlib/compute_io.h"
49 #include "gromacs/mdlib/coupling.h"
50 #include "gromacs/mdlib/enerdata_utils.h"
51 #include "gromacs/mdlib/energyoutput.h"
52 #include "gromacs/mdlib/mdatoms.h"
53 #include "gromacs/mdlib/mdoutf.h"
54 #include "gromacs/mdlib/stat.h"
55 #include "gromacs/mdlib/update.h"
56 #include "gromacs/mdrunutility/handlerestart.h"
57 #include "gromacs/mdtypes/checkpointdata.h"
58 #include "gromacs/mdtypes/commrec.h"
59 #include "gromacs/mdtypes/enerdata.h"
60 #include "gromacs/mdtypes/energyhistory.h"
61 #include "gromacs/mdtypes/inputrec.h"
62 #include "gromacs/mdtypes/mdatom.h"
63 #include "gromacs/mdtypes/observableshistory.h"
64 #include "gromacs/mdtypes/pullhistory.h"
65 #include "gromacs/topology/topology.h"
67 #include "freeenergyperturbationdata.h"
68 #include "modularsimulator.h"
69 #include "parrinellorahmanbarostat.h"
70 #include "simulatoralgorithm.h"
71 #include "statepropagatordata.h"
72 #include "velocityscalingtemperaturecoupling.h"
81 EnergyData::EnergyData(StatePropagatorData* statePropagatorData,
82 FreeEnergyPerturbationData* freeEnergyPerturbationData,
83 const gmx_mtop_t* globalTopology,
84 const t_inputrec* inputrec,
85 const MDAtoms* mdAtoms,
86 gmx_enerdata_t* enerd,
87 gmx_ekindata_t* ekind,
88 const Constraints* constr,
91 const MdModulesNotifier& mdModulesNotifier,
93 ObservablesHistory* observablesHistory,
94 StartingBehavior startingBehavior) :
95 element_(std::make_unique<Element>(this, isMasterRank)),
96 isMasterRank_(isMasterRank),
101 needToSumEkinhOld_(false),
102 hasReadEkinFromCheckpoint_(false),
103 startingBehavior_(startingBehavior),
104 statePropagatorData_(statePropagatorData),
105 freeEnergyPerturbationData_(freeEnergyPerturbationData),
106 velocityScalingTemperatureCoupling_(nullptr),
107 parrinelloRahmanBarostat_(nullptr),
109 top_global_(globalTopology),
116 mdModulesNotifier_(mdModulesNotifier),
117 groups_(&globalTopology->groups),
118 observablesHistory_(observablesHistory)
120 clear_mat(forceVirial_);
121 clear_mat(shakeVirial_);
122 clear_mat(totalVirial_);
123 clear_mat(pressure_);
126 init_ekinstate(&ekinstate_, inputrec_);
127 observablesHistory_->energyHistory = std::make_unique<energyhistory_t>();
130 void EnergyData::Element::scheduleTask(Step step, Time time, const RegisterRunFunction& registerRunFunction)
136 auto writeEnergy = energyWritingStep_ == step;
137 auto isEnergyCalculationStep = energyCalculationStep_ == step;
138 auto isFreeEnergyCalculationStep = freeEnergyCalculationStep_ == step;
139 if (isEnergyCalculationStep || writeEnergy)
141 registerRunFunction([this, time, isEnergyCalculationStep, isFreeEnergyCalculationStep]() {
142 energyData_->doStep(time, isEnergyCalculationStep, isFreeEnergyCalculationStep);
147 registerRunFunction([this]() { energyData_->energyOutput_->recordNonEnergyStep(); });
151 void EnergyData::teardown()
153 if (inputrec_->nstcalcenergy > 0 && isMasterRank_)
155 energyOutput_->printAverages(fplog_, groups_);
159 void EnergyData::Element::trajectoryWriterSetup(gmx_mdoutf* outf)
161 energyData_->setup(outf);
164 void EnergyData::setup(gmx_mdoutf* outf)
166 pull_t* pull_work = nullptr;
167 energyOutput_ = std::make_unique<EnergyOutput>(mdoutf_get_fp_ene(outf), top_global_, inputrec_,
168 pull_work, mdoutf_get_fp_dhdl(outf), false,
169 startingBehavior_, mdModulesNotifier_);
176 initializeEnergyHistory(startingBehavior_, observablesHistory_, energyOutput_.get());
178 // TODO: This probably doesn't really belong here...
179 // but we have all we need in this element,
180 // so we'll leave it here for now!
181 double io = compute_io(inputrec_, top_global_->natoms, *groups_, energyOutput_->numEnergyTerms(), 1);
182 if ((io > 2000) && isMasterRank_)
184 fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
186 if (!inputrec_->bContinuation)
188 real temp = enerd_->term[F_TEMP];
189 if (inputrec_->eI != eiVV)
191 /* Result of Ekin averaged over velocities of -half
192 * and +half step, while we only have -half step here.
196 fprintf(fplog_, "Initial temperature: %g K\n", temp);
200 std::optional<ITrajectoryWriterCallback> EnergyData::Element::registerTrajectoryWriterCallback(TrajectoryEvent event)
202 if (event == TrajectoryEvent::EnergyWritingStep && isMasterRank_)
204 return [this](gmx_mdoutf* mdoutf, Step step, Time time, bool writeTrajectory, bool writeLog) {
205 energyData_->write(mdoutf, step, time, writeTrajectory, writeLog);
211 std::optional<SignallerCallback> EnergyData::Element::registerTrajectorySignallerCallback(gmx::TrajectoryEvent event)
213 if (event == TrajectoryEvent::EnergyWritingStep && isMasterRank_)
215 return [this](Step step, Time /*unused*/) { energyWritingStep_ = step; };
220 std::optional<SignallerCallback> EnergyData::Element::registerEnergyCallback(EnergySignallerEvent event)
222 if (event == EnergySignallerEvent::EnergyCalculationStep && isMasterRank_)
224 return [this](Step step, Time /*unused*/) { energyCalculationStep_ = step; };
226 if (event == EnergySignallerEvent::FreeEnergyCalculationStep && isMasterRank_)
228 return [this](Step step, Time /*unused*/) { freeEnergyCalculationStep_ = step; };
233 void EnergyData::doStep(Time time, bool isEnergyCalculationStep, bool isFreeEnergyCalculationStep)
235 enerd_->term[F_ETOT] = enerd_->term[F_EPOT] + enerd_->term[F_EKIN];
236 if (freeEnergyPerturbationData_)
238 accumulateKineticLambdaComponents(enerd_, freeEnergyPerturbationData_->constLambdaView(),
239 *inputrec_->fepvals);
241 if (integratorHasConservedEnergyQuantity(inputrec_))
243 enerd_->term[F_ECONSERVED] =
245 + (velocityScalingTemperatureCoupling_
246 ? velocityScalingTemperatureCoupling_->conservedEnergyContribution()
248 + (parrinelloRahmanBarostat_ ? parrinelloRahmanBarostat_->conservedEnergyContribution() : 0);
250 matrix nullMatrix = {};
251 energyOutput_->addDataAtEnergyStep(
252 isFreeEnergyCalculationStep, isEnergyCalculationStep, time, mdAtoms_->mdatoms()->tmass, enerd_,
253 inputrec_->fepvals, inputrec_->expandedvals, statePropagatorData_->constPreviousBox(),
254 PTCouplingArrays({ parrinelloRahmanBarostat_ ? parrinelloRahmanBarostat_->boxVelocities() : nullMatrix,
259 freeEnergyPerturbationData_ ? freeEnergyPerturbationData_->currentFEPState() : 0,
260 shakeVirial_, forceVirial_, totalVirial_, pressure_, ekind_, muTot_, constr_);
263 void EnergyData::write(gmx_mdoutf* outf, Step step, Time time, bool writeTrajectory, bool writeLog)
267 energyOutput_->printHeader(fplog_, step, time);
270 bool do_dr = do_per_step(step, inputrec_->nstdisreout);
271 bool do_or = do_per_step(step, inputrec_->nstorireout);
273 // energyOutput_->printAnnealingTemperatures(writeLog ? fplog_ : nullptr, groups_, &(inputrec_->opts));
275 energyOutput_->printStepToEnergyFile(mdoutf_get_fp_ene(outf), writeTrajectory, do_dr, do_or,
276 writeLog ? fplog_ : nullptr, step, time, fcd_, awh);
279 void EnergyData::addToForceVirial(const tensor virial, Step step)
281 if (step > forceVirialStep_)
283 forceVirialStep_ = step;
284 clear_mat(forceVirial_);
286 m_add(forceVirial_, virial, forceVirial_);
289 void EnergyData::addToConstraintVirial(const tensor virial, Step step)
291 if (step > shakeVirialStep_)
293 shakeVirialStep_ = step;
294 clear_mat(shakeVirial_);
296 m_add(shakeVirial_, virial, shakeVirial_);
299 rvec* EnergyData::forceVirial(Step gmx_unused step)
301 if (step > forceVirialStep_)
303 forceVirialStep_ = step;
304 clear_mat(forceVirial_);
306 GMX_ASSERT(step >= forceVirialStep_ || forceVirialStep_ == -1,
307 "Asked for force virial of previous step.");
311 rvec* EnergyData::constraintVirial(Step gmx_unused step)
313 if (step > shakeVirialStep_)
315 shakeVirialStep_ = step;
316 clear_mat(shakeVirial_);
318 GMX_ASSERT(step >= shakeVirialStep_ || shakeVirialStep_ == -1,
319 "Asked for constraint virial of previous step.");
323 rvec* EnergyData::totalVirial(Step gmx_unused step)
325 if (step > totalVirialStep_)
327 totalVirialStep_ = step;
328 clear_mat(totalVirial_);
330 GMX_ASSERT(step >= totalVirialStep_ || totalVirialStep_ == -1,
331 "Asked for total virial of previous step.");
335 rvec* EnergyData::pressure(Step gmx_unused step)
337 if (step > pressureStep_)
339 pressureStep_ = step;
340 clear_mat(pressure_);
342 GMX_ASSERT(step >= pressureStep_ || pressureStep_ == -1,
343 "Asked for pressure of previous step.");
347 real* EnergyData::muTot()
352 gmx_enerdata_t* EnergyData::enerdata()
357 gmx_ekindata_t* EnergyData::ekindata()
362 bool* EnergyData::needToSumEkinhOld()
364 return &needToSumEkinhOld_;
367 bool EnergyData::hasReadEkinFromCheckpoint() const
369 return hasReadEkinFromCheckpoint_;
375 * \brief Enum describing the contents EnergyData::Element writes to modular checkpoint
377 * When changing the checkpoint content, add a new element just above Count, and adjust the
378 * checkpoint functionality.
380 enum class CheckpointVersion
382 Base, //!< First version of modular checkpointing
383 Count //!< Number of entries. Add new versions right above this!
385 constexpr auto c_currentVersion = CheckpointVersion(int(CheckpointVersion::Count) - 1);
388 template<CheckpointDataOperation operation>
389 void EnergyData::Element::doCheckpointData(CheckpointData<operation>* checkpointData, const t_commrec* cr)
393 checkpointVersion(checkpointData, "EnergyData version", c_currentVersion);
395 energyData_->observablesHistory_->energyHistory->doCheckpoint<operation>(
396 checkpointData->subCheckpointData("energy history"));
397 energyData_->ekinstate_.doCheckpoint<operation>(
398 checkpointData->subCheckpointData("ekinstate"));
402 void EnergyData::Element::writeCheckpoint(WriteCheckpointData checkpointData, const t_commrec* cr)
406 if (energyData_->needToSumEkinhOld_)
408 energyData_->ekinstate_.bUpToDate = false;
412 update_ekinstate(&energyData_->ekinstate_, energyData_->ekind_);
413 energyData_->ekinstate_.bUpToDate = true;
415 energyData_->energyOutput_->fillEnergyHistory(
416 energyData_->observablesHistory_->energyHistory.get());
418 doCheckpointData<CheckpointDataOperation::Write>(&checkpointData, cr);
421 void EnergyData::Element::readCheckpoint(ReadCheckpointData checkpointData, const t_commrec* cr)
423 doCheckpointData<CheckpointDataOperation::Read>(&checkpointData, cr);
424 energyData_->hasReadEkinFromCheckpoint_ = MASTER(cr) ? energyData_->ekinstate_.bUpToDate : false;
427 gmx_bcast(sizeof(hasReadEkinFromCheckpoint_), &energyData_->hasReadEkinFromCheckpoint_,
428 cr->mpi_comm_mygroup);
430 if (energyData_->hasReadEkinFromCheckpoint_)
432 // this takes care of broadcasting from master to agents
433 restore_ekinstate_from_state(cr, energyData_->ekind_, &energyData_->ekinstate_);
437 const std::string& EnergyData::Element::clientID()
442 void EnergyData::initializeEnergyHistory(StartingBehavior startingBehavior,
443 ObservablesHistory* observablesHistory,
444 EnergyOutput* energyOutput)
446 if (startingBehavior != StartingBehavior::NewSimulation)
448 /* Restore from energy history if appending to output files */
449 if (startingBehavior == StartingBehavior::RestartWithAppending)
451 /* If no history is available (because a checkpoint is from before
452 * it was written) make a new one later, otherwise restore it.
454 if (observablesHistory->energyHistory)
456 energyOutput->restoreFromEnergyHistory(*observablesHistory->energyHistory);
459 else if (observablesHistory->energyHistory)
461 /* We might have read an energy history from checkpoint.
462 * As we are not appending, we want to restart the statistics.
463 * Free the allocated memory and reset the counts.
465 observablesHistory->energyHistory = {};
466 /* We might have read a pull history from checkpoint.
467 * We will still want to keep the statistics, so that the files
468 * can be joined and still be meaningful.
469 * This means that observablesHistory_->pullHistory
470 * should not be reset.
474 if (!observablesHistory->energyHistory)
476 observablesHistory->energyHistory = std::make_unique<energyhistory_t>();
478 if (!observablesHistory->pullHistory)
480 observablesHistory->pullHistory = std::make_unique<PullHistory>();
482 /* Set the initial energy history */
483 energyOutput->fillEnergyHistory(observablesHistory->energyHistory.get());
486 void EnergyData::setVelocityScalingTemperatureCoupling(const VelocityScalingTemperatureCoupling* velocityScalingTemperatureCoupling)
488 velocityScalingTemperatureCoupling_ = velocityScalingTemperatureCoupling;
491 void EnergyData::setParrinelloRahamnBarostat(const gmx::ParrinelloRahmanBarostat* parrinelloRahmanBarostat)
493 parrinelloRahmanBarostat_ = parrinelloRahmanBarostat;
496 EnergyData::Element* EnergyData::element()
498 return element_.get();
501 EnergyData::Element::Element(EnergyData* energyData, bool isMasterRank) :
502 energyData_(energyData),
503 isMasterRank_(isMasterRank),
504 energyWritingStep_(-1),
505 energyCalculationStep_(-1),
506 freeEnergyCalculationStep_(-1)
510 ISimulatorElement* EnergyData::Element::getElementPointerImpl(
511 LegacySimulatorData gmx_unused* legacySimulatorData,
512 ModularSimulatorAlgorithmBuilderHelper gmx_unused* builderHelper,
513 StatePropagatorData gmx_unused* statePropagatorData,
514 EnergyData* energyData,
515 FreeEnergyPerturbationData gmx_unused* freeEnergyPerturbationData,
516 GlobalCommunicationHelper gmx_unused* globalCommunicationHelper)
518 return energyData->element();