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) 2011-2019,2020,2021, 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.
40 * \brief Implements the replica exchange routines.
42 * \author David van der Spoel <david.vanderspoel@icm.uu.se>
43 * \author Mark Abraham <mark.j.abraham@gmail.com>
44 * \ingroup module_mdrun
48 #include "replicaexchange.h"
56 #include "gromacs/domdec/collect.h"
57 #include "gromacs/gmxlib/network.h"
58 #include "gromacs/math/units.h"
59 #include "gromacs/math/vec.h"
60 #include "gromacs/mdrunutility/multisim.h"
61 #include "gromacs/mdtypes/commrec.h"
62 #include "gromacs/mdtypes/enerdata.h"
63 #include "gromacs/mdtypes/inputrec.h"
64 #include "gromacs/mdtypes/md_enums.h"
65 #include "gromacs/mdtypes/state.h"
66 #include "gromacs/random/threefry.h"
67 #include "gromacs/random/uniformintdistribution.h"
68 #include "gromacs/random/uniformrealdistribution.h"
69 #include "gromacs/utility/enumerationhelpers.h"
70 #include "gromacs/utility/fatalerror.h"
71 #include "gromacs/utility/pleasecite.h"
72 #include "gromacs/utility/smalloc.h"
74 //! Helps cut off probability values.
75 constexpr int c_probabilityCutoff = 100;
77 /* we don't bother evaluating if events are more rare than exp(-100) = 3.7x10^-44 */
79 //! Rank in the multisimulation
80 #define MSRANK(ms, nodeid) (nodeid)
82 //! Enum for replica exchange flavours
83 enum class ReplicaExchangeType : int
91 /*! \brief Strings describing replica exchange flavours.
93 * end_single_marker merely notes the end of single variable replica
94 * exchange. All types higher than it are multiple replica exchange
97 * Eventually, should add 'pressure', 'temperature and pressure',
98 * 'lambda_and_pressure', 'temperature_lambda_pressure'?; Let's wait
99 * until we feel better about the pressure control methods giving
100 * exact ensembles. Right now, we assume constant pressure */
101 static const char* enumValueToString(ReplicaExchangeType enumValue)
103 constexpr gmx::EnumerationArray<ReplicaExchangeType, const char*> replicateExchangeTypeNames = {
104 "temperature", "lambda", "end_single_marker", "temperature and lambda"
106 return replicateExchangeTypeNames[enumValue];
109 //! Working data for replica exchange.
114 //! Total number of replica
118 //! Replica exchange type from ReplicaExchangeType enum
119 ReplicaExchangeType type;
120 //! Quantity, e.g. temperature or lambda; first index is ere, second index is replica ID
121 gmx::EnumerationArray<ReplicaExchangeType, real*> q;
122 //! Use constant pressure and temperature
124 //! Replica pressures
128 //! Used for keeping track of all the replica swaps
130 //! Replica exchange interval (number of steps)
132 //! Number of exchanges per interval
136 //! Number of even and odd replica change attempts
138 //! Sum of probabilities
140 //! Number of moves between replicas i and j
142 //! i-th element of the array is the number of exchanges between replica i-1 and i
145 /*! \brief Helper arrays for replica exchange; allocated here
146 * so they don't have to be allocated each time */
156 //! Helper arrays to hold the quantities that are exchanged.
166 // TODO We should add Doxygen here some time.
169 static gmx_bool repl_quantity(const gmx_multisim_t* ms, struct gmx_repl_ex* re, ReplicaExchangeType ere, real q)
175 snew(qall, ms->numSimulations_);
177 gmx_sum_sim(ms->numSimulations_, qall, ms);
180 for (s = 1; s < ms->numSimulations_; s++)
182 if (qall[s] != qall[0])
190 /* Set the replica exchange type and quantities */
193 snew(re->q[ere], re->nrepl);
194 for (s = 0; s < ms->numSimulations_; s++)
196 re->q[ere][s] = qall[s];
203 gmx_repl_ex_t init_replica_exchange(FILE* fplog,
204 const gmx_multisim_t* ms,
205 int numAtomsInSystem,
206 const t_inputrec* ir,
207 const ReplicaExchangeParameters& replExParams)
211 struct gmx_repl_ex* re;
213 gmx_bool bLambda = FALSE;
215 fprintf(fplog, "\nInitializing Replica Exchange\n");
217 if (!isMultiSim(ms) || ms->numSimulations_ == 1)
220 "Nothing to exchange with only one replica, maybe you forgot to set the "
221 "-multidir option of mdrun?");
223 if (replExParams.numExchanges < 0)
225 gmx_fatal(FARGS, "Replica exchange number of exchanges needs to be positive");
228 if (!EI_DYNAMICS(ir->eI))
230 gmx_fatal(FARGS, "Replica exchange is only supported by dynamical simulations");
231 /* Note that PAR(cr) is defined by cr->nnodes > 1, which is
232 * distinct from isMultiSim(ms). A multi-simulation only runs
233 * with real MPI parallelism, but this does not imply PAR(cr)
236 * Since we are using a dynamical integrator, the only
237 * decomposition is DD, so PAR(cr) and DOMAINDECOMP(cr) are
238 * synonymous. The only way for cr->nnodes > 1 to be true is
239 * if we are using DD. */
244 re->repl = ms->simulationIndex_;
245 re->nrepl = ms->numSimulations_;
247 fprintf(fplog, "Repl There are %d replicas:\n", re->nrepl);
249 /* We only check that the number of atoms in the systms match.
250 * This, of course, do not guarantee that the systems are the same,
251 * but it does guarantee that we can perform replica exchange.
253 check_multi_int(fplog, ms, numAtomsInSystem, "the number of atoms", FALSE);
254 check_multi_int(fplog, ms, static_cast<int>(ir->eI), "the integrator", FALSE);
255 check_multi_int64(fplog, ms, ir->init_step + ir->nsteps, "init_step+nsteps", FALSE);
256 const int nst = replExParams.exchangeInterval;
258 fplog, ms, (ir->init_step + nst - 1) / nst, "first exchange step: init_step/-replex", FALSE);
259 check_multi_int(fplog, ms, static_cast<int>(ir->etc), "the temperature coupling", FALSE);
260 check_multi_int(fplog, ms, ir->opts.ngtc, "the number of temperature coupling groups", FALSE);
261 check_multi_int(fplog, ms, static_cast<int>(ir->epc), "the pressure coupling", FALSE);
262 check_multi_int(fplog, ms, static_cast<int>(ir->efep), "free energy", FALSE);
263 check_multi_int(fplog, ms, ir->fepvals->n_lambda, "number of lambda states", FALSE);
265 re->temp = ir->opts.ref_t[0];
266 for (i = 1; (i < ir->opts.ngtc); i++)
268 if (ir->opts.ref_t[i] != re->temp)
271 "\nWARNING: The temperatures of the different temperature coupling groups are "
272 "not identical\n\n");
274 "\nWARNING: The temperatures of the different temperature coupling groups are "
275 "not identical\n\n");
279 re->type = ReplicaExchangeType::Count;
280 bTemp = repl_quantity(ms, re, ReplicaExchangeType::Temperature, re->temp);
281 if (ir->efep != FreeEnergyPerturbationType::No)
283 bLambda = repl_quantity(
284 ms, re, ReplicaExchangeType::Lambda, static_cast<real>(ir->fepvals->init_fep_state));
286 if (re->type == ReplicaExchangeType::Count) /* nothing was assigned */
289 "The properties of the %d systems are all the same, there is nothing to exchange",
292 if (bLambda && bTemp)
294 re->type = ReplicaExchangeType::TemperatureLambda;
299 please_cite(fplog, "Sugita1999a");
300 if (ir->epc != PressureCoupling::No)
303 fprintf(fplog, "Repl Using Constant Pressure REMD.\n");
304 please_cite(fplog, "Okabe2001a");
306 if (ir->etc == TemperatureCoupling::Berendsen)
309 "REMD with the %s thermostat does not produce correct potential energy "
310 "distributions, consider using the %s thermostat instead",
311 enumValueToString(ir->etc),
312 enumValueToString(TemperatureCoupling::VRescale));
317 if (ir->fepvals->delta_lambda != 0) /* check this? */
319 gmx_fatal(FARGS, "delta_lambda is not zero");
324 snew(re->pres, re->nrepl);
325 if (ir->epct == PressureCouplingType::SurfaceTension)
327 pres = ir->ref_p[ZZ][ZZ];
333 for (i = 0; i < DIM; i++)
335 if (ir->compress[i][i] != 0)
337 pres += ir->ref_p[i][i];
343 re->pres[re->repl] = pres;
344 gmx_sum_sim(re->nrepl, re->pres, ms);
347 /* Make an index for increasing replica order */
348 /* only makes sense if one or the other is varying, not both!
349 if both are varying, we trust the order the person gave. */
350 snew(re->ind, re->nrepl);
351 for (i = 0; i < re->nrepl; i++)
356 if (re->type < ReplicaExchangeType::EndSingle)
359 for (i = 0; i < re->nrepl; i++)
361 for (j = i + 1; j < re->nrepl; j++)
363 if (re->q[re->type][re->ind[j]] < re->q[re->type][re->ind[i]])
365 /* Unordered replicas are supposed to work, but there
366 * is still an issues somewhere.
367 * Note that at this point still re->ind[i]=i.
370 "Replicas with indices %d < %d have %ss %g > %g, please order your "
371 "replicas on increasing %s",
374 enumValueToString(re->type),
377 enumValueToString(re->type));
379 else if (re->q[re->type][re->ind[j]] == re->q[re->type][re->ind[i]])
381 gmx_fatal(FARGS, "Two replicas have identical %ss", enumValueToString(re->type));
387 /* keep track of all the swaps, starting with the initial placement. */
388 snew(re->allswaps, re->nrepl);
389 for (i = 0; i < re->nrepl; i++)
391 re->allswaps[i] = re->ind[i];
396 case ReplicaExchangeType::Temperature:
397 fprintf(fplog, "\nReplica exchange in temperature\n");
398 for (i = 0; i < re->nrepl; i++)
400 fprintf(fplog, " %5.1f", re->q[re->type][re->ind[i]]);
402 fprintf(fplog, "\n");
404 case ReplicaExchangeType::Lambda:
405 fprintf(fplog, "\nReplica exchange in lambda\n");
406 for (i = 0; i < re->nrepl; i++)
408 fprintf(fplog, " %3d", static_cast<int>(re->q[re->type][re->ind[i]]));
410 fprintf(fplog, "\n");
412 case ReplicaExchangeType::TemperatureLambda:
413 fprintf(fplog, "\nReplica exchange in temperature and lambda state\n");
414 for (i = 0; i < re->nrepl; i++)
416 fprintf(fplog, " %5.1f", re->q[ReplicaExchangeType::Temperature][re->ind[i]]);
418 fprintf(fplog, "\n");
419 for (i = 0; i < re->nrepl; i++)
421 fprintf(fplog, " %5d", static_cast<int>(re->q[ReplicaExchangeType::Lambda][re->ind[i]]));
423 fprintf(fplog, "\n");
425 default: gmx_incons("Unknown replica exchange quantity");
429 fprintf(fplog, "\nRepl p");
430 for (i = 0; i < re->nrepl; i++)
432 fprintf(fplog, " %5.2f", re->pres[re->ind[i]]);
435 for (i = 0; i < re->nrepl; i++)
437 if ((i > 0) && (re->pres[re->ind[i]] < re->pres[re->ind[i - 1]]))
440 "\nWARNING: The reference pressures decrease with increasing "
443 "\nWARNING: The reference pressures decrease with increasing "
449 if (replExParams.randomSeed == -1)
453 re->seed = static_cast<int>(gmx::makeRandomSeed());
459 gmx_sumi_sim(1, &(re->seed), ms);
463 re->seed = replExParams.randomSeed;
465 fprintf(fplog, "\nReplica exchange interval: %d\n", re->nst);
466 fprintf(fplog, "\nReplica random seed: %d\n", re->seed);
471 snew(re->prob_sum, re->nrepl);
472 snew(re->nexchange, re->nrepl);
473 snew(re->nmoves, re->nrepl);
474 for (i = 0; i < re->nrepl; i++)
476 snew(re->nmoves[i], re->nrepl);
478 fprintf(fplog, "Replica exchange information below: ex and x = exchange, pr = probability\n");
480 /* generate space for the helper functions so we don't have to snew each time */
482 snew(re->destinations, re->nrepl);
483 snew(re->incycle, re->nrepl);
484 snew(re->tmpswap, re->nrepl);
485 snew(re->cyclic, re->nrepl);
486 snew(re->order, re->nrepl);
487 for (i = 0; i < re->nrepl; i++)
489 snew(re->cyclic[i], re->nrepl + 1);
490 snew(re->order[i], re->nrepl);
492 /* allocate space for the functions storing the data for the replicas */
493 /* not all of these arrays needed in all cases, but they don't take
494 up much space, since the max size is nrepl**2 */
495 snew(re->prob, re->nrepl);
496 snew(re->bEx, re->nrepl);
497 snew(re->beta, re->nrepl);
498 snew(re->Vol, re->nrepl);
499 snew(re->Epot, re->nrepl);
500 snew(re->de, re->nrepl);
501 for (i = 0; i < re->nrepl; i++)
503 snew(re->de[i], re->nrepl);
505 re->nex = replExParams.numExchanges;
509 static void exchange_reals(const gmx_multisim_t gmx_unused* ms, int gmx_unused b, real* v, int n)
519 MPI_Sendrecv(v, n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
520 buf,n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
521 ms->mastersComm_,MPI_STATUS_IGNORE);
526 MPI_Isend(v, n * sizeof(real), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, &mpi_req);
527 MPI_Recv(buf, n * sizeof(real), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, MPI_STATUS_IGNORE);
528 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
531 for (i = 0; i < n; i++)
540 static void exchange_doubles(const gmx_multisim_t gmx_unused* ms, int gmx_unused b, double* v, int n)
550 MPI_Sendrecv(v, n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
551 buf,n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
552 ms->mastersComm_,MPI_STATUS_IGNORE);
557 MPI_Isend(v, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, &mpi_req);
558 MPI_Recv(buf, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, MPI_STATUS_IGNORE);
559 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
562 for (i = 0; i < n; i++)
570 static void exchange_rvecs(const gmx_multisim_t gmx_unused* ms, int gmx_unused b, rvec* v, int n)
580 MPI_Sendrecv(v[0], n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
581 buf[0],n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
582 ms->mastersComm_,MPI_STATUS_IGNORE);
587 MPI_Isend(v[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, &mpi_req);
588 MPI_Recv(buf[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, MPI_STATUS_IGNORE);
589 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
592 for (i = 0; i < n; i++)
594 copy_rvec(buf[i], v[i]);
600 static void exchange_state(const gmx_multisim_t* ms, int b, t_state* state)
602 /* When t_state changes, this code should be updated. */
604 ngtc = state->ngtc * state->nhchainlength;
605 nnhpres = state->nnhpres * state->nhchainlength;
606 exchange_rvecs(ms, b, state->box, DIM);
607 exchange_rvecs(ms, b, state->box_rel, DIM);
608 exchange_rvecs(ms, b, state->boxv, DIM);
609 exchange_reals(ms, b, &(state->veta), 1);
610 exchange_reals(ms, b, &(state->vol0), 1);
611 exchange_rvecs(ms, b, state->svir_prev, DIM);
612 exchange_rvecs(ms, b, state->fvir_prev, DIM);
613 exchange_rvecs(ms, b, state->pres_prev, DIM);
614 exchange_doubles(ms, b, state->nosehoover_xi.data(), ngtc);
615 exchange_doubles(ms, b, state->nosehoover_vxi.data(), ngtc);
616 exchange_doubles(ms, b, state->nhpres_xi.data(), nnhpres);
617 exchange_doubles(ms, b, state->nhpres_vxi.data(), nnhpres);
618 exchange_doubles(ms, b, state->therm_integral.data(), state->ngtc);
619 exchange_doubles(ms, b, &state->baros_integral, 1);
620 exchange_rvecs(ms, b, state->x.rvec_array(), state->natoms);
621 exchange_rvecs(ms, b, state->v.rvec_array(), state->natoms);
624 static void copy_state_serial(const t_state* src, t_state* dest)
628 /* Currently the local state is always a pointer to the global
629 * in serial, so we should never end up here.
630 * TODO: Implement a (trivial) t_state copy once converted to C++.
632 GMX_RELEASE_ASSERT(false, "State copying is currently not implemented in replica exchange");
636 static void scale_velocities(gmx::ArrayRef<gmx::RVec> velocities, real fac)
638 for (auto& v : velocities)
644 static void print_transition_matrix(FILE* fplog, int n, int** nmoves, const int* nattempt)
649 ntot = nattempt[0] + nattempt[1];
650 fprintf(fplog, "\n");
651 fprintf(fplog, "Repl");
652 for (i = 0; i < n; i++)
654 fprintf(fplog, " "); /* put the title closer to the center */
656 fprintf(fplog, "Empirical Transition Matrix\n");
658 fprintf(fplog, "Repl");
659 for (i = 0; i < n; i++)
661 fprintf(fplog, "%8d", (i + 1));
663 fprintf(fplog, "\n");
665 for (i = 0; i < n; i++)
667 fprintf(fplog, "Repl");
668 for (j = 0; j < n; j++)
671 if (nmoves[i][j] > 0)
673 Tprint = nmoves[i][j] / (2.0 * ntot);
675 fprintf(fplog, "%8.4f", Tprint);
677 fprintf(fplog, "%3d\n", i);
681 static void print_ind(FILE* fplog, const char* leg, int n, int* ind, const gmx_bool* bEx)
685 fprintf(fplog, "Repl %2s %2d", leg, ind[0]);
686 for (i = 1; i < n; i++)
688 fprintf(fplog, " %c %2d", (bEx != nullptr && bEx[i]) ? 'x' : ' ', ind[i]);
690 fprintf(fplog, "\n");
693 static void print_allswitchind(FILE* fplog, int n, int* pind, int* allswaps, int* tmpswap)
697 for (i = 0; i < n; i++)
699 tmpswap[i] = allswaps[i];
701 for (i = 0; i < n; i++)
703 allswaps[i] = tmpswap[pind[i]];
706 fprintf(fplog, "\nAccepted Exchanges: ");
707 for (i = 0; i < n; i++)
709 fprintf(fplog, "%d ", pind[i]);
711 fprintf(fplog, "\n");
713 /* the "Order After Exchange" is the state label corresponding to the configuration that
714 started in state listed in order, i.e.
719 configuration starting in simulation 3 is now in simulation 0,
720 configuration starting in simulation 0 is now in simulation 1,
721 configuration starting in simulation 1 is now in simulation 2,
722 configuration starting in simulation 2 is now in simulation 3
724 fprintf(fplog, "Order After Exchange: ");
725 for (i = 0; i < n; i++)
727 fprintf(fplog, "%d ", allswaps[i]);
729 fprintf(fplog, "\n\n");
732 static void print_prob(FILE* fplog, const char* leg, int n, real* prob)
737 fprintf(fplog, "Repl %2s ", leg);
738 for (i = 1; i < n; i++)
742 sprintf(buf, "%4.2f", prob[i]);
743 fprintf(fplog, " %3s", buf[0] == '1' ? "1.0" : buf + 1);
750 fprintf(fplog, "\n");
753 static void print_count(FILE* fplog, const char* leg, int n, int* count)
757 fprintf(fplog, "Repl %2s ", leg);
758 for (i = 1; i < n; i++)
760 fprintf(fplog, " %4d", count[i]);
762 fprintf(fplog, "\n");
765 static real calc_delta(FILE* fplog, gmx_bool bPrint, struct gmx_repl_ex* re, int a, int b, int ap, int bp)
768 real ediff, dpV, delta = 0;
769 real* Epot = re->Epot;
772 real* beta = re->beta;
774 /* Two cases; we are permuted and not. In all cases, setting ap = a and bp = b will reduce
775 to the non permuted case */
779 case ReplicaExchangeType::Temperature:
781 * Okabe et. al. Chem. Phys. Lett. 335 (2001) 435-439
783 ediff = Epot[b] - Epot[a];
784 delta = -(beta[bp] - beta[ap]) * ediff;
786 case ReplicaExchangeType::Lambda:
787 /* two cases: when we are permuted, and not. */
789 ediff = E_new - E_old
790 = [H_b(x_a) + H_a(x_b)] - [H_b(x_b) + H_a(x_a)]
791 = [H_b(x_a) - H_a(x_a)] + [H_a(x_b) - H_b(x_b)]
792 = de[b][a] + de[a][b] */
795 ediff = E_new - E_old
796 = [H_bp(x_a) + H_ap(x_b)] - [H_bp(x_b) + H_ap(x_a)]
797 = [H_bp(x_a) - H_ap(x_a)] + [H_ap(x_b) - H_bp(x_b)]
798 = [H_bp(x_a) - H_a(x_a) + H_a(x_a) - H_ap(x_a)] + [H_ap(x_b) - H_b(x_b) + H_b(x_b) - H_bp(x_b)]
799 = [H_bp(x_a) - H_a(x_a)] - [H_ap(x_a) - H_a(x_a)] + [H_ap(x_b) - H_b(x_b)] - H_bp(x_b) - H_b(x_b)]
800 = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]) */
801 /* but, in the current code implementation, we flip configurations, not indices . . .
802 So let's examine that.
803 = [H_b(x_ap) - H_a(x_a)] - [H_a(x_ap) - H_a(x_a)] + [H_a(x_bp) - H_b(x_b)] - H_b(x_bp) - H_b(x_b)]
804 = [H_b(x_ap) - H_a(x_ap)] + [H_a(x_bp) - H_b(x_pb)]
805 = (de[b][ap] - de[a][ap]) + (de[a][bp] - de[b][bp]
806 So, if we exchange b<=> bp and a<=> ap, we return to the same result.
807 So the simple solution is to flip the
808 position of perturbed and original indices in the tests.
811 ediff = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]);
812 delta = ediff * beta[a]; /* assume all same temperature in this case */
814 case ReplicaExchangeType::TemperatureLambda:
816 /* delta = reduced E_new - reduced E_old
817 = [beta_b H_b(x_a) + beta_a H_a(x_b)] - [beta_b H_b(x_b) + beta_a H_a(x_a)]
818 = [beta_b H_b(x_a) - beta_a H_a(x_a)] + [beta_a H_a(x_b) - beta_b H_b(x_b)]
819 = [beta_b dH_b(x_a) + beta_b H_a(x_a) - beta_a H_a(x_a)] +
820 [beta_a dH_a(x_b) + beta_a H_b(x_b) - beta_b H_b(x_b)]
821 = [beta_b dH_b(x_a) + [beta_a dH_a(x_b) +
822 beta_b (H_a(x_a) - H_b(x_b)]) - beta_a (H_a(x_a) - H_b(x_b))
823 = beta_b dH_b(x_a) + beta_a dH_a(x_b) - (beta_b - beta_a)(H_b(x_b) - H_a(x_a) */
824 /* delta = beta[b]*de[b][a] + beta[a]*de[a][b] - (beta[b] - beta[a])*(Epot[b] - Epot[a]; */
825 /* permuted (big breath!) */
826 /* delta = reduced E_new - reduced E_old
827 = [beta_bp H_bp(x_a) + beta_ap H_ap(x_b)] - [beta_bp H_bp(x_b) + beta_ap H_ap(x_a)]
828 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
829 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
830 - beta_pb H_a(x_a) + beta_ap H_a(x_a) + beta_pb H_a(x_a) - beta_ap H_a(x_a)
831 - beta_ap H_b(x_b) + beta_bp H_b(x_b) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
832 = [(beta_bp H_bp(x_a) - beta_bp H_a(x_a)) - (beta_ap H_ap(x_a) - beta_ap H_a(x_a))] +
833 [(beta_ap H_ap(x_b) - beta_ap H_b(x_b)) - (beta_bp H_bp(x_b) - beta_bp H_b(x_b))]
834 + beta_pb H_a(x_a) - beta_ap H_a(x_a) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
835 = [beta_bp (H_bp(x_a) - H_a(x_a)) - beta_ap (H_ap(x_a) - H_a(x_a))] +
836 [beta_ap (H_ap(x_b) - H_b(x_b)) - beta_bp (H_bp(x_b) - H_b(x_b))]
837 + beta_pb (H_a(x_a) - H_b(x_b)) - beta_ap (H_a(x_a) - H_b(x_b))
838 = ([beta_bp de[bp][a] - beta_ap de[ap][a]) + beta_ap de[ap][b] - beta_bp de[bp][b])
839 + (beta_pb-beta_ap)(H_a(x_a) - H_b(x_b)) */
840 delta = beta[bp] * (de[bp][a] - de[bp][b]) + beta[ap] * (de[ap][b] - de[ap][a])
841 - (beta[bp] - beta[ap]) * (Epot[b] - Epot[a]);
843 default: gmx_incons("Unknown replica exchange quantity");
847 fprintf(fplog, "Repl %d <-> %d dE_term = %10.3e (kT)\n", a, b, delta);
851 /* revist the calculation for 5.0. Might be some improvements. */
852 dpV = (beta[ap] * re->pres[ap] - beta[bp] * re->pres[bp]) * (Vol[b] - Vol[a]) / gmx::c_presfac;
855 fprintf(fplog, " dpV = %10.3e d = %10.3e\n", dpV, delta + dpV);
862 static void test_for_replica_exchange(FILE* fplog,
863 const gmx_multisim_t* ms,
864 struct gmx_repl_ex* re,
865 const gmx_enerdata_t* enerd,
870 int m, i, j, a, b, ap, bp, i0, i1, tmp;
872 gmx_bool bPrint, bMultiEx;
873 gmx_bool* bEx = re->bEx;
874 real* prob = re->prob;
875 int* pind = re->destinations; /* permuted index */
876 gmx_bool bEpot = FALSE;
877 gmx_bool bDLambda = FALSE;
878 gmx_bool bVol = FALSE;
879 gmx::ThreeFry2x64<64> rng(re->seed, gmx::RandomDomain::ReplicaExchange);
880 gmx::UniformRealDistribution<real> uniformRealDist;
881 gmx::UniformIntDistribution<int> uniformNreplDist(0, re->nrepl - 1);
883 bMultiEx = (re->nex > 1); /* multiple exchanges at each state */
884 fprintf(fplog, "Replica exchange at step %" PRId64 " time %.5f\n", step, time);
888 for (i = 0; i < re->nrepl; i++)
893 re->Vol[re->repl] = vol;
895 if ((re->type == ReplicaExchangeType::Temperature || re->type == ReplicaExchangeType::TemperatureLambda))
897 for (i = 0; i < re->nrepl; i++)
902 re->Epot[re->repl] = enerd->term[F_EPOT];
903 /* temperatures of different states*/
904 for (i = 0; i < re->nrepl; i++)
906 re->beta[i] = 1.0 / (re->q[ReplicaExchangeType::Temperature][i] * gmx::c_boltz);
911 for (i = 0; i < re->nrepl; i++)
913 re->beta[i] = 1.0 / (re->temp * gmx::c_boltz); /* we have a single temperature */
916 if (re->type == ReplicaExchangeType::Lambda || re->type == ReplicaExchangeType::TemperatureLambda)
919 /* lambda differences. */
920 /* de[i][j] is the energy of the jth simulation in the ith Hamiltonian
921 minus the energy of the jth simulation in the jth Hamiltonian */
922 for (i = 0; i < re->nrepl; i++)
924 for (j = 0; j < re->nrepl; j++)
929 for (i = 0; i < re->nrepl; i++)
931 re->de[i][re->repl] =
932 enerd->foreignLambdaTerms.deltaH(re->q[ReplicaExchangeType::Lambda][i]);
936 /* now actually do the communication */
939 gmx_sum_sim(re->nrepl, re->Vol, ms);
943 gmx_sum_sim(re->nrepl, re->Epot, ms);
947 for (i = 0; i < re->nrepl; i++)
949 gmx_sum_sim(re->nrepl, re->de[i], ms);
953 /* make a duplicate set of indices for shuffling */
954 for (i = 0; i < re->nrepl; i++)
956 pind[i] = re->ind[i];
959 rng.restart(step, 0);
963 /* multiple random switch exchange */
967 for (i = 0; i < re->nex + nself; i++)
969 // For now this is superfluous, but just in case we ever add more
970 // calls in different branches it is safer to always reset the distribution.
971 uniformNreplDist.reset();
973 /* randomly select a pair */
974 /* in theory, could reduce this by identifying only which switches had a nonneglibible
975 probability of occurring (log p > -100) and only operate on those switches */
976 /* find out which state it is from, and what label that state currently has. Likely
977 more work that useful. */
978 i0 = uniformNreplDist(rng);
979 i1 = uniformNreplDist(rng);
983 continue; /* self-exchange, back up and do it again */
986 a = re->ind[i0]; /* what are the indices of these states? */
991 bPrint = FALSE; /* too noisy */
992 /* calculate the energy difference */
993 /* if the code changes to flip the STATES, rather than the configurations,
994 use the commented version of the code */
995 /* delta = calc_delta(fplog,bPrint,re,a,b,ap,bp); */
996 delta = calc_delta(fplog, bPrint, re, ap, bp, a, b);
998 /* we actually only use the first space in the prob and bEx array,
999 since there are actually many switches between pairs. */
1009 if (delta > c_probabilityCutoff)
1015 prob[0] = exp(-delta);
1017 // roll a number to determine if accepted. For now it is superfluous to
1018 // reset, but just in case we ever add more calls in different branches
1019 // it is safer to always reset the distribution.
1020 uniformRealDist.reset();
1021 bEx[0] = uniformRealDist(rng) < prob[0];
1023 re->prob_sum[0] += prob[0];
1027 /* swap the states */
1029 pind[i0] = pind[i1];
1033 re->nattempt[0]++; /* keep track of total permutation trials here */
1034 print_allswitchind(fplog, re->nrepl, pind, re->allswaps, re->tmpswap);
1038 /* standard nearest neighbor replica exchange */
1040 m = (step / re->nst) % 2;
1041 for (i = 1; i < re->nrepl; i++)
1046 bPrint = (re->repl == a || re->repl == b);
1049 delta = calc_delta(fplog, bPrint, re, a, b, a, b);
1058 if (delta > c_probabilityCutoff)
1064 prob[i] = exp(-delta);
1066 // roll a number to determine if accepted. For now it is superfluous to
1067 // reset, but just in case we ever add more calls in different branches
1068 // it is safer to always reset the distribution.
1069 uniformRealDist.reset();
1070 bEx[i] = uniformRealDist(rng) < prob[i];
1072 re->prob_sum[i] += prob[i];
1076 /* swap these two */
1078 pind[i - 1] = pind[i];
1080 re->nexchange[i]++; /* statistics for back compatibility */
1089 /* print some statistics */
1090 print_ind(fplog, "ex", re->nrepl, re->ind, bEx);
1091 print_prob(fplog, "pr", re->nrepl, prob);
1092 fprintf(fplog, "\n");
1096 /* record which moves were made and accepted */
1097 for (i = 0; i < re->nrepl; i++)
1099 re->nmoves[re->ind[i]][pind[i]] += 1;
1100 re->nmoves[pind[i]][re->ind[i]] += 1;
1102 fflush(fplog); /* make sure we can see what the last exchange was */
1105 static void cyclic_decomposition(const int* destinations, int** cyclic, gmx_bool* incycle, const int nrepl, int* nswap)
1110 for (i = 0; i < nrepl; i++)
1114 for (i = 0; i < nrepl; i++) /* one cycle for each replica */
1125 for (j = 0; j < nrepl; j++) /* potentially all cycles are part, but we will break first */
1127 p = destinations[p]; /* start permuting */
1135 break; /* we've reached the original element, the cycle is complete, and we marked the end. */
1139 cyclic[i][c] = p; /* each permutation gives a new member of the cycle */
1145 *nswap = maxlen - 1;
1149 for (i = 0; i < nrepl; i++)
1151 fprintf(debug, "Cycle %d:", i);
1152 for (j = 0; j < nrepl; j++)
1154 if (cyclic[i][j] < 0)
1158 fprintf(debug, "%2d", cyclic[i][j]);
1160 fprintf(debug, "\n");
1166 static void compute_exchange_order(int** cyclic, int** order, const int nrepl, const int maxswap)
1170 for (j = 0; j < maxswap; j++)
1172 for (i = 0; i < nrepl; i++)
1174 if (cyclic[i][j + 1] >= 0)
1176 order[cyclic[i][j + 1]][j] = cyclic[i][j];
1177 order[cyclic[i][j]][j] = cyclic[i][j + 1];
1180 for (i = 0; i < nrepl; i++)
1182 if (order[i][j] < 0)
1184 order[i][j] = i; /* if it's not exchanging, it should stay this round*/
1191 fprintf(debug, "Replica Exchange Order\n");
1192 for (i = 0; i < nrepl; i++)
1194 fprintf(debug, "Replica %d:", i);
1195 for (j = 0; j < maxswap; j++)
1197 if (order[i][j] < 0)
1201 fprintf(debug, "%2d", order[i][j]);
1203 fprintf(debug, "\n");
1209 static void prepare_to_do_exchange(struct gmx_repl_ex* re, const int replica_id, int* maxswap, gmx_bool* bThisReplicaExchanged)
1212 /* Hold the cyclic decomposition of the (multiple) replica
1214 gmx_bool bAnyReplicaExchanged = FALSE;
1215 *bThisReplicaExchanged = FALSE;
1217 for (i = 0; i < re->nrepl; i++)
1219 if (re->destinations[i] != re->ind[i])
1221 /* only mark as exchanged if the index has been shuffled */
1222 bAnyReplicaExchanged = TRUE;
1226 if (bAnyReplicaExchanged)
1228 /* reinitialize the placeholder arrays */
1229 for (i = 0; i < re->nrepl; i++)
1231 for (j = 0; j < re->nrepl; j++)
1233 re->cyclic[i][j] = -1;
1234 re->order[i][j] = -1;
1238 /* Identify the cyclic decomposition of the permutation (very
1239 * fast if neighbor replica exchange). */
1240 cyclic_decomposition(re->destinations, re->cyclic, re->incycle, re->nrepl, maxswap);
1242 /* Now translate the decomposition into a replica exchange
1243 * order at each step. */
1244 compute_exchange_order(re->cyclic, re->order, re->nrepl, *maxswap);
1246 /* Did this replica do any exchange at any point? */
1247 for (j = 0; j < *maxswap; j++)
1249 if (replica_id != re->order[replica_id][j])
1251 *bThisReplicaExchanged = TRUE;
1258 gmx_bool replica_exchange(FILE* fplog,
1259 const t_commrec* cr,
1260 const gmx_multisim_t* ms,
1261 struct gmx_repl_ex* re,
1263 const gmx_enerdata_t* enerd,
1264 t_state* state_local,
1270 int exchange_partner;
1272 /* Number of rounds of exchanges needed to deal with any multiple
1274 /* Where each replica ends up after the exchange attempt(s). */
1275 /* The order in which multiple exchanges will occur. */
1276 gmx_bool bThisReplicaExchanged = FALSE;
1280 replica_id = re->repl;
1281 test_for_replica_exchange(fplog, ms, re, enerd, det(state_local->box), step, time);
1282 prepare_to_do_exchange(re, replica_id, &maxswap, &bThisReplicaExchanged);
1284 /* Do intra-simulation broadcast so all processors belonging to
1285 * each simulation know whether they need to participate in
1286 * collecting the state. Otherwise, they might as well get on with
1287 * the next thing to do. */
1288 if (DOMAINDECOMP(cr))
1291 MPI_Bcast(&bThisReplicaExchanged, sizeof(gmx_bool), MPI_BYTE, MASTERRANK(cr), cr->mpi_comm_mygroup);
1295 if (bThisReplicaExchanged)
1297 /* Exchange the states */
1298 /* Collect the global state on the master node */
1299 if (DOMAINDECOMP(cr))
1301 dd_collect_state(cr->dd, state_local, state);
1305 copy_state_serial(state_local, state);
1310 /* There will be only one swap cycle with standard replica
1311 * exchange, but there may be multiple swap cycles if we
1312 * allow multiple swaps. */
1314 for (j = 0; j < maxswap; j++)
1316 exchange_partner = re->order[replica_id][j];
1318 if (exchange_partner != replica_id)
1320 /* Exchange the global states between the master nodes */
1323 fprintf(debug, "Exchanging %d with %d\n", replica_id, exchange_partner);
1325 exchange_state(ms, exchange_partner, state);
1328 /* For temperature-type replica exchange, we need to scale
1329 * the velocities. */
1330 if (re->type == ReplicaExchangeType::Temperature || re->type == ReplicaExchangeType::TemperatureLambda)
1334 std::sqrt(re->q[ReplicaExchangeType::Temperature][replica_id]
1335 / re->q[ReplicaExchangeType::Temperature][re->destinations[replica_id]]));
1339 /* With domain decomposition the global state is distributed later */
1340 if (!DOMAINDECOMP(cr))
1342 /* Copy the global state to the local state data structure */
1343 copy_state_serial(state, state_local);
1347 return bThisReplicaExchanged;
1350 void print_replica_exchange_statistics(FILE* fplog, struct gmx_repl_ex* re)
1354 fprintf(fplog, "\nReplica exchange statistics\n");
1359 "Repl %d attempts, %d odd, %d even\n",
1360 re->nattempt[0] + re->nattempt[1],
1364 fprintf(fplog, "Repl average probabilities:\n");
1365 for (i = 1; i < re->nrepl; i++)
1367 if (re->nattempt[i % 2] == 0)
1373 re->prob[i] = re->prob_sum[i] / re->nattempt[i % 2];
1376 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1377 print_prob(fplog, "", re->nrepl, re->prob);
1379 fprintf(fplog, "Repl number of exchanges:\n");
1380 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1381 print_count(fplog, "", re->nrepl, re->nexchange);
1383 fprintf(fplog, "Repl average number of exchanges:\n");
1384 for (i = 1; i < re->nrepl; i++)
1386 if (re->nattempt[i % 2] == 0)
1392 re->prob[i] = (static_cast<real>(re->nexchange[i])) / re->nattempt[i % 2];
1395 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1396 print_prob(fplog, "", re->nrepl, re->prob);
1398 fprintf(fplog, "\n");
1400 /* print the transition matrix */
1401 print_transition_matrix(fplog, re->nrepl, re->nmoves, re->nattempt);