2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team.
7 * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
8 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9 * and including many others, as listed in the AUTHORS file in the
10 * top-level source directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
39 * \brief Defines code that writes energy-like quantities.
41 * \author Mark Abraham <mark.j.abraham@gmail.com>
42 * \author Paul Bauer <paul.bauer.q@gmail.com>
43 * \author Artem Zhmurov <zhmurov@gmail.com>
45 * \ingroup module_mdlib
49 #include "energyoutput.h"
58 #include "gromacs/applied_forces/awh/awh.h"
59 #include "gromacs/fileio/enxio.h"
60 #include "gromacs/fileio/gmxfio.h"
61 #include "gromacs/fileio/xvgr.h"
62 #include "gromacs/gmxlib/network.h"
63 #include "gromacs/listed_forces/disre.h"
64 #include "gromacs/listed_forces/orires.h"
65 #include "gromacs/math/functions.h"
66 #include "gromacs/math/units.h"
67 #include "gromacs/math/vec.h"
68 #include "gromacs/mdlib/constr.h"
69 #include "gromacs/mdlib/ebin.h"
70 #include "gromacs/mdlib/mdebin_bar.h"
71 #include "gromacs/mdrunutility/handlerestart.h"
72 #include "gromacs/mdtypes/energyhistory.h"
73 #include "gromacs/mdtypes/fcdata.h"
74 #include "gromacs/mdtypes/group.h"
75 #include "gromacs/mdtypes/inputrec.h"
76 #include "gromacs/mdtypes/md_enums.h"
77 #include "gromacs/mdtypes/state.h"
78 #include "gromacs/pbcutil/pbc.h"
79 #include "gromacs/pulling/pull.h"
80 #include "gromacs/topology/mtop_util.h"
81 #include "gromacs/trajectory/energyframe.h"
82 #include "gromacs/utility/arraysize.h"
83 #include "gromacs/utility/enumerationhelpers.h"
84 #include "gromacs/utility/fatalerror.h"
85 #include "gromacs/utility/mdmodulesnotifiers.h"
86 #include "gromacs/utility/smalloc.h"
87 #include "gromacs/utility/stringutil.h"
89 #include "energydrifttracker.h"
91 //! Labels for energy file quantities
93 static const char* conrmsd_nm[] = { "Constr. rmsd", "Constr.2 rmsd" };
95 static std::array<const char*, 3> boxs_nm = { "Box-X", "Box-Y", "Box-Z" };
97 static std::array<const char*, 6> tricl_boxs_nm = { "Box-XX", "Box-YY", "Box-ZZ",
98 "Box-YX", "Box-ZX", "Box-ZY" };
100 static const char* vol_nm[] = { "Volume" };
102 static const char* dens_nm[] = { "Density" };
104 static const char* pv_nm[] = { "pV" };
106 static const char* enthalpy_nm[] = { "Enthalpy" };
108 static std::array<const char*, 6> boxvel_nm = { "Box-Vel-XX", "Box-Vel-YY", "Box-Vel-ZZ",
109 "Box-Vel-YX", "Box-Vel-ZX", "Box-Vel-ZY" };
111 const char* enumValueToString(NonBondedEnergyTerms enumValue)
113 static constexpr gmx::EnumerationArray<NonBondedEnergyTerms, const char*> nonBondedEnergyTermTypeNames = {
114 "Coul-SR", "LJ-SR", "Buck-SR", "Coul-14", "LJ-14"
116 return nonBondedEnergyTermTypeNames[enumValue];
124 /*! \brief Energy output class
126 * This is the collection of energy averages collected during mdrun, and to
127 * be written out to the .edr file.
129 * \todo Use more std containers.
130 * \todo Remove GMX_CONSTRAINTVIR
131 * \todo Write free-energy output also to energy file (after adding more tests)
133 EnergyOutput::EnergyOutput(ener_file* fp_ene,
134 const gmx_mtop_t& mtop,
135 const t_inputrec& inputrec,
136 const pull_t* pull_work,
139 const StartingBehavior startingBehavior,
140 const bool simulationsShareState,
141 const MDModulesNotifiers& mdModulesNotifiers)
143 const char* ener_nm[F_NRE];
144 static const char* vir_nm[] = { "Vir-XX", "Vir-XY", "Vir-XZ", "Vir-YX", "Vir-YY",
145 "Vir-YZ", "Vir-ZX", "Vir-ZY", "Vir-ZZ" };
146 static const char* sv_nm[] = { "ShakeVir-XX", "ShakeVir-XY", "ShakeVir-XZ",
147 "ShakeVir-YX", "ShakeVir-YY", "ShakeVir-YZ",
148 "ShakeVir-ZX", "ShakeVir-ZY", "ShakeVir-ZZ" };
149 static const char* fv_nm[] = { "ForceVir-XX", "ForceVir-XY", "ForceVir-XZ",
150 "ForceVir-YX", "ForceVir-YY", "ForceVir-YZ",
151 "ForceVir-ZX", "ForceVir-ZY", "ForceVir-ZZ" };
152 static const char* pres_nm[] = { "Pres-XX", "Pres-XY", "Pres-XZ", "Pres-YX", "Pres-YY",
153 "Pres-YZ", "Pres-ZX", "Pres-ZY", "Pres-ZZ" };
154 static const char* surft_nm[] = { "#Surf*SurfTen" };
155 static const char* mu_nm[] = { "Mu-X", "Mu-Y", "Mu-Z" };
156 static const char* vcos_nm[] = { "2CosZ*Vel-X" };
157 static const char* visc_nm[] = { "1/Viscosity" };
158 static const char* baro_nm[] = { "Barostat" };
160 const SimulationGroups* groups;
164 int i, j, ni, nj, n, ncon, nset;
167 if (EI_DYNAMICS(inputrec.eI))
169 delta_t_ = inputrec.delta_t;
176 groups = &mtop.groups;
178 bBHAM = (mtop.ffparams.numTypes() > 0) && (mtop.ffparams.functype[0] == F_BHAM);
179 b14 = (gmx_mtop_ftype_count(mtop, F_LJ14) > 0 || gmx_mtop_ftype_count(mtop, F_LJC14_Q) > 0);
181 ncon = gmx_mtop_ftype_count(mtop, F_CONSTR);
182 nset = gmx_mtop_ftype_count(mtop, F_SETTLE);
183 bool bConstr = (ncon > 0 || nset > 0) && !isRerun;
188 if (ncon > 0 && inputrec.eConstrAlg == ConstraintAlgorithm::Lincs)
192 bConstrVir_ = (getenv("GMX_CONSTRAINTVIR") != nullptr);
199 /* Energy monitoring */
200 for (auto& term : bEInd_)
205 // Setting true only to those energy terms, that have active interactions and
206 // are not vsite terms (not VSITE2, VSITE3, VSITE3FD, VSITE3FAD, VSITE3OUT, VSITE4FD, VSITE4FDN, or VSITEN)
207 for (i = 0; i < F_NRE; i++)
209 bEner_[i] = (gmx_mtop_ftype_count(mtop, i) > 0)
210 && ((interaction_function[i].flags & IF_VSITE) == 0);
215 bEner_[F_EKIN] = EI_DYNAMICS(inputrec.eI);
216 bEner_[F_ETOT] = EI_DYNAMICS(inputrec.eI);
217 bEner_[F_TEMP] = EI_DYNAMICS(inputrec.eI);
219 bEner_[F_ECONSERVED] = integratorHasConservedEnergyQuantity(&inputrec);
220 bEner_[F_PDISPCORR] = (inputrec.eDispCorr != DispersionCorrectionType::No);
221 bEner_[F_PRES] = true;
224 bEner_[F_LJ] = !bBHAM;
225 bEner_[F_BHAM] = bBHAM;
226 bEner_[F_EQM] = inputrec.bQMMM;
227 bEner_[F_RF_EXCL] = (EEL_RF(inputrec.coulombtype) && inputrec.cutoff_scheme == CutoffScheme::Group);
228 bEner_[F_COUL_RECIP] = EEL_FULL(inputrec.coulombtype);
229 bEner_[F_LJ_RECIP] = EVDW_PME(inputrec.vdwtype);
230 bEner_[F_LJ14] = b14;
231 bEner_[F_COUL14] = b14;
232 bEner_[F_LJC14_Q] = false;
233 bEner_[F_LJC_PAIRS_NB] = false;
236 bEner_[F_DVDL_COUL] = (inputrec.efep != FreeEnergyPerturbationType::No)
237 && inputrec.fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Coul];
238 bEner_[F_DVDL_VDW] = (inputrec.efep != FreeEnergyPerturbationType::No)
239 && inputrec.fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Vdw];
240 bEner_[F_DVDL_BONDED] = (inputrec.efep != FreeEnergyPerturbationType::No)
241 && inputrec.fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Bonded];
242 bEner_[F_DVDL_RESTRAINT] =
243 (inputrec.efep != FreeEnergyPerturbationType::No)
244 && inputrec.fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Restraint];
245 bEner_[F_DKDL] = (inputrec.efep != FreeEnergyPerturbationType::No)
246 && inputrec.fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Mass];
247 bEner_[F_DVDL] = (inputrec.efep != FreeEnergyPerturbationType::No)
248 && inputrec.fepvals->separate_dvdl[FreeEnergyPerturbationCouplingType::Fep];
250 bEner_[F_CONSTR] = false;
251 bEner_[F_CONSTRNC] = false;
252 bEner_[F_SETTLE] = false;
254 bEner_[F_COUL_SR] = true;
255 bEner_[F_EPOT] = true;
257 bEner_[F_DISPCORR] = (inputrec.eDispCorr != DispersionCorrectionType::No);
258 bEner_[F_DISRESVIOL] = (gmx_mtop_ftype_count(mtop, F_DISRES) > 0);
259 bEner_[F_ORIRESDEV] = (gmx_mtop_ftype_count(mtop, F_ORIRES) > 0);
260 bEner_[F_COM_PULL] = ((inputrec.bPull && pull_have_potential(*pull_work)) || inputrec.bRot);
262 MDModulesEnergyOutputToDensityFittingRequestChecker mdModulesAddOutputToDensityFittingFieldRequest;
263 mdModulesNotifiers.simulationSetupNotifier_.notify(&mdModulesAddOutputToDensityFittingFieldRequest);
265 bEner_[F_DENSITYFITTING] = mdModulesAddOutputToDensityFittingFieldRequest.energyOutputToDensityFitting_;
268 // Counting the energy terms that will be printed and saving their names
270 for (i = 0; i < F_NRE; i++)
274 ener_nm[f_nre_] = interaction_function[i].longname;
279 epc_ = isRerun ? PressureCoupling::No : inputrec.epc;
280 bDiagPres_ = !TRICLINIC(inputrec.ref_p) && !isRerun;
281 ref_p_ = (inputrec.ref_p[XX][XX] + inputrec.ref_p[YY][YY] + inputrec.ref_p[ZZ][ZZ]) / DIM;
282 bTricl_ = TRICLINIC(inputrec.compress) || TRICLINIC(inputrec.deform);
283 bDynBox_ = inputrecDynamicBox(&inputrec);
284 etc_ = isRerun ? TemperatureCoupling::No : inputrec.etc;
285 bNHC_trotter_ = inputrecNvtTrotter(&inputrec) && !isRerun;
286 bPrintNHChains_ = inputrec.bPrintNHChains && !isRerun;
287 bMTTK_ = (inputrecNptTrotter(&inputrec) || inputrecNphTrotter(&inputrec)) && !isRerun;
288 bMu_ = inputrecNeedMutot(&inputrec);
292 /* Pass NULL for unit to let get_ebin_space determine the units
293 * for interaction_function[i].longname
295 ie_ = get_ebin_space(ebin_, f_nre_, ener_nm, nullptr);
298 /* This should be called directly after the call for ie_,
299 * such that iconrmsd_ follows directly in the list.
301 iconrmsd_ = get_ebin_space(ebin_, nCrmsd_, conrmsd_nm, "");
305 ib_ = get_ebin_space(ebin_,
306 bTricl_ ? tricl_boxs_nm.size() : boxs_nm.size(),
307 bTricl_ ? tricl_boxs_nm.data() : boxs_nm.data(),
309 ivol_ = get_ebin_space(ebin_, 1, vol_nm, unit_volume);
310 idens_ = get_ebin_space(ebin_, 1, dens_nm, unit_density_SI);
313 ipv_ = get_ebin_space(ebin_, 1, pv_nm, unit_energy);
314 ienthalpy_ = get_ebin_space(ebin_, 1, enthalpy_nm, unit_energy);
319 isvir_ = get_ebin_space(ebin_, asize(sv_nm), sv_nm, unit_energy);
320 ifvir_ = get_ebin_space(ebin_, asize(fv_nm), fv_nm, unit_energy);
324 ivir_ = get_ebin_space(ebin_, asize(vir_nm), vir_nm, unit_energy);
325 ipres_ = get_ebin_space(ebin_, asize(pres_nm), pres_nm, unit_pres_bar);
326 isurft_ = get_ebin_space(ebin_, asize(surft_nm), surft_nm, unit_surft_bar);
328 if (epc_ == PressureCoupling::ParrinelloRahman || epc_ == PressureCoupling::Mttk)
330 ipc_ = get_ebin_space(ebin_, bTricl_ ? boxvel_nm.size() : DIM, boxvel_nm.data(), unit_vel);
334 imu_ = get_ebin_space(ebin_, asize(mu_nm), mu_nm, unit_dipole_D);
336 if (inputrec.cos_accel != 0)
338 ivcos_ = get_ebin_space(ebin_, asize(vcos_nm), vcos_nm, unit_vel);
339 ivisc_ = get_ebin_space(ebin_, asize(visc_nm), visc_nm, unit_invvisc_SI);
342 /* Energy monitoring */
343 for (auto& term : bEInd_)
347 bEInd_[NonBondedEnergyTerms::CoulombSR] = true;
348 bEInd_[NonBondedEnergyTerms::LJSR] = true;
352 bEInd_[NonBondedEnergyTerms::LJSR] = false;
353 bEInd_[NonBondedEnergyTerms::BuckinghamSR] = true;
357 bEInd_[NonBondedEnergyTerms::LJ14] = true;
358 bEInd_[NonBondedEnergyTerms::Coulomb14] = true;
361 for (auto term : bEInd_)
368 n = groups->groups[SimulationAtomGroupType::EnergyOutput].size();
370 nE_ = (n * (n + 1)) / 2;
377 for (int k = 0; (k < nEc_); k++)
379 snew(gnm[k], STRLEN);
381 for (i = 0; (i < gmx::ssize(groups->groups[SimulationAtomGroupType::EnergyOutput])); i++)
383 ni = groups->groups[SimulationAtomGroupType::EnergyOutput][i];
384 for (j = i; (j < gmx::ssize(groups->groups[SimulationAtomGroupType::EnergyOutput])); j++)
386 nj = groups->groups[SimulationAtomGroupType::EnergyOutput][j];
388 for (auto key : keysOf(bEInd_))
394 enumValueToString(key),
395 *(groups->groupNames[ni]),
396 *(groups->groupNames[nj]));
400 igrp_[n] = get_ebin_space(ebin_, nEc_, gnm, unit_energy);
404 for (int k = 0; (k < nEc_); k++)
412 gmx_incons("Number of energy terms wrong");
416 nTC_ = isRerun ? 0 : groups->groups[SimulationAtomGroupType::TemperatureCoupling].size();
417 nNHC_ = inputrec.opts.nhchainlength; /* shorthand for number of NH chains */
420 nTCP_ = 1; /* assume only one possible coupling system for barostat
427 if (etc_ == TemperatureCoupling::NoseHoover)
431 mde_n_ = 2 * nNHC_ * nTC_;
437 if (epc_ == PressureCoupling::Mttk)
439 mdeb_n_ = 2 * nNHC_ * nTCP_;
448 tmp_r_.resize(mde_n_);
449 // TODO redo the group name memory management to make it more clear
451 snew(grpnms, std::max(mde_n_, mdeb_n_)); // Just in case mdeb_n_ > mde_n_
453 for (i = 0; (i < nTC_); i++)
455 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
456 sprintf(buf, "T-%s", *(groups->groupNames[ni]));
457 grpnms[i] = gmx_strdup(buf);
459 itemp_ = get_ebin_space(ebin_, nTC_, grpnms, unit_temp_K);
460 for (i = 0; i < nTC_; i++)
466 if (etc_ == TemperatureCoupling::NoseHoover)
472 for (i = 0; (i < nTC_); i++)
474 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
475 bufi = *(groups->groupNames[ni]);
476 for (j = 0; (j < nNHC_); j++)
478 sprintf(buf, "Xi-%d-%s", j, bufi);
479 grpnms[2 * (i * nNHC_ + j)] = gmx_strdup(buf);
480 sprintf(buf, "vXi-%d-%s", j, bufi);
481 grpnms[2 * (i * nNHC_ + j) + 1] = gmx_strdup(buf);
484 itc_ = get_ebin_space(ebin_, mde_n_, grpnms, unit_invtime);
488 for (i = 0; (i < nTCP_); i++)
490 bufi = baro_nm[0]; /* All barostat DOF's together for now. */
491 for (j = 0; (j < nNHC_); j++)
493 sprintf(buf, "Xi-%d-%s", j, bufi);
494 grpnms[2 * (i * nNHC_ + j)] = gmx_strdup(buf);
495 sprintf(buf, "vXi-%d-%s", j, bufi);
496 grpnms[2 * (i * nNHC_ + j) + 1] = gmx_strdup(buf);
499 itcb_ = get_ebin_space(ebin_, mdeb_n_, grpnms, unit_invtime);
505 for (i = 0; (i < nTC_); i++)
507 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
508 bufi = *(groups->groupNames[ni]);
509 sprintf(buf, "Xi-%s", bufi);
510 grpnms[2 * i] = gmx_strdup(buf);
511 sprintf(buf, "vXi-%s", bufi);
512 grpnms[2 * i + 1] = gmx_strdup(buf);
514 itc_ = get_ebin_space(ebin_, mde_n_, grpnms, unit_invtime);
519 else if (etc_ == TemperatureCoupling::Berendsen || etc_ == TemperatureCoupling::Yes
520 || etc_ == TemperatureCoupling::VRescale)
522 for (i = 0; (i < nTC_); i++)
524 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
525 sprintf(buf, "Lamb-%s", *(groups->groupNames[ni]));
526 grpnms[i] = gmx_strdup(buf);
528 itc_ = get_ebin_space(ebin_, mde_n_, grpnms, "");
532 for (i = 0; i < allocated; i++)
538 /* Note that fp_ene should be valid on the master rank and null otherwise */
539 if (fp_ene != nullptr && startingBehavior != StartingBehavior::RestartWithAppending)
541 do_enxnms(fp_ene, &ebin_->nener, &ebin_->enm);
544 /* check whether we're going to write dh histograms */
546 if (inputrec.fepvals->separate_dhdl_file == SeparateDhdlFile::No)
548 /* Currently dh histograms are only written with dynamics */
549 if (EI_DYNAMICS(inputrec.eI))
551 dhc_ = std::make_unique<t_mde_delta_h_coll>(inputrec);
554 dE_.resize(inputrec.fepvals->n_lambda);
559 dE_.resize(inputrec.fepvals->n_lambda);
561 if (inputrec.bSimTemp)
563 temperatures_ = inputrec.simtempvals->temperatures;
566 if (EI_MD(inputrec.eI) && !simulationsShareState)
568 conservedEnergyTracker_ = std::make_unique<EnergyDriftTracker>(mtop.natoms);
572 EnergyOutput::~EnergyOutput()
579 /*! \brief Print a lambda vector to a string
581 * \param[in] fep The inputrec's FEP input data
582 * \param[in] i The index of the lambda vector
583 * \param[in] get_native_lambda Whether to print the native lambda
584 * \param[in] get_names Whether to print the names rather than the values
585 * \param[in,out] str The pre-allocated string buffer to print to.
587 static void print_lambda_vector(t_lambda* fep, int i, bool get_native_lambda, bool get_names, char* str)
592 for (auto j : keysOf(fep->separate_dvdl))
594 if (fep->separate_dvdl[j])
599 str[0] = 0; /* reset the string */
602 str += sprintf(str, "("); /* set the opening parenthesis*/
604 for (auto j : keysOf(fep->separate_dvdl))
606 if (fep->separate_dvdl[j])
610 if (get_native_lambda && fep->init_lambda >= 0)
612 str += sprintf(str, "%.4f", fep->init_lambda);
616 str += sprintf(str, "%.4f", fep->all_lambda[j][i]);
621 str += sprintf(str, "%s", enumValueToStringSingular(j));
623 /* print comma for the next item */
626 str += sprintf(str, ", ");
633 /* and add the closing parenthesis */
638 FILE* open_dhdl(const char* filename, const t_inputrec* ir, const gmx_output_env_t* oenv)
641 const char *dhdl = "dH/d\\lambda", *deltag = "\\DeltaH", *lambda = "\\lambda",
642 *lambdastate = "\\lambda state";
643 int i, nsets, nsets_de, nsetsbegin;
644 int n_lambda_terms = 0;
645 t_lambda* fep = ir->fepvals.get(); /* for simplicity */
646 t_expanded* expand = ir->expandedvals.get();
647 char lambda_vec_str[STRLEN], lambda_name_str[STRLEN];
652 bool write_pV = false;
654 /* count the number of different lambda terms */
655 for (auto i : keysOf(fep->separate_dvdl))
657 if (fep->separate_dvdl[i])
663 std::string title, label_x, label_y;
664 if (fep->n_lambda == 0)
666 title = gmx::formatString("%s", dhdl);
667 label_x = gmx::formatString("Time (ps)");
668 label_y = gmx::formatString("%s (%s %s)", dhdl, unit_energy, "[\\lambda]\\S-1\\N");
672 title = gmx::formatString("%s and %s", dhdl, deltag);
673 label_x = gmx::formatString("Time (ps)");
674 label_y = gmx::formatString(
675 "%s and %s (%s %s)", dhdl, deltag, unit_energy, "[\\8l\\4]\\S-1\\N");
677 fp = gmx_fio_fopen(filename, "w+");
678 xvgr_header(fp, title.c_str(), label_x, label_y, exvggtXNY, oenv);
683 buf = gmx::formatString("T = %g (K) ", ir->opts.ref_t[0]);
685 if ((ir->efep != FreeEnergyPerturbationType::SlowGrowth)
686 && (ir->efep != FreeEnergyPerturbationType::Expanded))
688 if ((fep->init_lambda >= 0) && (n_lambda_terms == 1))
690 /* compatibility output */
691 buf += gmx::formatString("%s = %.4f", lambda, fep->init_lambda);
695 print_lambda_vector(fep, fep->init_fep_state, true, false, lambda_vec_str);
696 print_lambda_vector(fep, fep->init_fep_state, true, true, lambda_name_str);
697 buf += gmx::formatString(
698 "%s %d: %s = %s", lambdastate, fep->init_fep_state, lambda_name_str, lambda_vec_str);
701 xvgr_subtitle(fp, buf.c_str(), oenv);
705 if (fep->dhdl_derivatives == DhDlDerivativeCalculation::Yes)
707 nsets_dhdl = n_lambda_terms;
709 /* count the number of delta_g states */
710 nsets_de = fep->lambda_stop_n - fep->lambda_start_n;
712 nsets = nsets_dhdl + nsets_de; /* dhdl + fep differences */
714 if (fep->n_lambda > 0 && (expand->elmcmove > LambdaMoveCalculation::No))
716 nsets += 1; /*add fep state for expanded ensemble */
719 if (fep->edHdLPrintEnergy != FreeEnergyPrintEnergy::No)
721 nsets += 1; /* add energy to the dhdl as well */
725 if ((ir->epc != PressureCoupling::No) && (fep->n_lambda > 0) && (fep->init_lambda < 0))
727 nsetsextend += 1; /* for PV term, other terms possible if required for
728 the reduced potential (only needed with foreign
729 lambda, and only output when init_lambda is not
730 set in order to maintain compatibility of the
734 std::vector<std::string> setname(nsetsextend);
736 if (expand->elmcmove > LambdaMoveCalculation::No)
738 /* state for the fep_vals, if we have alchemical sampling */
739 setname[s++] = "Thermodynamic state";
742 if (fep->edHdLPrintEnergy != FreeEnergyPrintEnergy::No)
745 switch (fep->edHdLPrintEnergy)
747 case FreeEnergyPrintEnergy::Potential:
748 energy = gmx::formatString("%s (%s)", "Potential Energy", unit_energy);
750 case FreeEnergyPrintEnergy::Total:
751 case FreeEnergyPrintEnergy::Yes:
752 default: energy = gmx::formatString("%s (%s)", "Total Energy", unit_energy);
754 setname[s++] = energy;
757 if (fep->dhdl_derivatives == DhDlDerivativeCalculation::Yes)
759 for (auto i : keysOf(fep->separate_dvdl))
761 if (fep->separate_dvdl[i])
763 std::string derivative;
764 if ((fep->init_lambda >= 0) && (n_lambda_terms == 1))
766 /* compatibility output */
767 derivative = gmx::formatString("%s %s %.4f", dhdl, lambda, fep->init_lambda);
771 double lam = fep->init_lambda;
772 if (fep->init_lambda < 0)
774 lam = fep->all_lambda[i][fep->init_fep_state];
776 derivative = gmx::formatString("%s %s = %.4f", dhdl, enumValueToStringSingular(i), lam);
778 setname[s++] = derivative;
783 if (fep->n_lambda > 0)
785 /* g_bar has to determine the lambda values used in this simulation
786 * from this xvg legend.
789 if (expand->elmcmove > LambdaMoveCalculation::No)
791 nsetsbegin = 1; /* for including the expanded ensemble */
798 if (fep->edHdLPrintEnergy != FreeEnergyPrintEnergy::No)
802 nsetsbegin += nsets_dhdl;
804 for (i = fep->lambda_start_n; i < fep->lambda_stop_n; i++)
806 print_lambda_vector(fep, i, false, false, lambda_vec_str);
808 if ((fep->init_lambda >= 0) && (n_lambda_terms == 1))
810 /* for compatible dhdl.xvg files */
811 buf = gmx::formatString("%s %s %s", deltag, lambda, lambda_vec_str);
815 buf = gmx::formatString("%s %s to %s", deltag, lambda, lambda_vec_str);
820 /* print the temperature for this state if doing simulated annealing */
821 buf += gmx::formatString(
822 "T = %g (%s)", ir->simtempvals->temperatures[s - (nsetsbegin)], unit_temp_K);
828 setname[s++] = gmx::formatString("pV (%s)", unit_energy);
831 xvgrLegend(fp, setname, oenv);
840 void EnergyOutput::addDataAtEnergyStep(bool bDoDHDL,
844 const gmx_enerdata_t* enerd,
846 const t_expanded* expand,
848 PTCouplingArrays ptCouplingArrays,
854 const gmx_ekindata_t* ekind,
856 const gmx::Constraints* constr)
858 int j, k, kk, n, gid;
859 real crmsd[2], tmp6[6];
860 real bs[tricl_boxs_nm.size()], vol, dens, enthalpy;
861 real eee[static_cast<int>(NonBondedEnergyTerms::Count)];
862 gmx::EnumerationArray<FreeEnergyPerturbationCouplingType, double> store_dhdl;
863 real store_energy = 0;
865 real pv = 0.0; // static analyzer warns about uninitialized variable warnings here.
867 /* Do NOT use the box in the state variable, but the separate box provided
868 * as an argument. This is because we sometimes need to write the box from
869 * the last timestep to match the trajectory frames.
871 add_ebin_indexed(ebin_, ie_, gmx::ArrayRef<bool>(bEner_), enerd->term, bSum);
874 crmsd[0] = constr->rmsd();
875 add_ebin(ebin_, iconrmsd_, nCrmsd_, crmsd, false);
888 nboxs = tricl_boxs_nm.size();
895 nboxs = boxs_nm.size();
897 vol = box[XX][XX] * box[YY][YY] * box[ZZ][ZZ];
898 dens = (tmass * gmx::c_amu) / (vol * gmx::c_nano * gmx::c_nano * gmx::c_nano);
899 add_ebin(ebin_, ib_, nboxs, bs, bSum);
900 add_ebin(ebin_, ivol_, 1, &vol, bSum);
901 add_ebin(ebin_, idens_, 1, &dens, bSum);
905 /* This is pV (in kJ/mol). The pressure is the reference pressure,
906 not the instantaneous pressure */
907 pv = vol * ref_p_ / gmx::c_presfac;
909 add_ebin(ebin_, ipv_, 1, &pv, bSum);
910 enthalpy = pv + enerd->term[F_ETOT];
911 add_ebin(ebin_, ienthalpy_, 1, &enthalpy, bSum);
916 add_ebin(ebin_, isvir_, 9, svir[0], bSum);
917 add_ebin(ebin_, ifvir_, 9, fvir[0], bSum);
921 add_ebin(ebin_, ivir_, 9, vir[0], bSum);
922 add_ebin(ebin_, ipres_, 9, pres[0], bSum);
923 tmp = (pres[ZZ][ZZ] - (pres[XX][XX] + pres[YY][YY]) * 0.5) * box[ZZ][ZZ];
924 add_ebin(ebin_, isurft_, 1, &tmp, bSum);
926 if (epc_ == PressureCoupling::ParrinelloRahman || epc_ == PressureCoupling::Mttk)
928 tmp6[0] = ptCouplingArrays.boxv[XX][XX];
929 tmp6[1] = ptCouplingArrays.boxv[YY][YY];
930 tmp6[2] = ptCouplingArrays.boxv[ZZ][ZZ];
931 tmp6[3] = ptCouplingArrays.boxv[YY][XX];
932 tmp6[4] = ptCouplingArrays.boxv[ZZ][XX];
933 tmp6[5] = ptCouplingArrays.boxv[ZZ][YY];
934 add_ebin(ebin_, ipc_, bTricl_ ? 6 : 3, tmp6, bSum);
938 add_ebin(ebin_, imu_, 3, mu_tot, bSum);
940 if (ekind && ekind->cosacc.cos_accel != 0)
942 vol = box[XX][XX] * box[YY][YY] * box[ZZ][ZZ];
943 dens = (tmass * gmx::c_amu) / (vol * gmx::c_nano * gmx::c_nano * gmx::c_nano);
944 add_ebin(ebin_, ivcos_, 1, &(ekind->cosacc.vcos), bSum);
945 /* 1/viscosity, unit 1/(kg m^-1 s^-1) */
947 / (ekind->cosacc.cos_accel / (ekind->cosacc.vcos * gmx::c_pico) * dens
948 * gmx::square(box[ZZ][ZZ] * gmx::c_nano / (2 * M_PI)));
949 add_ebin(ebin_, ivisc_, 1, &tmp, bSum);
954 for (int i = 0; (i < nEg_); i++)
956 for (j = i; (j < nEg_); j++)
958 gid = GID(i, j, nEg_);
959 for (k = kk = 0; (k < static_cast<int>(NonBondedEnergyTerms::Count)); k++)
963 eee[kk++] = enerd->grpp.energyGroupPairTerms[k][gid];
966 add_ebin(ebin_, igrp_[n], nEc_, eee, bSum);
974 for (int i = 0; (i < nTC_); i++)
976 tmp_r_[i] = ekind->tcstat[i].T;
978 add_ebin(ebin_, itemp_, nTC_, tmp_r_.data(), bSum);
980 if (etc_ == TemperatureCoupling::NoseHoover)
982 /* whether to print Nose-Hoover chains: */
987 for (int i = 0; (i < nTC_); i++)
989 for (j = 0; j < nNHC_; j++)
992 tmp_r_[2 * k] = ptCouplingArrays.nosehoover_xi[k];
993 tmp_r_[2 * k + 1] = ptCouplingArrays.nosehoover_vxi[k];
996 add_ebin(ebin_, itc_, mde_n_, tmp_r_.data(), bSum);
1000 for (int i = 0; (i < nTCP_); i++)
1002 for (j = 0; j < nNHC_; j++)
1005 tmp_r_[2 * k] = ptCouplingArrays.nhpres_xi[k];
1006 tmp_r_[2 * k + 1] = ptCouplingArrays.nhpres_vxi[k];
1009 add_ebin(ebin_, itcb_, mdeb_n_, tmp_r_.data(), bSum);
1014 for (int i = 0; (i < nTC_); i++)
1016 tmp_r_[2 * i] = ptCouplingArrays.nosehoover_xi[i];
1017 tmp_r_[2 * i + 1] = ptCouplingArrays.nosehoover_vxi[i];
1019 add_ebin(ebin_, itc_, mde_n_, tmp_r_.data(), bSum);
1023 else if (etc_ == TemperatureCoupling::Berendsen || etc_ == TemperatureCoupling::Yes
1024 || etc_ == TemperatureCoupling::VRescale)
1026 for (int i = 0; (i < nTC_); i++)
1028 tmp_r_[i] = ekind->tcstat[i].lambda;
1030 add_ebin(ebin_, itc_, nTC_, tmp_r_.data(), bSum);
1034 ebin_increase_count(1, ebin_, bSum);
1036 // BAR + thermodynamic integration values
1037 if ((fp_dhdl_ || dhc_) && bDoDHDL)
1039 const auto& foreignTerms = enerd->foreignLambdaTerms;
1040 for (int i = 0; i < foreignTerms.numLambdas(); i++)
1042 /* zero for simulated tempering */
1043 dE_[i] = foreignTerms.deltaH(i);
1044 if (!temperatures_.empty())
1046 GMX_RELEASE_ASSERT(gmx::ssize(temperatures_) > fep_state,
1047 "Number of lambdas in state is bigger then in input record");
1049 gmx::ssize(temperatures_) >= foreignTerms.numLambdas(),
1050 "Number of lambdas in energy data is bigger then in input record");
1051 /* MRS: is this right, given the way we have defined the exchange probabilities? */
1052 /* is this even useful to have at all? */
1053 dE_[i] += (temperatures_[i] / temperatures_[fep_state] - 1.0) * enerd->term[F_EKIN];
1059 fprintf(fp_dhdl_, "%.4f", time);
1060 /* the current free energy state */
1062 /* print the current state if we are doing expanded ensemble */
1063 if (expand->elmcmove > LambdaMoveCalculation::No)
1065 fprintf(fp_dhdl_, " %4d", fep_state);
1067 /* total energy (for if the temperature changes */
1069 if (fep->edHdLPrintEnergy != FreeEnergyPrintEnergy::No)
1071 switch (fep->edHdLPrintEnergy)
1073 case FreeEnergyPrintEnergy::Potential:
1074 store_energy = enerd->term[F_EPOT];
1076 case FreeEnergyPrintEnergy::Total:
1077 case FreeEnergyPrintEnergy::Yes:
1078 default: store_energy = enerd->term[F_ETOT];
1080 fprintf(fp_dhdl_, " %#.8g", store_energy);
1083 if (fep->dhdl_derivatives == DhDlDerivativeCalculation::Yes)
1085 for (auto i : keysOf(fep->separate_dvdl))
1087 if (fep->separate_dvdl[i])
1089 /* assumes F_DVDL is first */
1090 fprintf(fp_dhdl_, " %#.8g", enerd->term[F_DVDL + static_cast<int>(i)]);
1094 for (int i = fep->lambda_start_n; i < fep->lambda_stop_n; i++)
1096 fprintf(fp_dhdl_, " %#.8g", dE_[i]);
1098 if (bDynBox_ && bDiagPres_ && (epc_ != PressureCoupling::No)
1099 && foreignTerms.numLambdas() > 0 && (fep->init_lambda < 0))
1101 fprintf(fp_dhdl_, " %#.8g", pv); /* PV term only needed when
1102 there are alternate state
1103 lambda and we're not in
1104 compatibility mode */
1106 fprintf(fp_dhdl_, "\n");
1107 /* and the binary free energy output */
1109 if (dhc_ && bDoDHDL)
1112 for (auto i : keysOf(fep->separate_dvdl))
1114 if (fep->separate_dvdl[i])
1116 /* assumes F_DVDL is first */
1117 store_dhdl[idhdl] = enerd->term[F_DVDL + static_cast<int>(i)];
1121 store_energy = enerd->term[F_ETOT];
1122 /* store_dh is dE */
1123 mde_delta_h_coll_add_dh(dhc_.get(),
1124 static_cast<double>(fep_state),
1128 dE_.data() + fep->lambda_start_n,
1133 if (conservedEnergyTracker_)
1135 conservedEnergyTracker_->addPoint(
1136 time, bEner_[F_ECONSERVED] ? enerd->term[F_ECONSERVED] : enerd->term[F_ETOT]);
1140 void EnergyOutput::recordNonEnergyStep()
1142 ebin_increase_count(1, ebin_, false);
1145 void EnergyOutput::printHeader(FILE* log, int64_t steps, double time)
1154 gmx_step_str(steps, buf),
1158 void EnergyOutput::printStepToEnergyFile(ener_file* fp_ene,
1172 fr.nsteps = ebin_->nsteps;
1174 fr.nsum = ebin_->nsum;
1175 fr.nre = (bEne) ? ebin_->nener : 0;
1177 int ndisre = bDR ? fcd->disres->npair : 0;
1178 /* these are for the old-style blocks (1 subblock, only reals), because
1179 there can be only one per ID for these */
1183 /* Optional additional old-style (real-only) blocks. */
1184 for (int i = 0; i < enxNR; i++)
1189 if (bOR && fcd->orires->nr > 0)
1191 t_oriresdata& orires = *fcd->orires;
1192 diagonalize_orires_tensors(&orires);
1193 nr[enxOR] = orires.nr;
1194 block[enxOR] = orires.otav;
1196 nr[enxORI] = (orires.oinsl != orires.otav) ? orires.nr : 0;
1197 block[enxORI] = orires.oinsl;
1198 id[enxORI] = enxORI;
1199 nr[enxORT] = orires.nex * 12;
1200 block[enxORT] = orires.eig;
1201 id[enxORT] = enxORT;
1204 /* whether we are going to write anything out: */
1205 if (fr.nre || ndisre || nr[enxOR] || nr[enxORI])
1207 /* the old-style blocks go first */
1209 for (int i = 0; i < enxNR; i++)
1216 add_blocks_enxframe(&fr, fr.nblock);
1217 for (int b = 0; b < fr.nblock; b++)
1219 add_subblocks_enxblock(&(fr.block[b]), 1);
1220 fr.block[b].id = id[b];
1221 fr.block[b].sub[0].nr = nr[b];
1223 fr.block[b].sub[0].type = XdrDataType::Float;
1224 fr.block[b].sub[0].fval = block[b];
1226 fr.block[b].sub[0].type = XdrDataType::Double;
1227 fr.block[b].sub[0].dval = block[b];
1231 /* check for disre block & fill it. */
1236 add_blocks_enxframe(&fr, fr.nblock);
1238 add_subblocks_enxblock(&(fr.block[db]), 2);
1239 const t_disresdata& disres = *fcd->disres;
1240 fr.block[db].id = enxDISRE;
1241 fr.block[db].sub[0].nr = ndisre;
1242 fr.block[db].sub[1].nr = ndisre;
1244 fr.block[db].sub[0].type = XdrDataType::Float;
1245 fr.block[db].sub[1].type = XdrDataType::Float;
1246 fr.block[db].sub[0].fval = disres.rt;
1247 fr.block[db].sub[1].fval = disres.rm3tav;
1249 fr.block[db].sub[0].type = XdrDataType::Double;
1250 fr.block[db].sub[1].type = XdrDataType::Double;
1251 fr.block[db].sub[0].dval = disres.rt;
1252 fr.block[db].sub[1].dval = disres.rm3tav;
1255 /* here we can put new-style blocks */
1257 /* Free energy perturbation blocks */
1260 mde_delta_h_coll_handle_block(dhc_.get(), &fr, fr.nblock);
1263 /* we can now free & reset the data in the blocks */
1266 mde_delta_h_coll_reset(dhc_.get());
1269 /* AWH bias blocks. */
1270 if (awh != nullptr) // TODO: add boolean flag.
1272 awh->writeToEnergyFrame(step, &fr);
1275 /* do the actual I/O */
1276 do_enx(fp_ene, &fr);
1279 /* We have stored the sums, so reset the sum history */
1280 reset_ebin_sums(ebin_);
1286 if (bOR && fcd->orires->nr > 0)
1288 print_orires_log(log, fcd->orires);
1291 fprintf(log, " Energies (%s)\n", unit_energy);
1292 pr_ebin(log, ebin_, ie_, f_nre_ + nCrmsd_, 5, eprNORMAL, true);
1297 void EnergyOutput::printAnnealingTemperatures(FILE* log, const SimulationGroups* groups, const t_grpopts* opts)
1303 for (int i = 0; i < opts->ngtc; i++)
1305 if (opts->annealing[i] != SimulatedAnnealing::No)
1308 "Current ref_t for group %s: %8.1f\n",
1309 *(groups->groupNames[groups->groups[SimulationAtomGroupType::TemperatureCoupling][i]]),
1318 void EnergyOutput::printAverages(FILE* log, const SimulationGroups* groups)
1320 if (ebin_->nsum_sim <= 0)
1324 fprintf(log, "Not enough data recorded to report energy averages\n");
1331 char buf1[22], buf2[22];
1333 fprintf(log, "\t<====== ############### ==>\n");
1334 fprintf(log, "\t<==== A V E R A G E S ====>\n");
1335 fprintf(log, "\t<== ############### ======>\n\n");
1338 "\tStatistics over %s steps using %s frames\n",
1339 gmx_step_str(ebin_->nsteps_sim, buf1),
1340 gmx_step_str(ebin_->nsum_sim, buf2));
1343 fprintf(log, " Energies (%s)\n", unit_energy);
1344 pr_ebin(log, ebin_, ie_, f_nre_ + nCrmsd_, 5, eprAVER, true);
1349 pr_ebin(log, ebin_, ib_, bTricl_ ? tricl_boxs_nm.size() : boxs_nm.size(), 5, eprAVER, true);
1354 fprintf(log, " Constraint Virial (%s)\n", unit_energy);
1355 pr_ebin(log, ebin_, isvir_, 9, 3, eprAVER, false);
1357 fprintf(log, " Force Virial (%s)\n", unit_energy);
1358 pr_ebin(log, ebin_, ifvir_, 9, 3, eprAVER, false);
1363 fprintf(log, " Total Virial (%s)\n", unit_energy);
1364 pr_ebin(log, ebin_, ivir_, 9, 3, eprAVER, false);
1366 fprintf(log, " Pressure (%s)\n", unit_pres_bar);
1367 pr_ebin(log, ebin_, ipres_, 9, 3, eprAVER, false);
1372 fprintf(log, " Total Dipole (%s)\n", unit_dipole_D);
1373 pr_ebin(log, ebin_, imu_, 3, 3, eprAVER, false);
1379 int padding = 8 - strlen(unit_energy);
1380 fprintf(log, "%*sEpot (%s) ", padding, "", unit_energy);
1381 for (auto key : keysOf(bEInd_))
1385 fprintf(log, "%12s ", enumValueToString(key));
1391 for (int i = 0; (i < nEg_); i++)
1393 int ni = groups->groups[SimulationAtomGroupType::EnergyOutput][i];
1394 for (int j = i; (j < nEg_); j++)
1396 int nj = groups->groups[SimulationAtomGroupType::EnergyOutput][j];
1398 14 - (strlen(*(groups->groupNames[ni])) + strlen(*(groups->groupNames[nj])));
1399 fprintf(log, "%*s%s-%s", padding, "", *(groups->groupNames[ni]), *(groups->groupNames[nj]));
1400 pr_ebin(log, ebin_, igrp_[n], nEc_, nEc_, eprAVER, false);
1408 pr_ebin(log, ebin_, itemp_, nTC_, 4, eprAVER, true);
1414 void EnergyOutput::fillEnergyHistory(energyhistory_t* enerhist) const
1416 const t_ebin* const ebin = ebin_;
1418 enerhist->nsteps = ebin->nsteps;
1419 enerhist->nsum = ebin->nsum;
1420 enerhist->nsteps_sim = ebin->nsteps_sim;
1421 enerhist->nsum_sim = ebin->nsum_sim;
1425 /* This will only actually resize the first time */
1426 enerhist->ener_ave.resize(ebin->nener);
1427 enerhist->ener_sum.resize(ebin->nener);
1429 for (int i = 0; i < ebin->nener; i++)
1431 enerhist->ener_ave[i] = ebin->e[i].eav;
1432 enerhist->ener_sum[i] = ebin->e[i].esum;
1436 if (ebin->nsum_sim > 0)
1438 /* This will only actually resize the first time */
1439 enerhist->ener_sum_sim.resize(ebin->nener);
1441 for (int i = 0; i < ebin->nener; i++)
1443 enerhist->ener_sum_sim[i] = ebin->e_sim[i].esum;
1448 mde_delta_h_coll_update_energyhistory(dhc_.get(), enerhist);
1452 void EnergyOutput::restoreFromEnergyHistory(const energyhistory_t& enerhist)
1454 unsigned int nener = static_cast<unsigned int>(ebin_->nener);
1456 if ((enerhist.nsum > 0 && nener != enerhist.ener_sum.size())
1457 || (enerhist.nsum_sim > 0 && nener != enerhist.ener_sum_sim.size()))
1460 "Mismatch between number of energies in run input (%u) and checkpoint file (%zu "
1463 enerhist.ener_sum.size(),
1464 enerhist.ener_sum_sim.size());
1467 ebin_->nsteps = enerhist.nsteps;
1468 ebin_->nsum = enerhist.nsum;
1469 ebin_->nsteps_sim = enerhist.nsteps_sim;
1470 ebin_->nsum_sim = enerhist.nsum_sim;
1472 for (int i = 0; i < ebin_->nener; i++)
1474 ebin_->e[i].eav = (enerhist.nsum > 0 ? enerhist.ener_ave[i] : 0);
1475 ebin_->e[i].esum = (enerhist.nsum > 0 ? enerhist.ener_sum[i] : 0);
1476 ebin_->e_sim[i].esum = (enerhist.nsum_sim > 0 ? enerhist.ener_sum_sim[i] : 0);
1480 mde_delta_h_coll_restore_energyhistory(dhc_.get(), enerhist.deltaHForeignLambdas.get());
1484 int EnergyOutput::numEnergyTerms() const
1486 return ebin_->nener;
1489 void EnergyOutput::printEnergyConservation(FILE* fplog, int simulationPart, bool usingMdIntegrator) const
1491 if (fplog == nullptr)
1496 if (conservedEnergyTracker_)
1498 std::string partName = formatString("simulation part #%d", simulationPart);
1499 fprintf(fplog, "\n%s\n", conservedEnergyTracker_->energyDriftString(partName).c_str());
1501 else if (usingMdIntegrator)
1504 "\nCannot report drift of the conserved energy quantity because simulations share "