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,2018,2019, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
38 * \brief Defines code that writes energy-like quantities.
40 * \author Mark Abraham <mark.j.abraham@gmail.com>
41 * \author Paul Bauer <paul.bauer.q@gmail.com>
42 * \author Artem Zhmurov <zhmurov@gmail.com>
44 * \ingroup module_mdlib
48 #include "energyoutput.h"
57 #include "gromacs/awh/awh.h"
58 #include "gromacs/fileio/enxio.h"
59 #include "gromacs/fileio/gmxfio.h"
60 #include "gromacs/fileio/xvgr.h"
61 #include "gromacs/gmxlib/network.h"
62 #include "gromacs/listed_forces/disre.h"
63 #include "gromacs/listed_forces/orires.h"
64 #include "gromacs/math/functions.h"
65 #include "gromacs/math/units.h"
66 #include "gromacs/math/vec.h"
67 #include "gromacs/mdlib/constr.h"
68 #include "gromacs/mdlib/ebin.h"
69 #include "gromacs/mdlib/mdebin_bar.h"
70 #include "gromacs/mdtypes/energyhistory.h"
71 #include "gromacs/mdtypes/fcdata.h"
72 #include "gromacs/mdtypes/group.h"
73 #include "gromacs/mdtypes/inputrec.h"
74 #include "gromacs/mdtypes/md_enums.h"
75 #include "gromacs/mdtypes/state.h"
76 #include "gromacs/pbcutil/pbc.h"
77 #include "gromacs/pulling/pull.h"
78 #include "gromacs/topology/mtop_util.h"
79 #include "gromacs/trajectory/energyframe.h"
80 #include "gromacs/utility/arraysize.h"
81 #include "gromacs/utility/fatalerror.h"
82 #include "gromacs/utility/smalloc.h"
83 #include "gromacs/utility/stringutil.h"
85 //! Labels for energy file quantities
87 static const char *conrmsd_nm[] = { "Constr. rmsd", "Constr.2 rmsd" };
89 static std::array<const char *, 3> boxs_nm = { "Box-X", "Box-Y", "Box-Z" };
91 static std::array<const char *, 6> tricl_boxs_nm = {
92 "Box-XX", "Box-YY", "Box-ZZ",
93 "Box-YX", "Box-ZX", "Box-ZY"
96 static const char *vol_nm[] = { "Volume" };
98 static const char *dens_nm[] = {"Density" };
100 static const char *pv_nm[] = {"pV" };
102 static const char *enthalpy_nm[] = {"Enthalpy" };
104 static std::array<const char *, 6> boxvel_nm = {
105 "Box-Vel-XX", "Box-Vel-YY", "Box-Vel-ZZ",
106 "Box-Vel-YX", "Box-Vel-ZX", "Box-Vel-ZY"
109 const char *egrp_nm[egNR+1] = {
110 "Coul-SR", "LJ-SR", "Buck-SR",
111 "Coul-14", "LJ-14", nullptr
118 /*! \brief Energy output class
120 * This is the collection of energy averages collected during mdrun, and to
121 * be written out to the .edr file.
123 * \todo Use more std containers.
124 * \todo Remove GMX_CONSTRAINTVIR
125 * \todo Write free-energy output also to energy file (after adding more tests)
127 EnergyOutput::EnergyOutput(ener_file *fp_ene,
128 const gmx_mtop_t *mtop,
129 const t_inputrec *ir,
130 const pull_t *pull_work,
134 const char *ener_nm[F_NRE];
135 static const char *vir_nm[] = {
136 "Vir-XX", "Vir-XY", "Vir-XZ",
137 "Vir-YX", "Vir-YY", "Vir-YZ",
138 "Vir-ZX", "Vir-ZY", "Vir-ZZ"
140 static const char *sv_nm[] = {
141 "ShakeVir-XX", "ShakeVir-XY", "ShakeVir-XZ",
142 "ShakeVir-YX", "ShakeVir-YY", "ShakeVir-YZ",
143 "ShakeVir-ZX", "ShakeVir-ZY", "ShakeVir-ZZ"
145 static const char *fv_nm[] = {
146 "ForceVir-XX", "ForceVir-XY", "ForceVir-XZ",
147 "ForceVir-YX", "ForceVir-YY", "ForceVir-YZ",
148 "ForceVir-ZX", "ForceVir-ZY", "ForceVir-ZZ"
150 static const char *pres_nm[] = {
151 "Pres-XX", "Pres-XY", "Pres-XZ",
152 "Pres-YX", "Pres-YY", "Pres-YZ",
153 "Pres-ZX", "Pres-ZY", "Pres-ZZ"
155 static const char *surft_nm[] = {
158 static const char *mu_nm[] = {
159 "Mu-X", "Mu-Y", "Mu-Z"
161 static const char *vcos_nm[] = {
164 static const char *visc_nm[] = {
167 static const char *baro_nm[] = {
171 const SimulationGroups *groups;
175 int i, j, ni, nj, n, k, kk, ncon, nset;
178 if (EI_DYNAMICS(ir->eI))
180 delta_t_ = ir->delta_t;
187 groups = &mtop->groups;
189 bBHAM = (mtop->ffparams.numTypes() > 0) && (mtop->ffparams.functype[0] == F_BHAM);
190 b14 = (gmx_mtop_ftype_count(mtop, F_LJ14) > 0 ||
191 gmx_mtop_ftype_count(mtop, F_LJC14_Q) > 0);
193 ncon = gmx_mtop_ftype_count(mtop, F_CONSTR);
194 nset = gmx_mtop_ftype_count(mtop, F_SETTLE);
195 bool bConstr = (ncon > 0 || nset > 0) && !isRerun;
200 if (ncon > 0 && ir->eConstrAlg == econtLINCS)
204 bConstrVir_ = (getenv("GMX_CONSTRAINTVIR") != nullptr);
211 /* Energy monitoring */
212 for (i = 0; i < egNR; i++)
217 // Setting true only to those energy terms, that have active interactions and
218 // are not vsite terms (not VSITE2, VSITE3, VSITE3FD, VSITE3FAD, VSITE3OUT, VSITE4FD, VSITE4FDN, or VSITEN)
219 for (i = 0; i < F_NRE; i++)
221 bEner_[i] = (gmx_mtop_ftype_count(mtop, i) > 0) &&
222 ((interaction_function[i].flags & IF_VSITE) == 0);
227 bEner_[F_EKIN] = EI_DYNAMICS(ir->eI);
228 bEner_[F_ETOT] = EI_DYNAMICS(ir->eI);
229 bEner_[F_TEMP] = EI_DYNAMICS(ir->eI);
231 bEner_[F_ECONSERVED] = integratorHasConservedEnergyQuantity(ir);
232 bEner_[F_PDISPCORR] = (ir->eDispCorr != edispcNO);
233 bEner_[F_PRES] = true;
236 bEner_[F_LJ] = !bBHAM;
237 bEner_[F_BHAM] = bBHAM;
238 bEner_[F_EQM] = ir->bQMMM;
239 bEner_[F_RF_EXCL] = (EEL_RF(ir->coulombtype) && ir->cutoff_scheme == ecutsGROUP);
240 bEner_[F_COUL_RECIP] = EEL_FULL(ir->coulombtype);
241 bEner_[F_LJ_RECIP] = EVDW_PME(ir->vdwtype);
242 bEner_[F_LJ14] = b14;
243 bEner_[F_COUL14] = b14;
244 bEner_[F_LJC14_Q] = false;
245 bEner_[F_LJC_PAIRS_NB] = false;
248 bEner_[F_DVDL_COUL] = (ir->efep != efepNO) && ir->fepvals->separate_dvdl[efptCOUL];
249 bEner_[F_DVDL_VDW] = (ir->efep != efepNO) && ir->fepvals->separate_dvdl[efptVDW];
250 bEner_[F_DVDL_BONDED] = (ir->efep != efepNO) && ir->fepvals->separate_dvdl[efptBONDED];
251 bEner_[F_DVDL_RESTRAINT] = (ir->efep != efepNO) && ir->fepvals->separate_dvdl[efptRESTRAINT];
252 bEner_[F_DKDL] = (ir->efep != efepNO) && ir->fepvals->separate_dvdl[efptMASS];
253 bEner_[F_DVDL] = (ir->efep != efepNO) && ir->fepvals->separate_dvdl[efptFEP];
255 bEner_[F_CONSTR] = false;
256 bEner_[F_CONSTRNC] = false;
257 bEner_[F_SETTLE] = false;
259 bEner_[F_COUL_SR] = true;
260 bEner_[F_EPOT] = true;
262 bEner_[F_DISPCORR] = (ir->eDispCorr != edispcNO);
263 bEner_[F_DISRESVIOL] = (gmx_mtop_ftype_count(mtop, F_DISRES) > 0);
264 bEner_[F_ORIRESDEV] = (gmx_mtop_ftype_count(mtop, F_ORIRES) > 0);
265 bEner_[F_COM_PULL] = ((ir->bPull && pull_have_potential(pull_work)) || ir->bRot);
267 // Counting the energy terms that will be printed and saving their names
269 for (i = 0; i < F_NRE; i++)
273 ener_nm[f_nre_] = interaction_function[i].longname;
278 epc_ = isRerun ? epcNO : ir->epc;
279 bDiagPres_ = !TRICLINIC(ir->ref_p) && !isRerun;
280 ref_p_ = (ir->ref_p[XX][XX]+ir->ref_p[YY][YY]+ir->ref_p[ZZ][ZZ])/DIM;
281 bTricl_ = TRICLINIC(ir->compress) || TRICLINIC(ir->deform);
282 bDynBox_ = inputrecDynamicBox(ir);
283 etc_ = isRerun ? etcNO : ir->etc;
284 bNHC_trotter_ = inputrecNvtTrotter(ir) && !isRerun;
285 bPrintNHChains_ = ir->bPrintNHChains && !isRerun;
286 bMTTK_ = (inputrecNptTrotter(ir) || inputrecNphTrotter(ir)) && !isRerun;
287 bMu_ = inputrecNeedMutot(ir);
291 /* Pass NULL for unit to let get_ebin_space determine the units
292 * for interaction_function[i].longname
294 ie_ = get_ebin_space(ebin_, f_nre_, ener_nm, nullptr);
297 /* This should be called directly after the call for ie_,
298 * such that iconrmsd_ follows directly in the list.
300 iconrmsd_ = get_ebin_space(ebin_, nCrmsd_, conrmsd_nm, "");
304 ib_ = get_ebin_space(ebin_,
305 bTricl_ ? tricl_boxs_nm.size() : boxs_nm.size(),
306 bTricl_ ? tricl_boxs_nm.data() : boxs_nm.data(),
308 ivol_ = get_ebin_space(ebin_, 1, vol_nm, unit_volume);
309 idens_ = get_ebin_space(ebin_, 1, dens_nm, unit_density_SI);
312 ipv_ = get_ebin_space(ebin_, 1, pv_nm, unit_energy);
313 ienthalpy_ = get_ebin_space(ebin_, 1, enthalpy_nm, unit_energy);
318 isvir_ = get_ebin_space(ebin_, asize(sv_nm), sv_nm, unit_energy);
319 ifvir_ = get_ebin_space(ebin_, asize(fv_nm), fv_nm, unit_energy);
323 ivir_ = get_ebin_space(ebin_, asize(vir_nm), vir_nm, unit_energy);
324 ipres_ = get_ebin_space(ebin_, asize(pres_nm), pres_nm, unit_pres_bar);
325 isurft_ = get_ebin_space(ebin_, asize(surft_nm), surft_nm,
328 if (epc_ == epcPARRINELLORAHMAN || epc_ == epcMTTK)
330 ipc_ = get_ebin_space(ebin_, bTricl_ ? boxvel_nm.size() : DIM,
331 boxvel_nm.data(), unit_vel);
335 imu_ = get_ebin_space(ebin_, asize(mu_nm), mu_nm, unit_dipole_D);
337 if (ir->cos_accel != 0)
339 ivcos_ = get_ebin_space(ebin_, asize(vcos_nm), vcos_nm, unit_vel);
340 ivisc_ = get_ebin_space(ebin_, asize(visc_nm), visc_nm,
344 /* Energy monitoring */
345 for (i = 0; i < egNR; i++)
349 bEInd_[egCOULSR] = true;
350 bEInd_[egLJSR ] = true;
354 bEInd_[egLJSR] = false;
355 bEInd_[egBHAMSR] = true;
359 bEInd_[egLJ14] = true;
360 bEInd_[egCOUL14] = true;
363 for (i = 0; (i < egNR); i++)
370 n = groups->groups[SimulationAtomGroupType::EnergyOutput].size();
379 for (k = 0; (k < nEc_); k++)
381 snew(gnm[k], STRLEN);
383 for (i = 0; (i < gmx::ssize(groups->groups[SimulationAtomGroupType::EnergyOutput])); i++)
385 ni = groups->groups[SimulationAtomGroupType::EnergyOutput][i];
386 for (j = i; (j < gmx::ssize(groups->groups[SimulationAtomGroupType::EnergyOutput])); j++)
388 nj = groups->groups[SimulationAtomGroupType::EnergyOutput][j];
389 for (k = kk = 0; (k < egNR); k++)
393 sprintf(gnm[kk], "%s:%s-%s", egrp_nm[k],
394 *(groups->groupNames[ni]), *(groups->groupNames[nj]));
398 igrp_[n] = get_ebin_space(ebin_, nEc_,
403 for (k = 0; (k < nEc_); k++)
411 gmx_incons("Number of energy terms wrong");
415 nTC_ = isRerun ? 0 : groups->groups[SimulationAtomGroupType::TemperatureCoupling].size();
416 nNHC_ = ir->opts.nhchainlength; /* shorthand for number of NH chains */
419 nTCP_ = 1; /* assume only one possible coupling system for barostat
426 if (etc_ == etcNOSEHOOVER)
430 mde_n_ = 2*nNHC_*nTC_;
438 mdeb_n_ = 2*nNHC_*nTCP_;
447 snew(tmp_r_, mde_n_);
448 // TODO redo the group name memory management to make it more clear
450 snew(grpnms, std::max(mde_n_, mdeb_n_)); // Just in case mdeb_n_ > mde_n_
452 for (i = 0; (i < nTC_); i++)
454 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
455 sprintf(buf, "T-%s", *(groups->groupNames[ni]));
456 grpnms[i] = gmx_strdup(buf);
458 itemp_ = get_ebin_space(ebin_, nTC_, grpnms,
460 for (i = 0; i < nTC_; i++)
466 if (etc_ == etcNOSEHOOVER)
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_,
485 grpnms, unit_invtime);
489 for (i = 0; (i < nTCP_); i++)
491 bufi = baro_nm[0]; /* All barostat DOF's together for now. */
492 for (j = 0; (j < nNHC_); j++)
494 sprintf(buf, "Xi-%d-%s", j, bufi);
495 grpnms[2*(i*nNHC_+j)] = gmx_strdup(buf);
496 sprintf(buf, "vXi-%d-%s", j, bufi);
497 grpnms[2*(i*nNHC_+j)+1] = gmx_strdup(buf);
500 itcb_ = get_ebin_space(ebin_, mdeb_n_,
501 grpnms, unit_invtime);
507 for (i = 0; (i < nTC_); i++)
509 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
510 bufi = *(groups->groupNames[ni]);
511 sprintf(buf, "Xi-%s", bufi);
512 grpnms[2*i] = gmx_strdup(buf);
513 sprintf(buf, "vXi-%s", bufi);
514 grpnms[2*i+1] = gmx_strdup(buf);
516 itc_ = get_ebin_space(ebin_, mde_n_,
517 grpnms, unit_invtime);
522 else if (etc_ == etcBERENDSEN || etc_ == etcYES ||
525 for (i = 0; (i < nTC_); i++)
527 ni = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i];
528 sprintf(buf, "Lamb-%s", *(groups->groupNames[ni]));
529 grpnms[i] = gmx_strdup(buf);
531 itc_ = get_ebin_space(ebin_, mde_n_, grpnms, "");
535 for (i = 0; i < allocated; i++)
541 nU_ = groups->groups[SimulationAtomGroupType::Acceleration].size();
546 for (i = 0; (i < nU_); i++)
548 ni = groups->groups[SimulationAtomGroupType::Acceleration][i];
549 sprintf(buf, "Ux-%s", *(groups->groupNames[ni]));
550 grpnms[3*i+XX] = gmx_strdup(buf);
551 sprintf(buf, "Uy-%s", *(groups->groupNames[ni]));
552 grpnms[3*i+YY] = gmx_strdup(buf);
553 sprintf(buf, "Uz-%s", *(groups->groupNames[ni]));
554 grpnms[3*i+ZZ] = gmx_strdup(buf);
556 iu_ = get_ebin_space(ebin_, 3*nU_, grpnms, unit_vel);
557 for (i = 0; i < 3*nU_; i++)
566 do_enxnms(fp_ene, &ebin_->nener, &ebin_->enm);
569 /* check whether we're going to write dh histograms */
571 if (ir->fepvals->separate_dhdl_file == esepdhdlfileNO)
573 /* Currently dh histograms are only written with dynamics */
574 if (EI_DYNAMICS(ir->eI))
578 mde_delta_h_coll_init(dhc_, ir);
581 snew(dE_, ir->fepvals->n_lambda);
586 snew(dE_, ir->fepvals->n_lambda);
591 snew(temperatures_, ir->fepvals->n_lambda);
592 numTemperatures_ = ir->fepvals->n_lambda;
593 for (i = 0; i < ir->fepvals->n_lambda; i++)
595 temperatures_[i] = ir->simtempvals->temperatures[i];
600 numTemperatures_ = 0;
605 EnergyOutput::~EnergyOutput()
611 done_mde_delta_h_coll(dhc_);
613 if (numTemperatures_ > 0)
615 sfree(temperatures_);
621 /*! \brief Print a lambda vector to a string
623 * \param[in] fep The inputrec's FEP input data
624 * \param[in] i The index of the lambda vector
625 * \param[in] get_native_lambda Whether to print the native lambda
626 * \param[in] get_names Whether to print the names rather than the values
627 * \param[in,out] str The pre-allocated string buffer to print to.
629 static void print_lambda_vector(t_lambda *fep, int i,
630 bool get_native_lambda, bool get_names,
636 for (j = 0; j < efptNR; j++)
638 if (fep->separate_dvdl[j])
643 str[0] = 0; /* reset the string */
646 str += sprintf(str, "("); /* set the opening parenthesis*/
648 for (j = 0; j < efptNR; j++)
650 if (fep->separate_dvdl[j])
654 if (get_native_lambda && fep->init_lambda >= 0)
656 str += sprintf(str, "%.4f", fep->init_lambda);
660 str += sprintf(str, "%.4f", fep->all_lambda[j][i]);
665 str += sprintf(str, "%s", efpt_singular_names[j]);
667 /* print comma for the next item */
670 str += sprintf(str, ", ");
677 /* and add the closing parenthesis */
682 FILE *open_dhdl(const char *filename, const t_inputrec *ir,
683 const gmx_output_env_t *oenv)
686 const char *dhdl = "dH/d\\lambda", *deltag = "\\DeltaH", *lambda = "\\lambda",
687 *lambdastate = "\\lambda state";
688 int i, nsets, nsets_de, nsetsbegin;
689 int n_lambda_terms = 0;
690 t_lambda *fep = ir->fepvals; /* for simplicity */
691 t_expanded *expand = ir->expandedvals;
692 char lambda_vec_str[STRLEN], lambda_name_str[STRLEN];
697 bool write_pV = false;
699 /* count the number of different lambda terms */
700 for (i = 0; i < efptNR; i++)
702 if (fep->separate_dvdl[i])
708 std::string title, label_x, label_y;
709 if (fep->n_lambda == 0)
711 title = gmx::formatString("%s", dhdl);
712 label_x = gmx::formatString("Time (ps)");
713 label_y = gmx::formatString("%s (%s %s)",
714 dhdl, unit_energy, "[\\lambda]\\S-1\\N");
718 title = gmx::formatString("%s and %s", dhdl, deltag);
719 label_x = gmx::formatString("Time (ps)");
720 label_y = gmx::formatString("%s and %s (%s %s)",
721 dhdl, deltag, unit_energy, "[\\8l\\4]\\S-1\\N");
723 fp = gmx_fio_fopen(filename, "w+");
724 xvgr_header(fp, title.c_str(), label_x, label_y, exvggtXNY, oenv);
729 buf = gmx::formatString("T = %g (K) ", ir->opts.ref_t[0]);
731 if ((ir->efep != efepSLOWGROWTH) && (ir->efep != efepEXPANDED))
733 if ( (fep->init_lambda >= 0) && (n_lambda_terms == 1 ))
735 /* compatibility output */
736 buf += gmx::formatString("%s = %.4f", lambda, fep->init_lambda);
740 print_lambda_vector(fep, fep->init_fep_state, true, false,
742 print_lambda_vector(fep, fep->init_fep_state, true, true,
744 buf += gmx::formatString("%s %d: %s = %s",
745 lambdastate, fep->init_fep_state,
746 lambda_name_str, lambda_vec_str);
749 xvgr_subtitle(fp, buf.c_str(), oenv);
753 if (fep->dhdl_derivatives == edhdlderivativesYES)
755 nsets_dhdl = n_lambda_terms;
757 /* count the number of delta_g states */
758 nsets_de = fep->lambda_stop_n - fep->lambda_start_n;
760 nsets = nsets_dhdl + nsets_de; /* dhdl + fep differences */
762 if (fep->n_lambda > 0 && (expand->elmcmove > elmcmoveNO))
764 nsets += 1; /*add fep state for expanded ensemble */
767 if (fep->edHdLPrintEnergy != edHdLPrintEnergyNO)
769 nsets += 1; /* add energy to the dhdl as well */
773 if ((ir->epc != epcNO) && (fep->n_lambda > 0) && (fep->init_lambda < 0))
775 nsetsextend += 1; /* for PV term, other terms possible if required for
776 the reduced potential (only needed with foreign
777 lambda, and only output when init_lambda is not
778 set in order to maintain compatibility of the
782 std::vector<std::string> setname(nsetsextend);
784 if (expand->elmcmove > elmcmoveNO)
786 /* state for the fep_vals, if we have alchemical sampling */
787 setname[s++] = "Thermodynamic state";
790 if (fep->edHdLPrintEnergy != edHdLPrintEnergyNO)
793 switch (fep->edHdLPrintEnergy)
795 case edHdLPrintEnergyPOTENTIAL:
796 energy = gmx::formatString("%s (%s)", "Potential Energy", unit_energy);
798 case edHdLPrintEnergyTOTAL:
799 case edHdLPrintEnergyYES:
801 energy = gmx::formatString("%s (%s)", "Total Energy", unit_energy);
803 setname[s++] = energy;
806 if (fep->dhdl_derivatives == edhdlderivativesYES)
808 for (i = 0; i < efptNR; i++)
810 if (fep->separate_dvdl[i])
812 std::string derivative;
813 if ( (fep->init_lambda >= 0) && (n_lambda_terms == 1 ))
815 /* compatibility output */
816 derivative = gmx::formatString("%s %s %.4f", dhdl, lambda, fep->init_lambda);
820 double lam = fep->init_lambda;
821 if (fep->init_lambda < 0)
823 lam = fep->all_lambda[i][fep->init_fep_state];
825 derivative = gmx::formatString("%s %s = %.4f", dhdl, efpt_singular_names[i],
828 setname[s++] = derivative;
833 if (fep->n_lambda > 0)
835 /* g_bar has to determine the lambda values used in this simulation
836 * from this xvg legend.
839 if (expand->elmcmove > elmcmoveNO)
841 nsetsbegin = 1; /* for including the expanded ensemble */
848 if (fep->edHdLPrintEnergy != edHdLPrintEnergyNO)
852 nsetsbegin += nsets_dhdl;
854 for (i = fep->lambda_start_n; i < fep->lambda_stop_n; i++)
856 print_lambda_vector(fep, i, false, false, lambda_vec_str);
858 if ( (fep->init_lambda >= 0) && (n_lambda_terms == 1 ))
860 /* for compatible dhdl.xvg files */
861 buf = gmx::formatString("%s %s %s", deltag, lambda, lambda_vec_str);
865 buf = gmx::formatString("%s %s to %s", deltag, lambda, lambda_vec_str);
870 /* print the temperature for this state if doing simulated annealing */
871 buf += gmx::formatString("T = %g (%s)",
872 ir->simtempvals->temperatures[s-(nsetsbegin)],
879 setname[s++] = gmx::formatString("pV (%s)", unit_energy);
882 xvgrLegend(fp, setname, oenv);
891 void EnergyOutput::addDataAtEnergyStep(bool bDoDHDL,
895 gmx_enerdata_t *enerd,
904 gmx_ekindata_t *ekind,
906 const gmx::Constraints *constr)
908 int j, k, kk, n, gid;
909 real crmsd[2], tmp6[6];
910 real bs[tricl_boxs_nm.size()], vol, dens, pv, enthalpy;
912 double store_dhdl[efptNR];
913 real store_energy = 0;
916 /* Do NOT use the box in the state variable, but the separate box provided
917 * as an argument. This is because we sometimes need to write the box from
918 * the last timestep to match the trajectory frames.
920 add_ebin_indexed(ebin_, ie_, gmx::ArrayRef<bool>(bEner_), enerd->term, bSum);
923 crmsd[0] = constr->rmsd();
924 add_ebin(ebin_, iconrmsd_, nCrmsd_, crmsd, false);
937 nboxs = tricl_boxs_nm.size();
944 nboxs = boxs_nm.size();
946 vol = box[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
947 dens = (tmass*AMU)/(vol*NANO*NANO*NANO);
948 add_ebin(ebin_, ib_, nboxs, bs, bSum);
949 add_ebin(ebin_, ivol_, 1, &vol, bSum);
950 add_ebin(ebin_, idens_, 1, &dens, bSum);
954 /* This is pV (in kJ/mol). The pressure is the reference pressure,
955 not the instantaneous pressure */
956 pv = vol*ref_p_/PRESFAC;
958 add_ebin(ebin_, ipv_, 1, &pv, bSum);
959 enthalpy = pv + enerd->term[F_ETOT];
960 add_ebin(ebin_, ienthalpy_, 1, &enthalpy, bSum);
965 add_ebin(ebin_, isvir_, 9, svir[0], bSum);
966 add_ebin(ebin_, ifvir_, 9, fvir[0], bSum);
970 add_ebin(ebin_, ivir_, 9, vir[0], bSum);
971 add_ebin(ebin_, ipres_, 9, pres[0], bSum);
972 tmp = (pres[ZZ][ZZ]-(pres[XX][XX]+pres[YY][YY])*0.5)*box[ZZ][ZZ];
973 add_ebin(ebin_, isurft_, 1, &tmp, bSum);
975 if (epc_ == epcPARRINELLORAHMAN || epc_ == epcMTTK)
977 tmp6[0] = state->boxv[XX][XX];
978 tmp6[1] = state->boxv[YY][YY];
979 tmp6[2] = state->boxv[ZZ][ZZ];
980 tmp6[3] = state->boxv[YY][XX];
981 tmp6[4] = state->boxv[ZZ][XX];
982 tmp6[5] = state->boxv[ZZ][YY];
983 add_ebin(ebin_, ipc_, bTricl_ ? 6 : 3, tmp6, bSum);
987 add_ebin(ebin_, imu_, 3, mu_tot, bSum);
989 if (ekind && ekind->cosacc.cos_accel != 0)
991 vol = box[XX][XX]*box[YY][YY]*box[ZZ][ZZ];
992 dens = (tmass*AMU)/(vol*NANO*NANO*NANO);
993 add_ebin(ebin_, ivcos_, 1, &(ekind->cosacc.vcos), bSum);
994 /* 1/viscosity, unit 1/(kg m^-1 s^-1) */
995 tmp = 1/(ekind->cosacc.cos_accel/(ekind->cosacc.vcos*PICO)
996 *dens*gmx::square(box[ZZ][ZZ]*NANO/(2*M_PI)));
997 add_ebin(ebin_, ivisc_, 1, &tmp, bSum);
1002 for (int i = 0; (i < nEg_); i++)
1004 for (j = i; (j < nEg_); j++)
1006 gid = GID(i, j, nEg_);
1007 for (k = kk = 0; (k < egNR); k++)
1011 eee[kk++] = enerd->grpp.ener[k][gid];
1014 add_ebin(ebin_, igrp_[n], nEc_, eee, bSum);
1022 for (int i = 0; (i < nTC_); i++)
1024 tmp_r_[i] = ekind->tcstat[i].T;
1026 add_ebin(ebin_, itemp_, nTC_, tmp_r_, bSum);
1028 if (etc_ == etcNOSEHOOVER)
1030 /* whether to print Nose-Hoover chains: */
1031 if (bPrintNHChains_)
1035 for (int i = 0; (i < nTC_); i++)
1037 for (j = 0; j < nNHC_; j++)
1040 tmp_r_[2*k] = state->nosehoover_xi[k];
1041 tmp_r_[2*k+1] = state->nosehoover_vxi[k];
1044 add_ebin(ebin_, itc_, mde_n_, tmp_r_, bSum);
1048 for (int i = 0; (i < nTCP_); i++)
1050 for (j = 0; j < nNHC_; j++)
1053 tmp_r_[2*k] = state->nhpres_xi[k];
1054 tmp_r_[2*k+1] = state->nhpres_vxi[k];
1057 add_ebin(ebin_, itcb_, mdeb_n_, tmp_r_, bSum);
1062 for (int i = 0; (i < nTC_); i++)
1064 tmp_r_[2*i] = state->nosehoover_xi[i];
1065 tmp_r_[2*i+1] = state->nosehoover_vxi[i];
1067 add_ebin(ebin_, itc_, mde_n_, tmp_r_, bSum);
1071 else if (etc_ == etcBERENDSEN || etc_ == etcYES ||
1072 etc_ == etcVRESCALE)
1074 for (int i = 0; (i < nTC_); i++)
1076 tmp_r_[i] = ekind->tcstat[i].lambda;
1078 add_ebin(ebin_, itc_, nTC_, tmp_r_, bSum);
1082 if (ekind && nU_ > 1)
1084 for (int i = 0; (i < nU_); i++)
1086 copy_rvec(ekind->grpstat[i].u, tmp_v_[i]);
1088 add_ebin(ebin_, iu_, 3*nU_, tmp_v_[0], bSum);
1091 ebin_increase_count(1, ebin_, bSum);
1093 // BAR + thermodynamic integration values
1094 if ((fp_dhdl_ || dhc_) && bDoDHDL)
1096 for (gmx::index i = 0; i < static_cast<gmx::index>(enerd->enerpart_lambda.size()) - 1; i++)
1098 /* zero for simulated tempering */
1099 dE_[i] = enerd->enerpart_lambda[i+1]-enerd->enerpart_lambda[0];
1100 if (numTemperatures_ > 0)
1102 GMX_RELEASE_ASSERT(numTemperatures_ > state->fep_state, "Number of lambdas in state is bigger then in input record");
1103 GMX_RELEASE_ASSERT(numTemperatures_ >= static_cast<gmx::index>(enerd->enerpart_lambda.size()) - 1, "Number of lambdas in energy data is bigger then in input record");
1104 /* MRS: is this right, given the way we have defined the exchange probabilities? */
1105 /* is this even useful to have at all? */
1106 dE_[i] += (temperatures_[i]/
1107 temperatures_[state->fep_state]-1.0)*
1108 enerd->term[F_EKIN];
1114 fprintf(fp_dhdl_, "%.4f", time);
1115 /* the current free energy state */
1117 /* print the current state if we are doing expanded ensemble */
1118 if (expand->elmcmove > elmcmoveNO)
1120 fprintf(fp_dhdl_, " %4d", state->fep_state);
1122 /* total energy (for if the temperature changes */
1124 if (fep->edHdLPrintEnergy != edHdLPrintEnergyNO)
1126 switch (fep->edHdLPrintEnergy)
1128 case edHdLPrintEnergyPOTENTIAL:
1129 store_energy = enerd->term[F_EPOT];
1131 case edHdLPrintEnergyTOTAL:
1132 case edHdLPrintEnergyYES:
1134 store_energy = enerd->term[F_ETOT];
1136 fprintf(fp_dhdl_, " %#.8g", store_energy);
1139 if (fep->dhdl_derivatives == edhdlderivativesYES)
1141 for (int i = 0; i < efptNR; i++)
1143 if (fep->separate_dvdl[i])
1145 /* assumes F_DVDL is first */
1146 fprintf(fp_dhdl_, " %#.8g", enerd->term[F_DVDL+i]);
1150 for (int i = fep->lambda_start_n; i < fep->lambda_stop_n; i++)
1152 fprintf(fp_dhdl_, " %#.8g", dE_[i]);
1157 !enerd->enerpart_lambda.empty() &&
1158 (fep->init_lambda < 0))
1160 fprintf(fp_dhdl_, " %#.8g", pv); /* PV term only needed when
1161 there are alternate state
1162 lambda and we're not in
1163 compatibility mode */
1165 fprintf(fp_dhdl_, "\n");
1166 /* and the binary free energy output */
1168 if (dhc_ && bDoDHDL)
1171 for (int i = 0; i < efptNR; i++)
1173 if (fep->separate_dvdl[i])
1175 /* assumes F_DVDL is first */
1176 store_dhdl[idhdl] = enerd->term[F_DVDL+i];
1180 store_energy = enerd->term[F_ETOT];
1181 /* store_dh is dE */
1182 mde_delta_h_coll_add_dh(dhc_,
1183 static_cast<double>(state->fep_state),
1187 dE_ + fep->lambda_start_n,
1194 void EnergyOutput::recordNonEnergyStep()
1196 ebin_increase_count(1, ebin_, false);
1199 void EnergyOutput::printHeader(FILE *log, int64_t steps, double time)
1203 fprintf(log, " %12s %12s\n"
1205 "Step", "Time", gmx_step_str(steps, buf), time);
1208 void EnergyOutput::printStepToEnergyFile(ener_file *fp_ene, bool bEne, bool bDR, bool bOR,
1210 int64_t step, double time,
1218 fr.nsteps = ebin_->nsteps;
1220 fr.nsum = ebin_->nsum;
1221 fr.nre = (bEne) ? ebin_->nener : 0;
1223 int ndisre = bDR ? fcd->disres.npair : 0;
1224 /* these are for the old-style blocks (1 subblock, only reals), because
1225 there can be only one per ID for these */
1229 /* Optional additional old-style (real-only) blocks. */
1230 for (int i = 0; i < enxNR; i++)
1235 if (bOR && fcd->orires.nr > 0)
1237 diagonalize_orires_tensors(&(fcd->orires));
1238 nr[enxOR] = fcd->orires.nr;
1239 block[enxOR] = fcd->orires.otav;
1241 nr[enxORI] = (fcd->orires.oinsl != fcd->orires.otav) ?
1243 block[enxORI] = fcd->orires.oinsl;
1244 id[enxORI] = enxORI;
1245 nr[enxORT] = fcd->orires.nex*12;
1246 block[enxORT] = fcd->orires.eig;
1247 id[enxORT] = enxORT;
1250 /* whether we are going to write anything out: */
1251 if (fr.nre || ndisre || nr[enxOR] || nr[enxORI])
1253 /* the old-style blocks go first */
1255 for (int i = 0; i < enxNR; i++)
1262 add_blocks_enxframe(&fr, fr.nblock);
1263 for (int b = 0; b < fr.nblock; b++)
1265 add_subblocks_enxblock(&(fr.block[b]), 1);
1266 fr.block[b].id = id[b];
1267 fr.block[b].sub[0].nr = nr[b];
1269 fr.block[b].sub[0].type = xdr_datatype_float;
1270 fr.block[b].sub[0].fval = block[b];
1272 fr.block[b].sub[0].type = xdr_datatype_double;
1273 fr.block[b].sub[0].dval = block[b];
1277 /* check for disre block & fill it. */
1282 add_blocks_enxframe(&fr, fr.nblock);
1284 add_subblocks_enxblock(&(fr.block[db]), 2);
1285 fr.block[db].id = enxDISRE;
1286 fr.block[db].sub[0].nr = ndisre;
1287 fr.block[db].sub[1].nr = ndisre;
1289 fr.block[db].sub[0].type = xdr_datatype_float;
1290 fr.block[db].sub[1].type = xdr_datatype_float;
1291 fr.block[db].sub[0].fval = fcd->disres.rt;
1292 fr.block[db].sub[1].fval = fcd->disres.rm3tav;
1294 fr.block[db].sub[0].type = xdr_datatype_double;
1295 fr.block[db].sub[1].type = xdr_datatype_double;
1296 fr.block[db].sub[0].dval = fcd->disres.rt;
1297 fr.block[db].sub[1].dval = fcd->disres.rm3tav;
1300 /* here we can put new-style blocks */
1302 /* Free energy perturbation blocks */
1305 mde_delta_h_coll_handle_block(dhc_, &fr, fr.nblock);
1308 /* we can now free & reset the data in the blocks */
1311 mde_delta_h_coll_reset(dhc_);
1314 /* AWH bias blocks. */
1315 if (awh != nullptr) // TODO: add boolean flag.
1317 awh->writeToEnergyFrame(step, &fr);
1320 /* do the actual I/O */
1321 do_enx(fp_ene, &fr);
1324 /* We have stored the sums, so reset the sum history */
1325 reset_ebin_sums(ebin_);
1331 if (bOR && fcd->orires.nr > 0)
1333 print_orires_log(log, &(fcd->orires));
1336 fprintf(log, " Energies (%s)\n", unit_energy);
1337 pr_ebin(log, ebin_, ie_, f_nre_+nCrmsd_, 5, eprNORMAL, true);
1342 void EnergyOutput::printAnnealingTemperatures(FILE *log, SimulationGroups *groups, t_grpopts *opts)
1348 for (int i = 0; i < opts->ngtc; i++)
1350 if (opts->annealing[i] != eannNO)
1352 fprintf(log, "Current ref_t for group %s: %8.1f\n",
1353 *(groups->groupNames[groups->groups[SimulationAtomGroupType::TemperatureCoupling][i]]),
1362 void EnergyOutput::printAverages(FILE *log, SimulationGroups *groups)
1364 if (ebin_->nsum_sim <= 0)
1368 fprintf(log, "Not enough data recorded to report energy averages\n");
1375 char buf1[22], buf2[22];
1377 fprintf(log, "\t<====== ############### ==>\n");
1378 fprintf(log, "\t<==== A V E R A G E S ====>\n");
1379 fprintf(log, "\t<== ############### ======>\n\n");
1381 fprintf(log, "\tStatistics over %s steps using %s frames\n",
1382 gmx_step_str(ebin_->nsteps_sim, buf1),
1383 gmx_step_str(ebin_->nsum_sim, buf2));
1386 fprintf(log, " Energies (%s)\n", unit_energy);
1387 pr_ebin(log, ebin_, ie_, f_nre_+nCrmsd_, 5, eprAVER, true);
1392 pr_ebin(log, ebin_, ib_, bTricl_ ? tricl_boxs_nm.size() : boxs_nm.size(), 5,
1398 fprintf(log, " Constraint Virial (%s)\n", unit_energy);
1399 pr_ebin(log, ebin_, isvir_, 9, 3, eprAVER, false);
1401 fprintf(log, " Force Virial (%s)\n", unit_energy);
1402 pr_ebin(log, ebin_, ifvir_, 9, 3, eprAVER, false);
1407 fprintf(log, " Total Virial (%s)\n", unit_energy);
1408 pr_ebin(log, ebin_, ivir_, 9, 3, eprAVER, false);
1410 fprintf(log, " Pressure (%s)\n", unit_pres_bar);
1411 pr_ebin(log, ebin_, ipres_, 9, 3, eprAVER, false);
1416 fprintf(log, " Total Dipole (%s)\n", unit_dipole_D);
1417 pr_ebin(log, ebin_, imu_, 3, 3, eprAVER, false);
1423 int padding = 8 - strlen(unit_energy);
1424 fprintf(log, "%*sEpot (%s) ", padding, "", unit_energy);
1425 for (int i = 0; (i < egNR); i++)
1429 fprintf(log, "%12s ", egrp_nm[i]);
1435 for (int i = 0; (i < nEg_); i++)
1437 int ni = groups->groups[SimulationAtomGroupType::EnergyOutput][i];
1438 for (int j = i; (j < nEg_); j++)
1440 int nj = groups->groups[SimulationAtomGroupType::EnergyOutput][j];
1441 int padding = 14 - (strlen(*(groups->groupNames[ni])) +
1442 strlen(*(groups->groupNames[nj])));
1443 fprintf(log, "%*s%s-%s", padding, "",
1444 *(groups->groupNames[ni]),
1445 *(groups->groupNames[nj]));
1446 pr_ebin(log, ebin_, igrp_[n], nEc_, nEc_, eprAVER,
1455 pr_ebin(log, ebin_, itemp_, nTC_, 4, eprAVER, true);
1460 fprintf(log, "%15s %12s %12s %12s\n",
1461 "Group", "Ux", "Uy", "Uz");
1462 for (int i = 0; (i < nU_); i++)
1464 int ni = groups->groups[SimulationAtomGroupType::Acceleration][i];
1465 fprintf(log, "%15s", *groups->groupNames[ni]);
1466 pr_ebin(log, ebin_, iu_+3*i, 3, 3, eprAVER, false);
1473 void EnergyOutput::fillEnergyHistory(energyhistory_t *enerhist) const
1475 const t_ebin * const ebin = ebin_;
1477 enerhist->nsteps = ebin->nsteps;
1478 enerhist->nsum = ebin->nsum;
1479 enerhist->nsteps_sim = ebin->nsteps_sim;
1480 enerhist->nsum_sim = ebin->nsum_sim;
1484 /* This will only actually resize the first time */
1485 enerhist->ener_ave.resize(ebin->nener);
1486 enerhist->ener_sum.resize(ebin->nener);
1488 for (int i = 0; i < ebin->nener; i++)
1490 enerhist->ener_ave[i] = ebin->e[i].eav;
1491 enerhist->ener_sum[i] = ebin->e[i].esum;
1495 if (ebin->nsum_sim > 0)
1497 /* This will only actually resize the first time */
1498 enerhist->ener_sum_sim.resize(ebin->nener);
1500 for (int i = 0; i < ebin->nener; i++)
1502 enerhist->ener_sum_sim[i] = ebin->e_sim[i].esum;
1507 mde_delta_h_coll_update_energyhistory(dhc_, enerhist);
1511 void EnergyOutput::restoreFromEnergyHistory(const energyhistory_t &enerhist)
1513 unsigned int nener = static_cast<unsigned int>(ebin_->nener);
1515 if ((enerhist.nsum > 0 && nener != enerhist.ener_sum.size()) ||
1516 (enerhist.nsum_sim > 0 && nener != enerhist.ener_sum_sim.size()))
1518 gmx_fatal(FARGS, "Mismatch between number of energies in run input (%u) and checkpoint file (%zu or %zu).",
1519 nener, enerhist.ener_sum.size(), enerhist.ener_sum_sim.size());
1522 ebin_->nsteps = enerhist.nsteps;
1523 ebin_->nsum = enerhist.nsum;
1524 ebin_->nsteps_sim = enerhist.nsteps_sim;
1525 ebin_->nsum_sim = enerhist.nsum_sim;
1527 for (int i = 0; i < ebin_->nener; i++)
1530 (enerhist.nsum > 0 ? enerhist.ener_ave[i] : 0);
1532 (enerhist.nsum > 0 ? enerhist.ener_sum[i] : 0);
1533 ebin_->e_sim[i].esum =
1534 (enerhist.nsum_sim > 0 ? enerhist.ener_sum_sim[i] : 0);
1538 mde_delta_h_coll_restore_energyhistory(dhc_, enerhist.deltaHForeignLambdas.get());
1542 int EnergyOutput::numEnergyTerms() const
1544 return ebin_->nener;