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, 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/fatalerror.h"
70 #include "gromacs/utility/pleasecite.h"
71 #include "gromacs/utility/smalloc.h"
73 //! Helps cut off probability values.
74 constexpr int c_probabilityCutoff = 100;
76 /* we don't bother evaluating if events are more rare than exp(-100) = 3.7x10^-44 */
78 //! Rank in the multisimulation
79 #define MSRANK(ms, nodeid) (nodeid)
81 //! Enum for replica exchange flavours
90 /*! \brief Strings describing replica exchange flavours.
92 * end_single_marker merely notes the end of single variable replica
93 * exchange. All types higher than it are multiple replica exchange
96 * Eventually, should add 'pressure', 'temperature and pressure',
97 * 'lambda_and_pressure', 'temperature_lambda_pressure'?; Let's wait
98 * until we feel better about the pressure control methods giving
99 * exact ensembles. Right now, we assume constant pressure */
100 static const char* erename[ereNR] = { "temperature", "lambda", "end_single_marker",
101 "temperature and lambda" };
103 //! Working data for replica exchange.
108 //! Total number of replica
112 //! Replica exchange type from ere enum
114 //! Quantity, e.g. temperature or lambda; first index is ere, second index is replica ID
116 //! Use constant pressure and temperature
118 //! Replica pressures
122 //! Used for keeping track of all the replica swaps
124 //! Replica exchange interval (number of steps)
126 //! Number of exchanges per interval
130 //! Number of even and odd replica change attempts
132 //! Sum of probabilities
134 //! Number of moves between replicas i and j
136 //! i-th element of the array is the number of exchanges between replica i-1 and i
139 /*! \brief Helper arrays for replica exchange; allocated here
140 * so they don't have to be allocated each time */
150 //! Helper arrays to hold the quantities that are exchanged.
160 // TODO We should add Doxygen here some time.
163 static gmx_bool repl_quantity(const gmx_multisim_t* ms, struct gmx_repl_ex* re, int ere, real q)
169 snew(qall, ms->nsim);
171 gmx_sum_sim(ms->nsim, qall, ms);
174 for (s = 1; s < ms->nsim; s++)
176 if (qall[s] != qall[0])
184 /* Set the replica exchange type and quantities */
187 snew(re->q[ere], re->nrepl);
188 for (s = 0; s < ms->nsim; s++)
190 re->q[ere][s] = qall[s];
197 gmx_repl_ex_t init_replica_exchange(FILE* fplog,
198 const gmx_multisim_t* ms,
199 int numAtomsInSystem,
200 const t_inputrec* ir,
201 const ReplicaExchangeParameters& replExParams)
205 struct gmx_repl_ex* re;
207 gmx_bool bLambda = FALSE;
209 fprintf(fplog, "\nInitializing Replica Exchange\n");
211 if (!isMultiSim(ms) || ms->nsim == 1)
214 "Nothing to exchange with only one replica, maybe you forgot to set the "
215 "-multidir option of mdrun?");
217 if (replExParams.numExchanges < 0)
219 gmx_fatal(FARGS, "Replica exchange number of exchanges needs to be positive");
222 if (!EI_DYNAMICS(ir->eI))
224 gmx_fatal(FARGS, "Replica exchange is only supported by dynamical simulations");
225 /* Note that PAR(cr) is defined by cr->nnodes > 1, which is
226 * distinct from isMultiSim(ms). A multi-simulation only runs
227 * with real MPI parallelism, but this does not imply PAR(cr)
230 * Since we are using a dynamical integrator, the only
231 * decomposition is DD, so PAR(cr) and DOMAINDECOMP(cr) are
232 * synonymous. The only way for cr->nnodes > 1 to be true is
233 * if we are using DD. */
239 re->nrepl = ms->nsim;
240 snew(re->q, ereENDSINGLE);
242 fprintf(fplog, "Repl There are %d replicas:\n", re->nrepl);
244 /* We only check that the number of atoms in the systms match.
245 * This, of course, do not guarantee that the systems are the same,
246 * but it does guarantee that we can perform replica exchange.
248 check_multi_int(fplog, ms, numAtomsInSystem, "the number of atoms", FALSE);
249 check_multi_int(fplog, ms, ir->eI, "the integrator", FALSE);
250 check_multi_int64(fplog, ms, ir->init_step + ir->nsteps, "init_step+nsteps", FALSE);
251 const int nst = replExParams.exchangeInterval;
252 check_multi_int64(fplog, ms, (ir->init_step + nst - 1) / nst,
253 "first exchange step: init_step/-replex", FALSE);
254 check_multi_int(fplog, ms, ir->etc, "the temperature coupling", FALSE);
255 check_multi_int(fplog, ms, ir->opts.ngtc, "the number of temperature coupling groups", FALSE);
256 check_multi_int(fplog, ms, ir->epc, "the pressure coupling", FALSE);
257 check_multi_int(fplog, ms, ir->efep, "free energy", FALSE);
258 check_multi_int(fplog, ms, ir->fepvals->n_lambda, "number of lambda states", FALSE);
260 re->temp = ir->opts.ref_t[0];
261 for (i = 1; (i < ir->opts.ngtc); i++)
263 if (ir->opts.ref_t[i] != re->temp)
266 "\nWARNING: The temperatures of the different temperature coupling groups are "
267 "not identical\n\n");
269 "\nWARNING: The temperatures of the different temperature coupling groups are "
270 "not identical\n\n");
275 bTemp = repl_quantity(ms, re, ereTEMP, re->temp);
276 if (ir->efep != efepNO)
278 bLambda = repl_quantity(ms, re, ereLAMBDA, static_cast<real>(ir->fepvals->init_fep_state));
280 if (re->type == -1) /* nothing was assigned */
283 "The properties of the %d systems are all the same, there is nothing to exchange",
286 if (bLambda && bTemp)
293 please_cite(fplog, "Sugita1999a");
294 if (ir->epc != epcNO)
297 fprintf(fplog, "Repl Using Constant Pressure REMD.\n");
298 please_cite(fplog, "Okabe2001a");
300 if (ir->etc == etcBERENDSEN)
303 "REMD with the %s thermostat does not produce correct potential energy "
304 "distributions, consider using the %s thermostat instead",
305 ETCOUPLTYPE(ir->etc), ETCOUPLTYPE(etcVRESCALE));
310 if (ir->fepvals->delta_lambda != 0) /* check this? */
312 gmx_fatal(FARGS, "delta_lambda is not zero");
317 snew(re->pres, re->nrepl);
318 if (ir->epct == epctSURFACETENSION)
320 pres = ir->ref_p[ZZ][ZZ];
326 for (i = 0; i < DIM; i++)
328 if (ir->compress[i][i] != 0)
330 pres += ir->ref_p[i][i];
336 re->pres[re->repl] = pres;
337 gmx_sum_sim(re->nrepl, re->pres, ms);
340 /* Make an index for increasing replica order */
341 /* only makes sense if one or the other is varying, not both!
342 if both are varying, we trust the order the person gave. */
343 snew(re->ind, re->nrepl);
344 for (i = 0; i < re->nrepl; i++)
349 if (re->type < ereENDSINGLE)
352 for (i = 0; i < re->nrepl; i++)
354 for (j = i + 1; j < re->nrepl; j++)
356 if (re->q[re->type][re->ind[j]] < re->q[re->type][re->ind[i]])
358 /* Unordered replicas are supposed to work, but there
359 * is still an issues somewhere.
360 * Note that at this point still re->ind[i]=i.
363 "Replicas with indices %d < %d have %ss %g > %g, please order your "
364 "replicas on increasing %s",
365 i, j, erename[re->type], re->q[re->type][i], re->q[re->type][j],
368 else if (re->q[re->type][re->ind[j]] == re->q[re->type][re->ind[i]])
370 gmx_fatal(FARGS, "Two replicas have identical %ss", erename[re->type]);
376 /* keep track of all the swaps, starting with the initial placement. */
377 snew(re->allswaps, re->nrepl);
378 for (i = 0; i < re->nrepl; i++)
380 re->allswaps[i] = re->ind[i];
386 fprintf(fplog, "\nReplica exchange in temperature\n");
387 for (i = 0; i < re->nrepl; i++)
389 fprintf(fplog, " %5.1f", re->q[re->type][re->ind[i]]);
391 fprintf(fplog, "\n");
394 fprintf(fplog, "\nReplica exchange in lambda\n");
395 for (i = 0; i < re->nrepl; i++)
397 fprintf(fplog, " %3d", static_cast<int>(re->q[re->type][re->ind[i]]));
399 fprintf(fplog, "\n");
402 fprintf(fplog, "\nReplica exchange in temperature and lambda state\n");
403 for (i = 0; i < re->nrepl; i++)
405 fprintf(fplog, " %5.1f", re->q[ereTEMP][re->ind[i]]);
407 fprintf(fplog, "\n");
408 for (i = 0; i < re->nrepl; i++)
410 fprintf(fplog, " %5d", static_cast<int>(re->q[ereLAMBDA][re->ind[i]]));
412 fprintf(fplog, "\n");
414 default: gmx_incons("Unknown replica exchange quantity");
418 fprintf(fplog, "\nRepl p");
419 for (i = 0; i < re->nrepl; i++)
421 fprintf(fplog, " %5.2f", re->pres[re->ind[i]]);
424 for (i = 0; i < re->nrepl; i++)
426 if ((i > 0) && (re->pres[re->ind[i]] < re->pres[re->ind[i - 1]]))
429 "\nWARNING: The reference pressures decrease with increasing "
432 "\nWARNING: The reference pressures decrease with increasing "
438 if (replExParams.randomSeed == -1)
442 re->seed = static_cast<int>(gmx::makeRandomSeed());
448 gmx_sumi_sim(1, &(re->seed), ms);
452 re->seed = replExParams.randomSeed;
454 fprintf(fplog, "\nReplica exchange interval: %d\n", re->nst);
455 fprintf(fplog, "\nReplica random seed: %d\n", re->seed);
460 snew(re->prob_sum, re->nrepl);
461 snew(re->nexchange, re->nrepl);
462 snew(re->nmoves, re->nrepl);
463 for (i = 0; i < re->nrepl; i++)
465 snew(re->nmoves[i], re->nrepl);
467 fprintf(fplog, "Replica exchange information below: ex and x = exchange, pr = probability\n");
469 /* generate space for the helper functions so we don't have to snew each time */
471 snew(re->destinations, re->nrepl);
472 snew(re->incycle, re->nrepl);
473 snew(re->tmpswap, re->nrepl);
474 snew(re->cyclic, re->nrepl);
475 snew(re->order, re->nrepl);
476 for (i = 0; i < re->nrepl; i++)
478 snew(re->cyclic[i], re->nrepl + 1);
479 snew(re->order[i], re->nrepl);
481 /* allocate space for the functions storing the data for the replicas */
482 /* not all of these arrays needed in all cases, but they don't take
483 up much space, since the max size is nrepl**2 */
484 snew(re->prob, re->nrepl);
485 snew(re->bEx, re->nrepl);
486 snew(re->beta, re->nrepl);
487 snew(re->Vol, re->nrepl);
488 snew(re->Epot, re->nrepl);
489 snew(re->de, re->nrepl);
490 for (i = 0; i < re->nrepl; i++)
492 snew(re->de[i], re->nrepl);
494 re->nex = replExParams.numExchanges;
498 static void exchange_reals(const gmx_multisim_t gmx_unused* ms, int gmx_unused b, real* v, int n)
508 MPI_Sendrecv(v, n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
509 buf,n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
510 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
515 MPI_Isend(v, n * sizeof(real), MPI_BYTE, MSRANK(ms, b), 0, ms->mpi_comm_masters, &mpi_req);
516 MPI_Recv(buf, n * sizeof(real), MPI_BYTE, MSRANK(ms, b), 0, ms->mpi_comm_masters,
518 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
521 for (i = 0; i < n; i++)
530 static void exchange_doubles(const gmx_multisim_t gmx_unused* ms, int gmx_unused b, double* v, int n)
540 MPI_Sendrecv(v, n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
541 buf,n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
542 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
547 MPI_Isend(v, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mpi_comm_masters, &mpi_req);
548 MPI_Recv(buf, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mpi_comm_masters,
550 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
553 for (i = 0; i < n; i++)
561 static void exchange_rvecs(const gmx_multisim_t gmx_unused* ms, int gmx_unused b, rvec* v, int n)
571 MPI_Sendrecv(v[0], n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
572 buf[0],n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
573 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
578 MPI_Isend(v[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mpi_comm_masters, &mpi_req);
579 MPI_Recv(buf[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mpi_comm_masters,
581 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
584 for (i = 0; i < n; i++)
586 copy_rvec(buf[i], v[i]);
592 static void exchange_state(const gmx_multisim_t* ms, int b, t_state* state)
594 /* When t_state changes, this code should be updated. */
596 ngtc = state->ngtc * state->nhchainlength;
597 nnhpres = state->nnhpres * state->nhchainlength;
598 exchange_rvecs(ms, b, state->box, DIM);
599 exchange_rvecs(ms, b, state->box_rel, DIM);
600 exchange_rvecs(ms, b, state->boxv, DIM);
601 exchange_reals(ms, b, &(state->veta), 1);
602 exchange_reals(ms, b, &(state->vol0), 1);
603 exchange_rvecs(ms, b, state->svir_prev, DIM);
604 exchange_rvecs(ms, b, state->fvir_prev, DIM);
605 exchange_rvecs(ms, b, state->pres_prev, DIM);
606 exchange_doubles(ms, b, state->nosehoover_xi.data(), ngtc);
607 exchange_doubles(ms, b, state->nosehoover_vxi.data(), ngtc);
608 exchange_doubles(ms, b, state->nhpres_xi.data(), nnhpres);
609 exchange_doubles(ms, b, state->nhpres_vxi.data(), nnhpres);
610 exchange_doubles(ms, b, state->therm_integral.data(), state->ngtc);
611 exchange_doubles(ms, b, &state->baros_integral, 1);
612 exchange_rvecs(ms, b, state->x.rvec_array(), state->natoms);
613 exchange_rvecs(ms, b, state->v.rvec_array(), state->natoms);
616 static void copy_state_serial(const t_state* src, t_state* dest)
620 /* Currently the local state is always a pointer to the global
621 * in serial, so we should never end up here.
622 * TODO: Implement a (trivial) t_state copy once converted to C++.
624 GMX_RELEASE_ASSERT(false, "State copying is currently not implemented in replica exchange");
628 static void scale_velocities(gmx::ArrayRef<gmx::RVec> velocities, real fac)
630 for (auto& v : velocities)
636 static void print_transition_matrix(FILE* fplog, int n, int** nmoves, const int* nattempt)
641 ntot = nattempt[0] + nattempt[1];
642 fprintf(fplog, "\n");
643 fprintf(fplog, "Repl");
644 for (i = 0; i < n; i++)
646 fprintf(fplog, " "); /* put the title closer to the center */
648 fprintf(fplog, "Empirical Transition Matrix\n");
650 fprintf(fplog, "Repl");
651 for (i = 0; i < n; i++)
653 fprintf(fplog, "%8d", (i + 1));
655 fprintf(fplog, "\n");
657 for (i = 0; i < n; i++)
659 fprintf(fplog, "Repl");
660 for (j = 0; j < n; j++)
663 if (nmoves[i][j] > 0)
665 Tprint = nmoves[i][j] / (2.0 * ntot);
667 fprintf(fplog, "%8.4f", Tprint);
669 fprintf(fplog, "%3d\n", i);
673 static void print_ind(FILE* fplog, const char* leg, int n, int* ind, const gmx_bool* bEx)
677 fprintf(fplog, "Repl %2s %2d", leg, ind[0]);
678 for (i = 1; i < n; i++)
680 fprintf(fplog, " %c %2d", (bEx != nullptr && bEx[i]) ? 'x' : ' ', ind[i]);
682 fprintf(fplog, "\n");
685 static void print_allswitchind(FILE* fplog, int n, int* pind, int* allswaps, int* tmpswap)
689 for (i = 0; i < n; i++)
691 tmpswap[i] = allswaps[i];
693 for (i = 0; i < n; i++)
695 allswaps[i] = tmpswap[pind[i]];
698 fprintf(fplog, "\nAccepted Exchanges: ");
699 for (i = 0; i < n; i++)
701 fprintf(fplog, "%d ", pind[i]);
703 fprintf(fplog, "\n");
705 /* the "Order After Exchange" is the state label corresponding to the configuration that
706 started in state listed in order, i.e.
711 configuration starting in simulation 3 is now in simulation 0,
712 configuration starting in simulation 0 is now in simulation 1,
713 configuration starting in simulation 1 is now in simulation 2,
714 configuration starting in simulation 2 is now in simulation 3
716 fprintf(fplog, "Order After Exchange: ");
717 for (i = 0; i < n; i++)
719 fprintf(fplog, "%d ", allswaps[i]);
721 fprintf(fplog, "\n\n");
724 static void print_prob(FILE* fplog, const char* leg, int n, real* prob)
729 fprintf(fplog, "Repl %2s ", leg);
730 for (i = 1; i < n; i++)
734 sprintf(buf, "%4.2f", prob[i]);
735 fprintf(fplog, " %3s", buf[0] == '1' ? "1.0" : buf + 1);
742 fprintf(fplog, "\n");
745 static void print_count(FILE* fplog, const char* leg, int n, int* count)
749 fprintf(fplog, "Repl %2s ", leg);
750 for (i = 1; i < n; i++)
752 fprintf(fplog, " %4d", count[i]);
754 fprintf(fplog, "\n");
757 static real calc_delta(FILE* fplog, gmx_bool bPrint, struct gmx_repl_ex* re, int a, int b, int ap, int bp)
760 real ediff, dpV, delta = 0;
761 real* Epot = re->Epot;
764 real* beta = re->beta;
766 /* Two cases; we are permuted and not. In all cases, setting ap = a and bp = b will reduce
767 to the non permuted case */
773 * Okabe et. al. Chem. Phys. Lett. 335 (2001) 435-439
775 ediff = Epot[b] - Epot[a];
776 delta = -(beta[bp] - beta[ap]) * ediff;
779 /* two cases: when we are permuted, and not. */
781 ediff = E_new - E_old
782 = [H_b(x_a) + H_a(x_b)] - [H_b(x_b) + H_a(x_a)]
783 = [H_b(x_a) - H_a(x_a)] + [H_a(x_b) - H_b(x_b)]
784 = de[b][a] + de[a][b] */
787 ediff = E_new - E_old
788 = [H_bp(x_a) + H_ap(x_b)] - [H_bp(x_b) + H_ap(x_a)]
789 = [H_bp(x_a) - H_ap(x_a)] + [H_ap(x_b) - H_bp(x_b)]
790 = [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)]
791 = [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)]
792 = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]) */
793 /* but, in the current code implementation, we flip configurations, not indices . . .
794 So let's examine that.
795 = [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)]
796 = [H_b(x_ap) - H_a(x_ap)] + [H_a(x_bp) - H_b(x_pb)]
797 = (de[b][ap] - de[a][ap]) + (de[a][bp] - de[b][bp]
798 So, if we exchange b<=> bp and a<=> ap, we return to the same result.
799 So the simple solution is to flip the
800 position of perturbed and original indices in the tests.
803 ediff = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]);
804 delta = ediff * beta[a]; /* assume all same temperature in this case */
808 /* delta = reduced E_new - reduced E_old
809 = [beta_b H_b(x_a) + beta_a H_a(x_b)] - [beta_b H_b(x_b) + beta_a H_a(x_a)]
810 = [beta_b H_b(x_a) - beta_a H_a(x_a)] + [beta_a H_a(x_b) - beta_b H_b(x_b)]
811 = [beta_b dH_b(x_a) + beta_b H_a(x_a) - beta_a H_a(x_a)] +
812 [beta_a dH_a(x_b) + beta_a H_b(x_b) - beta_b H_b(x_b)]
813 = [beta_b dH_b(x_a) + [beta_a dH_a(x_b) +
814 beta_b (H_a(x_a) - H_b(x_b)]) - beta_a (H_a(x_a) - H_b(x_b))
815 = beta_b dH_b(x_a) + beta_a dH_a(x_b) - (beta_b - beta_a)(H_b(x_b) - H_a(x_a) */
816 /* delta = beta[b]*de[b][a] + beta[a]*de[a][b] - (beta[b] - beta[a])*(Epot[b] - Epot[a]; */
817 /* permuted (big breath!) */
818 /* delta = reduced E_new - reduced E_old
819 = [beta_bp H_bp(x_a) + beta_ap H_ap(x_b)] - [beta_bp H_bp(x_b) + beta_ap H_ap(x_a)]
820 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
821 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
822 - beta_pb H_a(x_a) + beta_ap H_a(x_a) + beta_pb H_a(x_a) - beta_ap H_a(x_a)
823 - beta_ap H_b(x_b) + beta_bp H_b(x_b) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
824 = [(beta_bp H_bp(x_a) - beta_bp H_a(x_a)) - (beta_ap H_ap(x_a) - beta_ap H_a(x_a))] +
825 [(beta_ap H_ap(x_b) - beta_ap H_b(x_b)) - (beta_bp H_bp(x_b) - beta_bp H_b(x_b))]
826 + beta_pb H_a(x_a) - beta_ap H_a(x_a) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
827 = [beta_bp (H_bp(x_a) - H_a(x_a)) - beta_ap (H_ap(x_a) - H_a(x_a))] +
828 [beta_ap (H_ap(x_b) - H_b(x_b)) - beta_bp (H_bp(x_b) - H_b(x_b))]
829 + beta_pb (H_a(x_a) - H_b(x_b)) - beta_ap (H_a(x_a) - H_b(x_b))
830 = ([beta_bp de[bp][a] - beta_ap de[ap][a]) + beta_ap de[ap][b] - beta_bp de[bp][b])
831 + (beta_pb-beta_ap)(H_a(x_a) - H_b(x_b)) */
832 delta = beta[bp] * (de[bp][a] - de[bp][b]) + beta[ap] * (de[ap][b] - de[ap][a])
833 - (beta[bp] - beta[ap]) * (Epot[b] - Epot[a]);
835 default: gmx_incons("Unknown replica exchange quantity");
839 fprintf(fplog, "Repl %d <-> %d dE_term = %10.3e (kT)\n", a, b, delta);
843 /* revist the calculation for 5.0. Might be some improvements. */
844 dpV = (beta[ap] * re->pres[ap] - beta[bp] * re->pres[bp]) * (Vol[b] - Vol[a]) / PRESFAC;
847 fprintf(fplog, " dpV = %10.3e d = %10.3e\n", dpV, delta + dpV);
854 static void test_for_replica_exchange(FILE* fplog,
855 const gmx_multisim_t* ms,
856 struct gmx_repl_ex* re,
857 const gmx_enerdata_t* enerd,
862 int m, i, j, a, b, ap, bp, i0, i1, tmp;
864 gmx_bool bPrint, bMultiEx;
865 gmx_bool* bEx = re->bEx;
866 real* prob = re->prob;
867 int* pind = re->destinations; /* permuted index */
868 gmx_bool bEpot = FALSE;
869 gmx_bool bDLambda = FALSE;
870 gmx_bool bVol = FALSE;
871 gmx::ThreeFry2x64<64> rng(re->seed, gmx::RandomDomain::ReplicaExchange);
872 gmx::UniformRealDistribution<real> uniformRealDist;
873 gmx::UniformIntDistribution<int> uniformNreplDist(0, re->nrepl - 1);
875 bMultiEx = (re->nex > 1); /* multiple exchanges at each state */
876 fprintf(fplog, "Replica exchange at step %" PRId64 " time %.5f\n", step, time);
880 for (i = 0; i < re->nrepl; i++)
885 re->Vol[re->repl] = vol;
887 if ((re->type == ereTEMP || re->type == ereTL))
889 for (i = 0; i < re->nrepl; i++)
894 re->Epot[re->repl] = enerd->term[F_EPOT];
895 /* temperatures of different states*/
896 for (i = 0; i < re->nrepl; i++)
898 re->beta[i] = 1.0 / (re->q[ereTEMP][i] * BOLTZ);
903 for (i = 0; i < re->nrepl; i++)
905 re->beta[i] = 1.0 / (re->temp * BOLTZ); /* we have a single temperature */
908 if (re->type == ereLAMBDA || re->type == ereTL)
911 /* lambda differences. */
912 /* de[i][j] is the energy of the jth simulation in the ith Hamiltonian
913 minus the energy of the jth simulation in the jth Hamiltonian */
914 for (i = 0; i < re->nrepl; i++)
916 for (j = 0; j < re->nrepl; j++)
921 for (i = 0; i < re->nrepl; i++)
923 re->de[i][re->repl] = (enerd->enerpart_lambda[static_cast<int>(re->q[ereLAMBDA][i]) + 1]
924 - enerd->enerpart_lambda[0]);
928 /* now actually do the communication */
931 gmx_sum_sim(re->nrepl, re->Vol, ms);
935 gmx_sum_sim(re->nrepl, re->Epot, ms);
939 for (i = 0; i < re->nrepl; i++)
941 gmx_sum_sim(re->nrepl, re->de[i], ms);
945 /* make a duplicate set of indices for shuffling */
946 for (i = 0; i < re->nrepl; i++)
948 pind[i] = re->ind[i];
951 rng.restart(step, 0);
955 /* multiple random switch exchange */
959 for (i = 0; i < re->nex + nself; i++)
961 // For now this is superfluous, but just in case we ever add more
962 // calls in different branches it is safer to always reset the distribution.
963 uniformNreplDist.reset();
965 /* randomly select a pair */
966 /* in theory, could reduce this by identifying only which switches had a nonneglibible
967 probability of occurring (log p > -100) and only operate on those switches */
968 /* find out which state it is from, and what label that state currently has. Likely
969 more work that useful. */
970 i0 = uniformNreplDist(rng);
971 i1 = uniformNreplDist(rng);
975 continue; /* self-exchange, back up and do it again */
978 a = re->ind[i0]; /* what are the indices of these states? */
983 bPrint = FALSE; /* too noisy */
984 /* calculate the energy difference */
985 /* if the code changes to flip the STATES, rather than the configurations,
986 use the commented version of the code */
987 /* delta = calc_delta(fplog,bPrint,re,a,b,ap,bp); */
988 delta = calc_delta(fplog, bPrint, re, ap, bp, a, b);
990 /* we actually only use the first space in the prob and bEx array,
991 since there are actually many switches between pairs. */
1001 if (delta > c_probabilityCutoff)
1007 prob[0] = exp(-delta);
1009 // roll a number to determine if accepted. For now it is superfluous to
1010 // reset, but just in case we ever add more calls in different branches
1011 // it is safer to always reset the distribution.
1012 uniformRealDist.reset();
1013 bEx[0] = uniformRealDist(rng) < prob[0];
1015 re->prob_sum[0] += prob[0];
1019 /* swap the states */
1021 pind[i0] = pind[i1];
1025 re->nattempt[0]++; /* keep track of total permutation trials here */
1026 print_allswitchind(fplog, re->nrepl, pind, re->allswaps, re->tmpswap);
1030 /* standard nearest neighbor replica exchange */
1032 m = (step / re->nst) % 2;
1033 for (i = 1; i < re->nrepl; i++)
1038 bPrint = (re->repl == a || re->repl == b);
1041 delta = calc_delta(fplog, bPrint, re, a, b, a, b);
1050 if (delta > c_probabilityCutoff)
1056 prob[i] = exp(-delta);
1058 // roll a number to determine if accepted. For now it is superfluous to
1059 // reset, but just in case we ever add more calls in different branches
1060 // it is safer to always reset the distribution.
1061 uniformRealDist.reset();
1062 bEx[i] = uniformRealDist(rng) < prob[i];
1064 re->prob_sum[i] += prob[i];
1068 /* swap these two */
1070 pind[i - 1] = pind[i];
1072 re->nexchange[i]++; /* statistics for back compatibility */
1081 /* print some statistics */
1082 print_ind(fplog, "ex", re->nrepl, re->ind, bEx);
1083 print_prob(fplog, "pr", re->nrepl, prob);
1084 fprintf(fplog, "\n");
1088 /* record which moves were made and accepted */
1089 for (i = 0; i < re->nrepl; i++)
1091 re->nmoves[re->ind[i]][pind[i]] += 1;
1092 re->nmoves[pind[i]][re->ind[i]] += 1;
1094 fflush(fplog); /* make sure we can see what the last exchange was */
1097 static void cyclic_decomposition(const int* destinations, int** cyclic, gmx_bool* incycle, const int nrepl, int* nswap)
1102 for (i = 0; i < nrepl; i++)
1106 for (i = 0; i < nrepl; i++) /* one cycle for each replica */
1117 for (j = 0; j < nrepl; j++) /* potentially all cycles are part, but we will break first */
1119 p = destinations[p]; /* start permuting */
1127 break; /* we've reached the original element, the cycle is complete, and we marked the end. */
1131 cyclic[i][c] = p; /* each permutation gives a new member of the cycle */
1137 *nswap = maxlen - 1;
1141 for (i = 0; i < nrepl; i++)
1143 fprintf(debug, "Cycle %d:", i);
1144 for (j = 0; j < nrepl; j++)
1146 if (cyclic[i][j] < 0)
1150 fprintf(debug, "%2d", cyclic[i][j]);
1152 fprintf(debug, "\n");
1158 static void compute_exchange_order(int** cyclic, int** order, const int nrepl, const int maxswap)
1162 for (j = 0; j < maxswap; j++)
1164 for (i = 0; i < nrepl; i++)
1166 if (cyclic[i][j + 1] >= 0)
1168 order[cyclic[i][j + 1]][j] = cyclic[i][j];
1169 order[cyclic[i][j]][j] = cyclic[i][j + 1];
1172 for (i = 0; i < nrepl; i++)
1174 if (order[i][j] < 0)
1176 order[i][j] = i; /* if it's not exchanging, it should stay this round*/
1183 fprintf(debug, "Replica Exchange Order\n");
1184 for (i = 0; i < nrepl; i++)
1186 fprintf(debug, "Replica %d:", i);
1187 for (j = 0; j < maxswap; j++)
1189 if (order[i][j] < 0)
1193 fprintf(debug, "%2d", order[i][j]);
1195 fprintf(debug, "\n");
1201 static void prepare_to_do_exchange(struct gmx_repl_ex* re, const int replica_id, int* maxswap, gmx_bool* bThisReplicaExchanged)
1204 /* Hold the cyclic decomposition of the (multiple) replica
1206 gmx_bool bAnyReplicaExchanged = FALSE;
1207 *bThisReplicaExchanged = FALSE;
1209 for (i = 0; i < re->nrepl; i++)
1211 if (re->destinations[i] != re->ind[i])
1213 /* only mark as exchanged if the index has been shuffled */
1214 bAnyReplicaExchanged = TRUE;
1218 if (bAnyReplicaExchanged)
1220 /* reinitialize the placeholder arrays */
1221 for (i = 0; i < re->nrepl; i++)
1223 for (j = 0; j < re->nrepl; j++)
1225 re->cyclic[i][j] = -1;
1226 re->order[i][j] = -1;
1230 /* Identify the cyclic decomposition of the permutation (very
1231 * fast if neighbor replica exchange). */
1232 cyclic_decomposition(re->destinations, re->cyclic, re->incycle, re->nrepl, maxswap);
1234 /* Now translate the decomposition into a replica exchange
1235 * order at each step. */
1236 compute_exchange_order(re->cyclic, re->order, re->nrepl, *maxswap);
1238 /* Did this replica do any exchange at any point? */
1239 for (j = 0; j < *maxswap; j++)
1241 if (replica_id != re->order[replica_id][j])
1243 *bThisReplicaExchanged = TRUE;
1250 gmx_bool replica_exchange(FILE* fplog,
1251 const t_commrec* cr,
1252 const gmx_multisim_t* ms,
1253 struct gmx_repl_ex* re,
1255 const gmx_enerdata_t* enerd,
1256 t_state* state_local,
1262 int exchange_partner;
1264 /* Number of rounds of exchanges needed to deal with any multiple
1266 /* Where each replica ends up after the exchange attempt(s). */
1267 /* The order in which multiple exchanges will occur. */
1268 gmx_bool bThisReplicaExchanged = FALSE;
1272 replica_id = re->repl;
1273 test_for_replica_exchange(fplog, ms, re, enerd, det(state_local->box), step, time);
1274 prepare_to_do_exchange(re, replica_id, &maxswap, &bThisReplicaExchanged);
1276 /* Do intra-simulation broadcast so all processors belonging to
1277 * each simulation know whether they need to participate in
1278 * collecting the state. Otherwise, they might as well get on with
1279 * the next thing to do. */
1280 if (DOMAINDECOMP(cr))
1283 MPI_Bcast(&bThisReplicaExchanged, sizeof(gmx_bool), MPI_BYTE, MASTERRANK(cr), cr->mpi_comm_mygroup);
1287 if (bThisReplicaExchanged)
1289 /* Exchange the states */
1290 /* Collect the global state on the master node */
1291 if (DOMAINDECOMP(cr))
1293 dd_collect_state(cr->dd, state_local, state);
1297 copy_state_serial(state_local, state);
1302 /* There will be only one swap cycle with standard replica
1303 * exchange, but there may be multiple swap cycles if we
1304 * allow multiple swaps. */
1306 for (j = 0; j < maxswap; j++)
1308 exchange_partner = re->order[replica_id][j];
1310 if (exchange_partner != replica_id)
1312 /* Exchange the global states between the master nodes */
1315 fprintf(debug, "Exchanging %d with %d\n", replica_id, exchange_partner);
1317 exchange_state(ms, exchange_partner, state);
1320 /* For temperature-type replica exchange, we need to scale
1321 * the velocities. */
1322 if (re->type == ereTEMP || re->type == ereTL)
1324 scale_velocities(state->v, std::sqrt(re->q[ereTEMP][replica_id]
1325 / re->q[ereTEMP][re->destinations[replica_id]]));
1329 /* With domain decomposition the global state is distributed later */
1330 if (!DOMAINDECOMP(cr))
1332 /* Copy the global state to the local state data structure */
1333 copy_state_serial(state, state_local);
1337 return bThisReplicaExchanged;
1340 void print_replica_exchange_statistics(FILE* fplog, struct gmx_repl_ex* re)
1344 fprintf(fplog, "\nReplica exchange statistics\n");
1348 fprintf(fplog, "Repl %d attempts, %d odd, %d even\n", re->nattempt[0] + re->nattempt[1],
1349 re->nattempt[1], re->nattempt[0]);
1351 fprintf(fplog, "Repl average probabilities:\n");
1352 for (i = 1; i < re->nrepl; i++)
1354 if (re->nattempt[i % 2] == 0)
1360 re->prob[i] = re->prob_sum[i] / re->nattempt[i % 2];
1363 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1364 print_prob(fplog, "", re->nrepl, re->prob);
1366 fprintf(fplog, "Repl number of exchanges:\n");
1367 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1368 print_count(fplog, "", re->nrepl, re->nexchange);
1370 fprintf(fplog, "Repl average number of exchanges:\n");
1371 for (i = 1; i < re->nrepl; i++)
1373 if (re->nattempt[i % 2] == 0)
1379 re->prob[i] = (static_cast<real>(re->nexchange[i])) / re->nattempt[i % 2];
1382 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1383 print_prob(fplog, "", re->nrepl, re->prob);
1385 fprintf(fplog, "\n");
1387 /* print the transition matrix */
1388 print_transition_matrix(fplog, re->nrepl, re->nmoves, re->nattempt);