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.
40 #include "read_params.h"
42 #include "gromacs/applied_forces/awh/awh.h"
43 #include "gromacs/fileio/readinp.h"
44 #include "gromacs/fileio/warninp.h"
45 #include "gromacs/math/units.h"
46 #include "gromacs/math/utilities.h"
47 #include "gromacs/math/vec.h"
48 #include "gromacs/mdtypes/awh_params.h"
49 #include "gromacs/mdtypes/inputrec.h"
50 #include "gromacs/mdtypes/md_enums.h"
51 #include "gromacs/mdtypes/multipletimestepping.h"
52 #include "gromacs/mdtypes/pull_params.h"
53 #include "gromacs/pbcutil/pbc.h"
54 #include "gromacs/pulling/pull.h"
55 #include "gromacs/random/seed.h"
56 #include "gromacs/topology/mtop_util.h"
57 #include "gromacs/utility/cstringutil.h"
58 #include "gromacs/utility/enumerationhelpers.h"
59 #include "gromacs/utility/fatalerror.h"
60 #include "gromacs/utility/iserializer.h"
61 #include "gromacs/utility/smalloc.h"
62 #include "gromacs/utility/stringutil.h"
64 #include "biasparams.h"
65 #include "biassharing.h"
70 const char* enumValueToString(AwhTargetType enumValue)
72 constexpr gmx::EnumerationArray<AwhTargetType, const char*> awhTargetTypeNames = {
73 "constant", "cutoff", "boltzmann", "local-boltzmann"
75 return awhTargetTypeNames[enumValue];
78 const char* enumValueToString(AwhHistogramGrowthType enumValue)
80 constexpr gmx::EnumerationArray<AwhHistogramGrowthType, const char*> awhHistogramGrowthTypeNames = {
81 "exp-linear", "linear"
83 return awhHistogramGrowthTypeNames[enumValue];
86 const char* enumValueToString(AwhPotentialType enumValue)
88 constexpr gmx::EnumerationArray<AwhPotentialType, const char*> awhPotentialTypeNames = {
89 "convolved", "umbrella"
91 return awhPotentialTypeNames[enumValue];
94 const char* enumValueToString(AwhCoordinateProviderType enumValue)
96 constexpr gmx::EnumerationArray<AwhCoordinateProviderType, const char*> awhCoordinateProviderTypeNames = {
99 return awhCoordinateProviderTypeNames[enumValue];
106 * Check multiple time-stepping consistency between AWH and pull and/or FEP
108 * \param[in] inputrec Inputput parameter struct.
109 * \param[in,out] wi Struct for bookeeping warnings.
111 void checkMtsConsistency(const t_inputrec& inputrec, warninp_t wi)
113 if (!inputrec.useMts)
118 GMX_RELEASE_ASSERT(inputrec.mtsLevels.size() == 2, "Only 2 MTS levels supported here");
120 bool usesPull = false;
121 bool usesFep = false;
122 for (const auto& awhBiasParam : inputrec.awhParams->awhBiasParams())
124 for (const auto& dimParam : awhBiasParam.dimParams())
126 switch (dimParam.coordinateProvider())
128 case AwhCoordinateProviderType::Pull: usesPull = true; break;
129 case AwhCoordinateProviderType::FreeEnergyLambda: usesFep = true; break;
130 default: GMX_RELEASE_ASSERT(false, "Unsupported coord provider");
134 const int awhMtsLevel = forceGroupMtsLevel(inputrec.mtsLevels, MtsForceGroups::Awh);
135 if (usesPull && forceGroupMtsLevel(inputrec.mtsLevels, MtsForceGroups::Pull) != awhMtsLevel)
138 "When AWH is applied to pull coordinates, pull and AWH should be computed at "
139 "the same MTS level");
141 if (usesFep && awhMtsLevel != ssize(inputrec.mtsLevels) - 1)
144 "When AWH is applied to the free-energy lambda with MTS, AWH should be "
145 "computed at the slow MTS level");
148 if (inputrec.awhParams->nstSampleCoord() % inputrec.mtsLevels[awhMtsLevel].stepFactor != 0)
151 "With MTS applied to AWH, awh-nstsample should be a multiple of mts-factor");
156 * Check the parameters of an AWH bias pull dimension.
158 * \param[in] prefix Prefix for dimension parameters.
159 * \param[in,out] dimParams AWH dimensional parameters.
160 * \param[in] pull_params Pull parameters.
161 * \param[in,out] wi Struct for bookeeping warnings.
163 void checkPullDimParams(const std::string& prefix,
164 const AwhDimParams& dimParams,
165 const pull_params_t& pull_params,
168 if (dimParams.coordinateIndex() < 0)
171 "Failed to read a valid coordinate index for %s-coord-index. "
172 "Note that the pull coordinate indexing starts at 1.",
175 if (dimParams.coordinateIndex() >= pull_params.ncoord)
178 "The given AWH coordinate index (%d) is larger than the number of pull "
180 dimParams.coordinateIndex() + 1,
183 if (pull_params.coord[dimParams.coordinateIndex()].rate != 0)
185 auto message = formatString(
186 "Setting pull-coord%d-rate (%g) is incompatible with AWH biasing this coordinate",
187 dimParams.coordinateIndex() + 1,
188 pull_params.coord[dimParams.coordinateIndex()].rate);
189 warning_error(wi, message);
192 if (gmx_within_tol(dimParams.end() - dimParams.origin(), 0, GMX_REAL_EPS))
194 auto message = formatString(
195 "The given interval length given by %s-start (%g) and %s-end (%g) is zero. "
196 "This will result in only one point along this axis in the coordinate value grid.",
201 warning(wi, message);
204 if (dimParams.forceConstant() <= 0)
206 warning_error(wi, "The force AWH bias force constant should be > 0");
209 /* Grid params for each axis */
210 PullGroupGeometry eGeom = pull_params.coord[dimParams.coordinateIndex()].eGeom;
212 /* Check that the requested interval is in allowed range */
213 if (eGeom == PullGroupGeometry::Distance)
215 if (dimParams.origin() < 0 || dimParams.end() < 0)
218 "%s-start (%g) or %s-end (%g) set to a negative value. With pull "
219 "geometry distance coordinate values are non-negative. "
220 "Perhaps you want to use geometry %s instead?",
225 enumValueToString(PullGroupGeometry::Direction));
228 else if (eGeom == PullGroupGeometry::Angle || eGeom == PullGroupGeometry::AngleAxis)
230 if (dimParams.origin() < 0 || dimParams.end() > 180)
233 "%s-start (%g) and %s-end (%g) are outside of the allowed range "
234 "0 to 180 deg for pull geometries %s and %s ",
239 enumValueToString(PullGroupGeometry::Angle),
240 enumValueToString(PullGroupGeometry::AngleAxis));
243 else if (eGeom == PullGroupGeometry::Dihedral)
245 if (dimParams.origin() < -180 || dimParams.end() > 180)
248 "%s-start (%g) and %s-end (%g) are outside of the allowed range "
249 "-180 to 180 deg for pull geometry %s. ",
254 enumValueToString(PullGroupGeometry::Dihedral));
260 * Check parameters of an AWH bias in a free energy lambda state dimension.
262 * \param[in] prefix Prefix for dimension parameters.
263 * \param[in,out] dimParams AWH dimensional parameters.
264 * \param[in] lambdaParams The free energy lambda related parameters.
265 * \param[in] efep This is the type of FEP calculation (efep enumerator).
266 * \param[in,out] wi Struct for bookeeping warnings.
268 void checkFepLambdaDimParams(const std::string& prefix,
269 const AwhDimParams& dimParams,
270 const t_lambda* lambdaParams,
271 const FreeEnergyPerturbationType efep,
279 "There must be free energy input if using AWH to steer the free energy lambda "
283 if (lambdaParams->lambda_neighbors != -1)
286 "When running AWH coupled to the free energy lambda state all lambda states "
287 "should be used as neighbors in order to get correct probabilities, i.e. "
288 "calc-lambda-neighbors (%d) must be %d.",
289 lambdaParams->lambda_neighbors,
293 if (efep == FreeEnergyPerturbationType::SlowGrowth || lambdaParams->delta_lambda != 0)
296 "AWH coupled to the free energy lambda state is not compatible with slow-growth "
297 "and delta-lambda must be 0.");
300 if (efep == FreeEnergyPerturbationType::Expanded)
303 "AWH is not treated like other expanded ensemble methods. Do not use expanded.");
306 if (dimParams.origin() < 0)
308 opt = prefix + "-start";
310 "When running AWH coupled to the free energy lambda state the lower lambda state "
311 "for AWH, %s (%.0f), must be >= 0.",
315 if (dimParams.end() >= lambdaParams->n_lambda)
317 opt = prefix + "-end";
319 "When running AWH coupled to the free energy lambda state the upper lambda state "
320 "for AWH, %s (%.0f), must be < n_lambda (%d).",
323 lambdaParams->n_lambda);
325 if (gmx_within_tol(dimParams.end() - dimParams.origin(), 0, GMX_REAL_EPS))
327 auto message = formatString(
328 "The given interval length given by %s-start (%g) and %s-end (%g) is zero. "
329 "This will result in only one lambda point along this free energy lambda state "
330 "axis in the coordinate value grid.",
335 warning(wi, message);
338 if (dimParams.forceConstant() != 0)
342 "The force AWH bias force constant is not used with free energy lambda state as "
343 "coordinate provider.");
348 * Check that AWH FEP is not combined with incompatible decoupling.
350 * \param[in] mtop System topology.
351 * \param[in,out] wi Struct for bookeeping warnings.
353 void checkFepLambdaDimDecouplingConsistency(const gmx_mtop_t& mtop, warninp_t wi)
355 if (haveFepPerturbedMasses(mtop))
358 "Masses may not be perturbed when using the free energy lambda state as AWH "
359 "coordinate provider. If you are using fep-lambdas to specify lambda states "
360 "make sure that you also specify mass-lambdas without perturbation.");
362 if (havePerturbedConstraints(mtop))
365 "Constraints may not be perturbed when using the free energy lambda state as AWH "
366 "coordinate provider. If you are using fep-lambdas to specify lambda states "
367 "make sure that you also specify mass-lambdas without perturbation.");
372 * Check the parameters of an AWH bias dimension.
374 * \param[in] prefix Prefix for dimension parameters.
375 * \param[in,out] dimParams AWH dimensional parameters.
376 * \param[in] ir Input parameter struct.
377 * \param[in,out] wi Struct for bookeeping warnings.
379 void checkDimParams(const std::string& prefix, const AwhDimParams& dimParams, const t_inputrec& ir, warninp_t wi)
381 if (dimParams.coordinateProvider() == AwhCoordinateProviderType::Pull)
386 "AWH biasing along a pull dimension is only compatible with COM pulling "
389 checkPullDimParams(prefix, dimParams, *ir.pull, wi);
391 else if (dimParams.coordinateProvider() == AwhCoordinateProviderType::FreeEnergyLambda)
393 if (ir.efep == FreeEnergyPerturbationType::No)
396 "AWH biasing along a free energy lambda state dimension is only compatible "
397 "with free energy turned on");
399 checkFepLambdaDimParams(prefix, dimParams, ir.fepvals.get(), ir.efep, wi);
404 "AWH biasing can only be applied to pull and free energy lambda state "
410 * Check the parameters of an AWH bias.
412 * \param[in] awhBiasParams AWH dimensional parameters.
413 * \param[in] prefix Prefix for bias parameters.
414 * \param[in] ir Input parameter struct.
415 * \param[in,out] wi Struct for bookeeping warnings.
417 void checkBiasParams(const AwhBiasParams& awhBiasParams, const std::string& prefix, const t_inputrec& ir, warninp_t wi)
419 std::string opt = prefix + "-error-init";
420 if (awhBiasParams.initialErrorEstimate() <= 0)
422 gmx_fatal(FARGS, "%s needs to be > 0.", opt.c_str());
425 opt = prefix + "-equilibrate-histogram";
426 if (awhBiasParams.equilibrateHistogram()
427 && awhBiasParams.growthType() != AwhHistogramGrowthType::ExponentialLinear)
430 formatString("Option %s will only have an effect for histogram growth type '%s'.",
432 enumValueToString(AwhHistogramGrowthType::ExponentialLinear));
433 warning(wi, message);
436 if ((awhBiasParams.targetDistribution() == AwhTargetType::LocalBoltzmann)
437 && (awhBiasParams.growthType() == AwhHistogramGrowthType::ExponentialLinear))
439 auto message = formatString(
440 "Target type '%s' combined with histogram growth type '%s' is not "
441 "expected to give stable bias updates. You probably want to use growth type "
443 enumValueToString(AwhTargetType::LocalBoltzmann),
444 enumValueToString(AwhHistogramGrowthType::ExponentialLinear),
445 enumValueToString(AwhHistogramGrowthType::Linear));
446 warning(wi, message);
449 opt = prefix + "-target-beta-scaling";
450 switch (awhBiasParams.targetDistribution())
452 case AwhTargetType::Boltzmann:
453 case AwhTargetType::LocalBoltzmann:
454 if (awhBiasParams.targetBetaScaling() < 0 || awhBiasParams.targetBetaScaling() > 1)
457 "%s = %g is not useful for target type %s.",
459 awhBiasParams.targetBetaScaling(),
460 enumValueToString(awhBiasParams.targetDistribution()));
464 if (awhBiasParams.targetBetaScaling() != 0)
468 "Value for %s (%g) set explicitly but will not be used for target type %s.",
470 awhBiasParams.targetBetaScaling(),
471 enumValueToString(awhBiasParams.targetDistribution()));
476 opt = prefix + "-target-cutoff";
477 switch (awhBiasParams.targetDistribution())
479 case AwhTargetType::Cutoff:
480 if (awhBiasParams.targetCutoff() <= 0)
483 "%s = %g is not useful for target type %s.",
485 awhBiasParams.targetCutoff(),
486 enumValueToString(awhBiasParams.targetDistribution()));
490 if (awhBiasParams.targetCutoff() != 0)
494 "Value for %s (%g) set explicitly but will not be used for target type %s.",
496 awhBiasParams.targetCutoff(),
497 enumValueToString(awhBiasParams.targetDistribution()));
502 opt = prefix + "-share-group";
503 if (awhBiasParams.shareGroup() < 0)
505 warning_error(wi, "AWH bias share-group should be >= 0");
508 opt = prefix + "-ndim";
509 if (awhBiasParams.ndim() <= 0 || awhBiasParams.ndim() > c_biasMaxNumDim)
511 gmx_fatal(FARGS, "%s (%d) needs to be > 0 and at most %d\n", opt.c_str(), awhBiasParams.ndim(), c_biasMaxNumDim);
513 if (awhBiasParams.ndim() > 2)
516 "For awh-dim > 2 the estimate based on the diffusion and the initial error is "
517 "currently only a rough guideline."
518 " You should verify its usefulness for your system before production runs!");
520 for (int d = 0; d < awhBiasParams.ndim(); d++)
522 std::string prefixdim = prefix + formatString("-dim%d", d + 1);
523 checkDimParams(prefixdim, awhBiasParams.dimParams()[d], ir, wi);
528 * Check consistency of input at the AWH bias level.
530 * \param[in] awhBiasParams AWH bias parameters.
531 * \param[in,out] wi Struct for bookkeeping warnings.
533 void checkInputConsistencyAwhBias(const AwhBiasParams& awhBiasParams, warninp_t wi)
535 /* Covering diameter and sharing warning. */
536 auto awhBiasDimensionParams = awhBiasParams.dimParams();
537 for (const auto& dimensionParam : awhBiasDimensionParams)
539 double coverDiameter = dimensionParam.coverDiameter();
540 if (awhBiasParams.shareGroup() <= 0 && coverDiameter > 0)
543 "The covering diameter is only relevant to set for bias sharing simulations.");
549 * Check consistency of input at the AWH level.
551 * \param[in] awhParams AWH parameters.
552 * \param[in,out] wi Struct for bookkeeping warnings.
554 void checkInputConsistencyAwh(const AwhParams& awhParams, warninp_t wi)
556 /* Each pull coord can map to at most 1 AWH coord.
557 * Check that we have a shared bias when requesting multisim sharing.
559 bool haveSharedBias = false;
560 auto awhBiasParams = awhParams.awhBiasParams();
561 for (int k1 = 0; k1 < awhParams.numBias(); k1++)
563 const AwhBiasParams& awhBiasParams1 = awhBiasParams[k1];
565 if (awhBiasParams1.shareGroup() > 0)
567 haveSharedBias = true;
570 /* k1 is the reference AWH, k2 is the AWH we compare with (can be equal to k1) */
571 for (int k2 = k1; k2 < awhParams.numBias(); k2++)
573 const AwhBiasParams& awhBiasParams2 = awhBiasParams[k2];
574 const auto& dimParams1 = awhBiasParams1.dimParams();
575 const auto& dimParams2 = awhBiasParams2.dimParams();
576 for (int d1 = 0; d1 < gmx::ssize(dimParams1); d1++)
578 if (dimParams1[d1].coordinateProvider() == AwhCoordinateProviderType::FreeEnergyLambda)
582 /* d1 is the reference dimension of the reference AWH. d2 is the dim index of the AWH to compare with. */
583 for (int d2 = 0; d2 < gmx::ssize(dimParams2); d2++)
585 if (dimParams2[d2].coordinateProvider() == AwhCoordinateProviderType::FreeEnergyLambda)
589 /* Give an error if (d1, k1) is different from (d2, k2) but the pull coordinate is the same */
590 if ((d1 != d2 || k1 != k2)
591 && (dimParams1[d1].coordinateIndex() == dimParams2[d2].coordinateIndex()))
593 char errormsg[STRLEN];
595 "One pull coordinate (%d) cannot be mapped to two separate AWH "
596 "dimensions (awh%d-dim%d and awh%d-dim%d). "
597 "If this is really what you want to do you will have to duplicate "
598 "this pull coordinate.",
599 dimParams1[d1].coordinateIndex() + 1,
604 gmx_fatal(FARGS, "%s", errormsg);
611 if (awhParams.shareBiasMultisim() && !haveSharedBias)
614 "Sharing of biases over multiple simulations is requested, but no bias is marked "
615 "as shared (share-group > 0)");
618 /* mdrun does not support this (yet), but will check again */
619 if (haveBiasSharingWithinSimulation(awhParams))
622 "You have shared biases within a single simulation, but mdrun does not support "
629 AwhDimParams::AwhDimParams(std::vector<t_inpfile>* inp, const std::string& prefix, warninp_t wi, bool bComment)
634 printStringNoNewline(
636 "The provider of the reaction coordinate, "
637 "currently only 'pull' and 'fep-lambda' (free energy lambda state) is supported");
640 opt = prefix + "-coord-provider";
641 eCoordProvider_ = getEnum<AwhCoordinateProviderType>(inp, opt.c_str(), wi);
645 printStringNoNewline(inp, "The coordinate index for this dimension");
647 opt = prefix + "-coord-index";
649 coordIndexInput = get_eint(inp, opt, 1, wi);
650 if (coordIndexInput < 1)
653 "Failed to read a valid coordinate index for %s. "
654 "Note that the pull coordinate indexing starts at 1.",
658 /* The pull coordinate indices start at 1 in the input file, at 0 internally */
659 coordIndex_ = coordIndexInput - 1;
663 printStringNoNewline(inp, "Start and end values for each coordinate dimension");
666 opt = prefix + "-start";
667 origin_ = get_ereal(inp, opt, 0., wi);
669 opt = prefix + "-end";
670 end_ = get_ereal(inp, opt, 0., wi);
674 printStringNoNewline(
675 inp, "The force constant for this coordinate (kJ/mol/nm^2 or kJ/mol/rad^2)");
677 opt = prefix + "-force-constant";
678 forceConstant_ = get_ereal(inp, opt, 0, wi);
682 printStringNoNewline(inp, "Estimated diffusion constant (nm^2/ps or rad^2/ps or ps^-1)");
684 opt = prefix + "-diffusion";
685 double diffusionValue = get_ereal(inp, opt, 0, wi);
686 if (diffusionValue <= 0)
688 const double diffusion_default = 1e-5;
689 auto message = formatString(
690 "%s not explicitly set by user. You can choose to use a default "
691 "value (%g nm^2/ps or rad^2/ps) but this may very well be "
692 "non-optimal for your system!",
695 warning(wi, message);
696 diffusionValue = diffusion_default;
698 diffusion_ = diffusionValue;
702 printStringNoNewline(inp,
703 "Diameter that needs to be sampled around a point before it is "
704 "considered covered. In FEP dimensions the cover diameter is "
705 "specified in lambda states.");
707 opt = prefix + "-cover-diameter";
708 coverDiameter_ = get_ereal(inp, opt, 0, wi);
711 AwhDimParams::AwhDimParams(ISerializer* serializer)
713 GMX_RELEASE_ASSERT(serializer->reading(),
714 "Can not use writing serializer for creating datastructure");
715 serializer->doEnumAsInt(&eCoordProvider_);
716 serializer->doInt(&coordIndex_);
717 serializer->doDouble(&origin_);
718 serializer->doDouble(&end_);
719 serializer->doDouble(&period_);
720 serializer->doDouble(&forceConstant_);
721 serializer->doDouble(&diffusion_);
722 serializer->doDouble(&coordValueInit_);
723 serializer->doDouble(&coverDiameter_);
726 void AwhDimParams::serialize(ISerializer* serializer)
728 GMX_RELEASE_ASSERT(!serializer->reading(),
729 "Can not use reading serializer for writing datastructure");
730 serializer->doEnumAsInt(&eCoordProvider_);
731 serializer->doInt(&coordIndex_);
732 serializer->doDouble(&origin_);
733 serializer->doDouble(&end_);
734 serializer->doDouble(&period_);
735 serializer->doDouble(&forceConstant_);
736 serializer->doDouble(&diffusion_);
737 serializer->doDouble(&coordValueInit_);
738 serializer->doDouble(&coverDiameter_);
741 AwhBiasParams::AwhBiasParams(std::vector<t_inpfile>* inp, const std::string& prefix, warninp_t wi, bool bComment)
745 printStringNoNewline(inp, "Estimated initial PMF error (kJ/mol)");
748 std::string opt = prefix + "-error-init";
749 errorInitial_ = get_ereal(inp, opt, 10, wi);
753 printStringNoNewline(inp,
754 "Growth rate of the reference histogram determining the bias update "
755 "size: exp-linear or linear");
757 opt = prefix + "-growth";
758 eGrowth_ = getEnum<AwhHistogramGrowthType>(inp, opt.c_str(), wi);
762 printStringNoNewline(inp,
763 "Start the simulation by equilibrating histogram towards the target "
764 "distribution: no or yes");
766 opt = prefix + "-equilibrate-histogram";
767 equilibrateHistogram_ = (getEnum<Boolean>(inp, opt.c_str(), wi) != Boolean::No);
771 printStringNoNewline(
772 inp, "Target distribution type: constant, cutoff, boltzmann or local-boltzmann");
774 opt = prefix + "-target";
775 eTarget_ = getEnum<AwhTargetType>(inp, opt.c_str(), wi);
779 printStringNoNewline(inp,
780 "Boltzmann beta scaling factor for target distribution types "
781 "'boltzmann' and 'boltzmann-local'");
783 opt = prefix + "-target-beta-scaling";
784 targetBetaScaling_ = get_ereal(inp, opt, 0, wi);
788 printStringNoNewline(inp, "Free energy cutoff value for target distribution type 'cutoff'");
790 opt = prefix + "-target-cutoff";
791 targetCutoff_ = get_ereal(inp, opt, 0, wi);
795 printStringNoNewline(inp, "Initialize PMF and target with user data: no or yes");
797 opt = prefix + "-user-data";
798 bUserData_ = getEnum<Boolean>(inp, opt.c_str(), wi) != Boolean::No;
802 printStringNoNewline(inp, "Group index to share the bias with, 0 means not shared");
804 opt = prefix + "-share-group";
805 shareGroup_ = get_eint(inp, opt, 0, wi);
809 printStringNoNewline(inp, "Dimensionality of the coordinate");
811 opt = prefix + "-ndim";
812 int ndim = get_eint(inp, opt, 0, wi);
814 /* Check this before starting to read the AWH dimension parameters. */
815 if (ndim <= 0 || ndim > c_biasMaxNumDim)
817 gmx_fatal(FARGS, "%s (%d) needs to be > 0 and at most %d\n", opt.c_str(), ndim, c_biasMaxNumDim);
819 for (int d = 0; d < ndim; d++)
821 bComment = bComment && d == 0;
822 std::string prefixdim = prefix + formatString("-dim%d", d + 1);
823 dimParams_.emplace_back(inp, prefixdim, wi, bComment);
827 AwhBiasParams::AwhBiasParams(ISerializer* serializer)
829 GMX_RELEASE_ASSERT(serializer->reading(),
830 "Can not use writing serializer to create datastructure");
831 serializer->doEnumAsInt(&eTarget_);
832 serializer->doDouble(&targetBetaScaling_);
833 serializer->doDouble(&targetCutoff_);
834 serializer->doEnumAsInt(&eGrowth_);
836 serializer->doInt(&temp);
837 bUserData_ = static_cast<bool>(temp);
838 serializer->doDouble(&errorInitial_);
839 int numDimensions = dimParams_.size();
840 serializer->doInt(&numDimensions);
841 serializer->doInt(&shareGroup_);
842 serializer->doBool(&equilibrateHistogram_);
844 for (int k = 0; k < numDimensions; k++)
846 dimParams_.emplace_back(serializer);
848 /* Check consistencies here that cannot be checked at read time at a lower level. */
849 checkInputConsistencyAwhBias(*this, nullptr);
852 void AwhBiasParams::serialize(ISerializer* serializer)
854 GMX_RELEASE_ASSERT(!serializer->reading(),
855 "Can not use reading serializer to write datastructure");
856 serializer->doEnumAsInt(&eTarget_);
857 serializer->doDouble(&targetBetaScaling_);
858 serializer->doDouble(&targetCutoff_);
859 serializer->doEnumAsInt(&eGrowth_);
860 int temp = static_cast<int>(bUserData_);
861 serializer->doInt(&temp);
862 serializer->doDouble(&errorInitial_);
863 int numDimensions = ndim();
864 serializer->doInt(&numDimensions);
865 serializer->doInt(&shareGroup_);
866 serializer->doBool(&equilibrateHistogram_);
868 for (int k = 0; k < numDimensions; k++)
870 dimParams_[k].serialize(serializer);
874 AwhParams::AwhParams(std::vector<t_inpfile>* inp, warninp_t wi)
878 /* Parameters common for all biases */
880 printStringNoNewline(inp, "The way to apply the biasing potential: convolved or umbrella");
881 opt = "awh-potential";
882 potentialEnum_ = getEnum<AwhPotentialType>(inp, opt.c_str(), wi);
884 printStringNoNewline(inp,
885 "The random seed used for sampling the umbrella center in the case of "
886 "umbrella type potential");
888 seed_ = get_eint(inp, opt, -1, wi);
891 seed_ = static_cast<int>(gmx::makeRandomSeed());
892 fprintf(stderr, "Setting the AWH bias MC random seed to %" PRId64 "\n", seed_);
895 printStringNoNewline(inp, "Data output interval in number of steps");
897 nstOut_ = get_eint(inp, opt, 100000, wi);
899 printStringNoNewline(inp, "Coordinate sampling interval in number of steps");
900 opt = "awh-nstsample";
901 nstSampleCoord_ = get_eint(inp, opt, 10, wi);
903 printStringNoNewline(inp, "Free energy and bias update interval in number of samples");
904 opt = "awh-nsamples-update";
905 numSamplesUpdateFreeEnergy_ = get_eint(inp, opt, 10, wi);
907 printStringNoNewline(
908 inp, "When true, biases with share-group>0 are shared between multiple simulations");
909 opt = "awh-share-multisim";
910 shareBiasMultisim_ = (getEnum<Boolean>(inp, opt.c_str(), wi) != Boolean::No);
912 printStringNoNewline(inp, "The number of independent AWH biases");
914 int numBias = get_eint(inp, opt, 1, wi);
915 /* Check this before starting to read the AWH biases. */
918 gmx_fatal(FARGS, "%s needs to be an integer > 0", opt.c_str());
921 /* Read the parameters specific to each AWH bias */
922 for (int k = 0; k < numBias; k++)
924 bool bComment = (k == 0);
925 std::string prefixawh = formatString("awh%d", k + 1);
926 awhBiasParams_.emplace_back(inp, prefixawh, wi, bComment);
928 checkInputConsistencyAwh(*this, wi);
931 AwhParams::AwhParams(ISerializer* serializer)
933 GMX_RELEASE_ASSERT(serializer->reading(),
934 "Can not use writing serializer to read AWH parameters");
935 int numberOfBiases = awhBiasParams_.size();
936 serializer->doInt(&numberOfBiases);
937 serializer->doInt(&nstOut_);
938 serializer->doInt64(&seed_);
939 serializer->doInt(&nstSampleCoord_);
940 serializer->doInt(&numSamplesUpdateFreeEnergy_);
941 serializer->doEnumAsInt(&potentialEnum_);
942 serializer->doBool(&shareBiasMultisim_);
944 if (numberOfBiases > 0)
946 for (int k = 0; k < numberOfBiases; k++)
948 awhBiasParams_.emplace_back(serializer);
951 checkInputConsistencyAwh(*this, nullptr);
954 void AwhParams::serialize(ISerializer* serializer)
956 GMX_RELEASE_ASSERT(!serializer->reading(),
957 "Can not use reading serializer to write AWH parameters");
958 int numberOfBiases = numBias();
959 serializer->doInt(&numberOfBiases);
960 serializer->doInt(&nstOut_);
961 serializer->doInt64(&seed_);
962 serializer->doInt(&nstSampleCoord_);
963 serializer->doInt(&numSamplesUpdateFreeEnergy_);
964 serializer->doEnumAsInt(&potentialEnum_);
965 serializer->doBool(&shareBiasMultisim_);
967 if (numberOfBiases > 0)
969 for (int k = 0; k < numberOfBiases; k++)
971 awhBiasParams_[k].serialize(serializer);
977 * Gets the period of a pull coordinate.
979 * \param[in] pullCoordParams The parameters for the pull coordinate.
980 * \param[in] pbc The PBC setup
981 * \param[in] intervalLength The length of the AWH interval for this pull coordinate
982 * \returns the period (or 0 if not periodic).
984 static double get_pull_coord_period(const t_pull_coord& pullCoordParams, const t_pbc& pbc, const real intervalLength)
988 if (pullCoordParams.eGeom == PullGroupGeometry::Direction)
990 const real margin = 0.001;
991 // Make dims periodic when the interval covers > 95%
992 const real periodicFraction = 0.95;
994 // Check if the pull direction is along a box vector
995 for (int dim = 0; dim < pbc.ndim_ePBC; dim++)
997 const real boxLength = norm(pbc.box[dim]);
998 const real innerProduct = iprod(pullCoordParams.vec, pbc.box[dim]);
999 if (innerProduct >= (1 - margin) * boxLength && innerProduct <= (1 + margin) * boxLength)
1001 if (intervalLength > (1 + margin) * boxLength)
1004 "The AWH interval (%f nm) for a pull coordinate is larger than the "
1010 if (intervalLength > periodicFraction * boxLength)
1017 else if (pullCoordParams.eGeom == PullGroupGeometry::Dihedral)
1019 /* The dihedral angle is periodic in -180 to 180 deg */
1027 * Checks if the given interval is defined in the correct periodic interval.
1029 * \param[in] origin Start value of interval.
1030 * \param[in] end End value of interval.
1031 * \param[in] period Period (or 0 if not periodic).
1032 * \returns true if the end point values are in the correct periodic interval.
1034 static bool intervalIsInPeriodicInterval(double origin, double end, double period)
1036 return (period == 0) || (std::fabs(origin) <= 0.5 * period && std::fabs(end) <= 0.5 * period);
1040 * Checks if a value is within an interval.
1042 * \param[in] origin Start value of interval.
1043 * \param[in] end End value of interval.
1044 * \param[in] period Period (or 0 if not periodic).
1045 * \param[in] value Value to check.
1046 * \returns true if the value is within the interval.
1048 static bool valueIsInInterval(double origin, double end, double period, double value)
1056 /* The interval closes within the periodic interval */
1057 bIn_interval = (value >= origin) && (value <= end);
1061 /* The interval wraps around the periodic boundary */
1062 bIn_interval = ((value >= origin) && (value <= 0.5 * period))
1063 || ((value >= -0.5 * period) && (value <= end));
1068 bIn_interval = (value >= origin) && (value <= end);
1071 return bIn_interval;
1075 * Check if the starting configuration is consistent with the given interval.
1077 * \param[in] awhParams AWH parameters.
1078 * \param[in,out] wi Struct for bookeeping warnings.
1080 static void checkInputConsistencyInterval(const AwhParams& awhParams, warninp_t wi)
1082 const auto& awhBiasParams = awhParams.awhBiasParams();
1083 for (int k = 0; k < gmx::ssize(awhBiasParams); k++)
1085 const auto& dimParams = awhBiasParams[k].dimParams();
1086 for (int d = 0; d < gmx::ssize(dimParams); d++)
1088 int coordIndex = dimParams[d].coordinateIndex();
1089 double origin = dimParams[d].origin(), end = dimParams[d].end(),
1090 period = dimParams[d].period();
1091 double coordValueInit = dimParams[d].initialCoordinate();
1093 if ((period == 0) && (origin > end))
1096 "For the non-periodic pull coordinates awh%d-dim%d-start (%f) cannot be "
1097 "larger than awh%d-dim%d-end (%f)",
1106 /* Currently we assume symmetric periodic intervals, meaning we use [-period/2, period/2] as the reference interval.
1107 Make sure the AWH interval is within this reference interval.
1109 Note: we could fairly simply allow using a more general interval (e.g. [x, x + period]) but it complicates
1110 things slightly and I don't see that there is a great need for it. It would also mean that the interval would
1111 depend on AWH input. Also, for dihedral angles you would always want the reference interval to be -180, +180,
1112 independent of AWH parameters.
1114 if (!intervalIsInPeriodicInterval(origin, end, period))
1117 "When using AWH with periodic pull coordinate geometries "
1118 "awh%d-dim%d-start (%.8g) and "
1119 "awh%d-dim%d-end (%.8g) should cover at most one period (%.8g) and take "
1120 "values in between "
1121 "minus half a period and plus half a period, i.e. in the interval [%.8g, "
1134 /* Warn if the pull initial coordinate value is not in the grid */
1135 if (!valueIsInInterval(origin, end, period, coordValueInit))
1137 auto message = formatString(
1138 "The initial coordinate value (%.8g) for pull coordinate index %d falls "
1140 "of the sampling nterval awh%d-dim%d-start (%.8g) to awh%d-dim%d-end "
1142 "This can lead to large initial forces pulling the coordinate towards the "
1143 "sampling interval.",
1152 warning(wi, message);
1159 * Sets AWH parameters, for one AWH pull dimension.
1161 * \param[in,out] dimParams AWH dimension parameters.
1162 * \param[in] biasIndex The index of the bias containing this AWH pull dimension.
1163 * \param[in] dimIndex The index of this AWH pull dimension.
1164 * \param[in] pull_params Pull parameters.
1165 * \param[in,out] pull_work Pull working struct to register AWH bias in.
1166 * \param[in] pbc A pbc information structure.
1167 * \param[in] compressibility Compressibility matrix for pressure coupling,
1168 * pass all 0 without pressure coupling.
1169 * \param[in,out] wi Struct for bookeeping warnings.
1172 static void setStateDependentAwhPullDimParams(AwhDimParams* dimParams,
1173 const int biasIndex,
1175 const pull_params_t& pull_params,
1178 const tensor& compressibility,
1181 const t_pull_coord& pullCoordParams = pull_params.coord[dimParams->coordinateIndex()];
1183 if (pullCoordParams.eGeom == PullGroupGeometry::DirectionPBC)
1186 "AWH does not support pull geometry '%s'. "
1187 "If the maximum distance between the groups is always "
1188 "less than half the box size, "
1189 "you can use geometry '%s' instead.",
1190 enumValueToString(PullGroupGeometry::DirectionPBC),
1191 enumValueToString(PullGroupGeometry::Direction));
1194 dimParams->setPeriod(
1195 get_pull_coord_period(pullCoordParams, pbc, dimParams->end() - dimParams->origin()));
1196 // We would like to check for scaling, but we don't have the full inputrec available here
1197 if (dimParams->period() > 0
1198 && !(pullCoordParams.eGeom == PullGroupGeometry::Angle
1199 || pullCoordParams.eGeom == PullGroupGeometry::Dihedral))
1201 bool coordIsScaled = false;
1202 for (int d2 = 0; d2 < DIM; d2++)
1204 if (pullCoordParams.vec[d2] != 0 && norm2(compressibility[d2]) != 0)
1206 coordIsScaled = true;
1211 std::string mesg = gmx::formatString(
1212 "AWH dimension %d of bias %d is periodic with pull geometry '%s', "
1213 "while you should be applying pressure scaling to the "
1214 "corresponding box vector, this is not supported.",
1217 enumValueToString(pullCoordParams.eGeom));
1218 warning(wi, mesg.c_str());
1222 /* The initial coordinate value, converted to external user units. */
1223 double initialCoordinate = get_pull_coord_value(pull_work, dimParams->coordinateIndex(), &pbc);
1224 initialCoordinate *= pull_conversion_factor_internal2userinput(pullCoordParams);
1225 dimParams->setInitialCoordinate(initialCoordinate);
1228 void setStateDependentAwhParams(AwhParams* awhParams,
1229 const pull_params_t& pull_params,
1233 const tensor& compressibility,
1234 const t_grpopts* inputrecGroupOptions,
1235 const real initLambda,
1236 const gmx_mtop_t& mtop,
1239 /* The temperature is not really state depenendent but is not known
1240 * when read_awhParams is called (in get ir).
1241 * It is known first after do_index has been called in grompp.cpp.
1243 if (inputrecGroupOptions->ref_t == nullptr || inputrecGroupOptions->ref_t[0] <= 0)
1245 gmx_fatal(FARGS, "AWH biasing is only supported for temperatures > 0");
1247 for (int i = 1; i < inputrecGroupOptions->ngtc; i++)
1249 if (inputrecGroupOptions->ref_t[i] != inputrecGroupOptions->ref_t[0])
1252 "AWH biasing is currently only supported for identical temperatures for all "
1253 "temperature coupling groups");
1258 set_pbc(&pbc, pbcType, box);
1260 auto awhBiasParams = awhParams->awhBiasParams();
1261 for (int k = 0; k < awhParams->numBias(); k++)
1263 auto awhBiasDimensionParams = awhBiasParams[k].dimParams();
1264 for (int d = 0; d < awhBiasParams[k].ndim(); d++)
1266 AwhDimParams* dimParams = &awhBiasDimensionParams[d];
1267 if (dimParams->coordinateProvider() == AwhCoordinateProviderType::Pull)
1269 setStateDependentAwhPullDimParams(
1270 dimParams, k, d, pull_params, pull_work, pbc, compressibility, wi);
1274 dimParams->setInitialCoordinate(initLambda);
1275 checkFepLambdaDimDecouplingConsistency(mtop, wi);
1279 checkInputConsistencyInterval(*awhParams, wi);
1281 /* Register AWH as external potential with pull (for AWH dimensions that use pull as
1282 * reaction coordinate provider) to check consistency. */
1283 Awh::registerAwhWithPull(*awhParams, pull_work);
1286 void checkAwhParams(const AwhParams& awhParams, const t_inputrec& ir, warninp_t wi)
1289 checkMtsConsistency(ir, wi);
1292 if (awhParams.nstout() <= 0)
1294 auto message = formatString("Not writing AWH output with AWH (%s = %d) does not make sense",
1296 awhParams.nstout());
1297 warning_error(wi, message);
1299 /* This restriction can be removed by changing a flag of print_ebin() */
1300 if (ir.nstenergy == 0 || awhParams.nstout() % ir.nstenergy != 0)
1302 auto message = formatString(
1303 "%s (%d) should be a multiple of nstenergy (%d)", opt.c_str(), awhParams.nstout(), ir.nstenergy);
1304 warning_error(wi, message);
1307 opt = "awh-nsamples-update";
1308 if (awhParams.numSamplesUpdateFreeEnergy() <= 0)
1310 warning_error(wi, opt + " needs to be an integer > 0");
1313 for (int k = 0; k < awhParams.numBias(); k++)
1315 std::string prefixawh = formatString("awh%d", k + 1);
1316 checkBiasParams(awhParams.awhBiasParams()[k], prefixawh, ir, wi);
1319 if (ir.init_step != 0)
1321 warning_error(wi, "With AWH init-step should be 0");