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,2012,2013,2014,2015,2016,2017,2018, 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/mdrun/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
83 ereTEMP, ereLAMBDA, ereENDSINGLE, ereTL, ereNR
85 /*! \brief Strings describing replica exchange flavours.
87 * end_single_marker merely notes the end of single variable replica
88 * exchange. All types higher than it are multiple replica exchange
91 * Eventually, should add 'pressure', 'temperature and pressure',
92 * 'lambda_and_pressure', 'temperature_lambda_pressure'?; Let's wait
93 * until we feel better about the pressure control methods giving
94 * exact ensembles. Right now, we assume constant pressure */
95 static const char *erename[ereNR] = { "temperature", "lambda", "end_single_marker", "temperature and lambda"};
97 //! Working data for replica exchange.
102 //! Total number of replica
106 //! Replica exchange type from ere enum
108 //! Quantity, e.g. temperature or lambda; first index is ere, second index is replica ID
110 //! Use constant pressure and temperature
112 //! Replica pressures
116 //! Used for keeping track of all the replica swaps
118 //! Replica exchange interval (number of steps)
120 //! Number of exchanges per interval
124 //! Number of even and odd replica change attempts
126 //! Sum of probabilities
128 //! Number of moves between replicas i and j
130 //! i-th element of the array is the number of exchanges between replica i-1 and i
133 /*! \brief Helper arrays for replica exchange; allocated here
134 * so they don't have to be allocated each time */
144 //! Helper arrays to hold the quantities that are exchanged.
154 // TODO We should add Doxygen here some time.
157 static gmx_bool repl_quantity(const gmx_multisim_t *ms,
158 struct gmx_repl_ex *re, int ere, real q)
164 snew(qall, ms->nsim);
166 gmx_sum_sim(ms->nsim, qall, ms);
169 for (s = 1; s < ms->nsim; s++)
171 if (qall[s] != qall[0])
179 /* Set the replica exchange type and quantities */
182 snew(re->q[ere], re->nrepl);
183 for (s = 0; s < ms->nsim; s++)
185 re->q[ere][s] = qall[s];
193 init_replica_exchange(FILE *fplog,
194 const gmx_multisim_t *ms,
195 int numAtomsInSystem,
196 const t_inputrec *ir,
197 const ReplicaExchangeParameters &replExParams)
201 struct gmx_repl_ex *re;
203 gmx_bool bLambda = FALSE;
205 fprintf(fplog, "\nInitializing Replica Exchange\n");
207 if (!isMultiSim(ms) || ms->nsim == 1)
209 gmx_fatal(FARGS, "Nothing to exchange with only one replica, maybe you forgot to set the -multidir option of mdrun?");
211 if (!EI_DYNAMICS(ir->eI))
213 gmx_fatal(FARGS, "Replica exchange is only supported by dynamical simulations");
214 /* Note that PAR(cr) is defined by cr->nnodes > 1, which is
215 * distinct from isMultiSim(ms). A multi-simulation only runs
216 * with real MPI parallelism, but this does not imply PAR(cr)
219 * Since we are using a dynamical integrator, the only
220 * decomposition is DD, so PAR(cr) and DOMAINDECOMP(cr) are
221 * synonymous. The only way for cr->nnodes > 1 to be true is
222 * if we are using DD. */
228 re->nrepl = ms->nsim;
229 snew(re->q, ereENDSINGLE);
231 fprintf(fplog, "Repl There are %d replicas:\n", re->nrepl);
233 /* We only check that the number of atoms in the systms match.
234 * This, of course, do not guarantee that the systems are the same,
235 * but it does guarantee that we can perform replica exchange.
237 check_multi_int(fplog, ms, numAtomsInSystem, "the number of atoms", FALSE);
238 check_multi_int(fplog, ms, ir->eI, "the integrator", FALSE);
239 check_multi_int64(fplog, ms, ir->init_step+ir->nsteps, "init_step+nsteps", FALSE);
240 const int nst = replExParams.exchangeInterval;
241 check_multi_int64(fplog, ms, (ir->init_step+nst-1)/nst,
242 "first exchange step: init_step/-replex", FALSE);
243 check_multi_int(fplog, ms, ir->etc, "the temperature coupling", FALSE);
244 check_multi_int(fplog, ms, ir->opts.ngtc,
245 "the number of temperature coupling groups", FALSE);
246 check_multi_int(fplog, ms, ir->epc, "the pressure coupling", FALSE);
247 check_multi_int(fplog, ms, ir->efep, "free energy", FALSE);
248 check_multi_int(fplog, ms, ir->fepvals->n_lambda, "number of lambda states", FALSE);
250 re->temp = ir->opts.ref_t[0];
251 for (i = 1; (i < ir->opts.ngtc); i++)
253 if (ir->opts.ref_t[i] != re->temp)
255 fprintf(fplog, "\nWARNING: The temperatures of the different temperature coupling groups are not identical\n\n");
256 fprintf(stderr, "\nWARNING: The temperatures of the different temperature coupling groups are not identical\n\n");
261 bTemp = repl_quantity(ms, re, ereTEMP, re->temp);
262 if (ir->efep != efepNO)
264 bLambda = repl_quantity(ms, re, ereLAMBDA, static_cast<real>(ir->fepvals->init_fep_state));
266 if (re->type == -1) /* nothing was assigned */
268 gmx_fatal(FARGS, "The properties of the %d systems are all the same, there is nothing to exchange", re->nrepl);
270 if (bLambda && bTemp)
277 please_cite(fplog, "Sugita1999a");
278 if (ir->epc != epcNO)
281 fprintf(fplog, "Repl Using Constant Pressure REMD.\n");
282 please_cite(fplog, "Okabe2001a");
284 if (ir->etc == etcBERENDSEN)
286 gmx_fatal(FARGS, "REMD with the %s thermostat does not produce correct potential energy distributions, consider using the %s thermostat instead",
287 ETCOUPLTYPE(ir->etc), ETCOUPLTYPE(etcVRESCALE));
292 if (ir->fepvals->delta_lambda != 0) /* check this? */
294 gmx_fatal(FARGS, "delta_lambda is not zero");
299 snew(re->pres, re->nrepl);
300 if (ir->epct == epctSURFACETENSION)
302 pres = ir->ref_p[ZZ][ZZ];
308 for (i = 0; i < DIM; i++)
310 if (ir->compress[i][i] != 0)
312 pres += ir->ref_p[i][i];
318 re->pres[re->repl] = pres;
319 gmx_sum_sim(re->nrepl, re->pres, ms);
322 /* Make an index for increasing replica order */
323 /* only makes sense if one or the other is varying, not both!
324 if both are varying, we trust the order the person gave. */
325 snew(re->ind, re->nrepl);
326 for (i = 0; i < re->nrepl; i++)
331 if (re->type < ereENDSINGLE)
334 for (i = 0; i < re->nrepl; i++)
336 for (j = i+1; j < re->nrepl; j++)
338 if (re->q[re->type][re->ind[j]] < re->q[re->type][re->ind[i]])
340 /* Unordered replicas are supposed to work, but there
341 * is still an issues somewhere.
342 * Note that at this point still re->ind[i]=i.
344 gmx_fatal(FARGS, "Replicas with indices %d < %d have %ss %g > %g, please order your replicas on increasing %s",
347 re->q[re->type][i], re->q[re->type][j],
350 else if (re->q[re->type][re->ind[j]] == re->q[re->type][re->ind[i]])
352 gmx_fatal(FARGS, "Two replicas have identical %ss", erename[re->type]);
358 /* keep track of all the swaps, starting with the initial placement. */
359 snew(re->allswaps, re->nrepl);
360 for (i = 0; i < re->nrepl; i++)
362 re->allswaps[i] = re->ind[i];
368 fprintf(fplog, "\nReplica exchange in temperature\n");
369 for (i = 0; i < re->nrepl; i++)
371 fprintf(fplog, " %5.1f", re->q[re->type][re->ind[i]]);
373 fprintf(fplog, "\n");
376 fprintf(fplog, "\nReplica exchange in lambda\n");
377 for (i = 0; i < re->nrepl; i++)
379 fprintf(fplog, " %3d", static_cast<int>(re->q[re->type][re->ind[i]]));
381 fprintf(fplog, "\n");
384 fprintf(fplog, "\nReplica exchange in temperature and lambda state\n");
385 for (i = 0; i < re->nrepl; i++)
387 fprintf(fplog, " %5.1f", re->q[ereTEMP][re->ind[i]]);
389 fprintf(fplog, "\n");
390 for (i = 0; i < re->nrepl; i++)
392 fprintf(fplog, " %5d", static_cast<int>(re->q[ereLAMBDA][re->ind[i]]));
394 fprintf(fplog, "\n");
397 gmx_incons("Unknown replica exchange quantity");
401 fprintf(fplog, "\nRepl p");
402 for (i = 0; i < re->nrepl; i++)
404 fprintf(fplog, " %5.2f", re->pres[re->ind[i]]);
407 for (i = 0; i < re->nrepl; i++)
409 if ((i > 0) && (re->pres[re->ind[i]] < re->pres[re->ind[i-1]]))
411 fprintf(fplog, "\nWARNING: The reference pressures decrease with increasing temperatures\n\n");
412 fprintf(stderr, "\nWARNING: The reference pressures decrease with increasing temperatures\n\n");
417 if (replExParams.randomSeed == -1)
421 re->seed = static_cast<int>(gmx::makeRandomSeed());
427 gmx_sumi_sim(1, &(re->seed), ms);
431 re->seed = replExParams.randomSeed;
433 fprintf(fplog, "\nReplica exchange interval: %d\n", re->nst);
434 fprintf(fplog, "\nReplica random seed: %d\n", re->seed);
439 snew(re->prob_sum, re->nrepl);
440 snew(re->nexchange, re->nrepl);
441 snew(re->nmoves, re->nrepl);
442 for (i = 0; i < re->nrepl; i++)
444 snew(re->nmoves[i], re->nrepl);
446 fprintf(fplog, "Replica exchange information below: ex and x = exchange, pr = probability\n");
448 /* generate space for the helper functions so we don't have to snew each time */
450 snew(re->destinations, re->nrepl);
451 snew(re->incycle, re->nrepl);
452 snew(re->tmpswap, re->nrepl);
453 snew(re->cyclic, re->nrepl);
454 snew(re->order, re->nrepl);
455 for (i = 0; i < re->nrepl; i++)
457 snew(re->cyclic[i], re->nrepl+1);
458 snew(re->order[i], re->nrepl);
460 /* allocate space for the functions storing the data for the replicas */
461 /* not all of these arrays needed in all cases, but they don't take
462 up much space, since the max size is nrepl**2 */
463 snew(re->prob, re->nrepl);
464 snew(re->bEx, re->nrepl);
465 snew(re->beta, re->nrepl);
466 snew(re->Vol, re->nrepl);
467 snew(re->Epot, re->nrepl);
468 snew(re->de, re->nrepl);
469 for (i = 0; i < re->nrepl; i++)
471 snew(re->de[i], re->nrepl);
473 re->nex = replExParams.numExchanges;
477 static void exchange_reals(const gmx_multisim_t gmx_unused *ms, int gmx_unused b, real *v, int n)
487 MPI_Sendrecv(v, n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
488 buf,n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
489 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
494 MPI_Isend(v, n*sizeof(real), MPI_BYTE, MSRANK(ms, b), 0,
495 ms->mpi_comm_masters, &mpi_req);
496 MPI_Recv(buf, n*sizeof(real), MPI_BYTE, MSRANK(ms, b), 0,
497 ms->mpi_comm_masters, MPI_STATUS_IGNORE);
498 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
501 for (i = 0; i < n; i++)
510 static void exchange_doubles(const gmx_multisim_t gmx_unused *ms, int gmx_unused b, double *v, int n)
520 MPI_Sendrecv(v, n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
521 buf,n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
522 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
527 MPI_Isend(v, n*sizeof(double), MPI_BYTE, MSRANK(ms, b), 0,
528 ms->mpi_comm_masters, &mpi_req);
529 MPI_Recv(buf, n*sizeof(double), MPI_BYTE, MSRANK(ms, b), 0,
530 ms->mpi_comm_masters, MPI_STATUS_IGNORE);
531 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
534 for (i = 0; i < n; i++)
542 static void exchange_rvecs(const gmx_multisim_t gmx_unused *ms, int gmx_unused b, rvec *v, int n)
552 MPI_Sendrecv(v[0], n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
553 buf[0],n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
554 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
559 MPI_Isend(v[0], n*sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0,
560 ms->mpi_comm_masters, &mpi_req);
561 MPI_Recv(buf[0], n*sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0,
562 ms->mpi_comm_masters, MPI_STATUS_IGNORE);
563 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
566 for (i = 0; i < n; i++)
568 copy_rvec(buf[i], v[i]);
574 static void exchange_state(const gmx_multisim_t *ms, int b, t_state *state)
576 /* When t_state changes, this code should be updated. */
578 ngtc = state->ngtc * state->nhchainlength;
579 nnhpres = state->nnhpres* state->nhchainlength;
580 exchange_rvecs(ms, b, state->box, DIM);
581 exchange_rvecs(ms, b, state->box_rel, DIM);
582 exchange_rvecs(ms, b, state->boxv, DIM);
583 exchange_reals(ms, b, &(state->veta), 1);
584 exchange_reals(ms, b, &(state->vol0), 1);
585 exchange_rvecs(ms, b, state->svir_prev, DIM);
586 exchange_rvecs(ms, b, state->fvir_prev, DIM);
587 exchange_rvecs(ms, b, state->pres_prev, DIM);
588 exchange_doubles(ms, b, state->nosehoover_xi.data(), ngtc);
589 exchange_doubles(ms, b, state->nosehoover_vxi.data(), ngtc);
590 exchange_doubles(ms, b, state->nhpres_xi.data(), nnhpres);
591 exchange_doubles(ms, b, state->nhpres_vxi.data(), nnhpres);
592 exchange_doubles(ms, b, state->therm_integral.data(), state->ngtc);
593 exchange_doubles(ms, b, &state->baros_integral, 1);
594 exchange_rvecs(ms, b, state->x.rvec_array(), state->natoms);
595 exchange_rvecs(ms, b, state->v.rvec_array(), state->natoms);
598 static void copy_state_serial(const t_state *src, t_state *dest)
602 /* Currently the local state is always a pointer to the global
603 * in serial, so we should never end up here.
604 * TODO: Implement a (trivial) t_state copy once converted to C++.
606 GMX_RELEASE_ASSERT(false, "State copying is currently not implemented in replica exchange");
610 static void scale_velocities(gmx::ArrayRef<gmx::RVec> velocities, real fac)
612 for (auto &v : velocities)
618 static void print_transition_matrix(FILE *fplog, int n, int **nmoves, const int *nattempt)
623 ntot = nattempt[0] + nattempt[1];
624 fprintf(fplog, "\n");
625 fprintf(fplog, "Repl");
626 for (i = 0; i < n; i++)
628 fprintf(fplog, " "); /* put the title closer to the center */
630 fprintf(fplog, "Empirical Transition Matrix\n");
632 fprintf(fplog, "Repl");
633 for (i = 0; i < n; i++)
635 fprintf(fplog, "%8d", (i+1));
637 fprintf(fplog, "\n");
639 for (i = 0; i < n; i++)
641 fprintf(fplog, "Repl");
642 for (j = 0; j < n; j++)
645 if (nmoves[i][j] > 0)
647 Tprint = nmoves[i][j]/(2.0*ntot);
649 fprintf(fplog, "%8.4f", Tprint);
651 fprintf(fplog, "%3d\n", i);
655 static void print_ind(FILE *fplog, const char *leg, int n, int *ind, const gmx_bool *bEx)
659 fprintf(fplog, "Repl %2s %2d", leg, ind[0]);
660 for (i = 1; i < n; i++)
662 fprintf(fplog, " %c %2d", (bEx != nullptr && bEx[i]) ? 'x' : ' ', ind[i]);
664 fprintf(fplog, "\n");
667 static void print_allswitchind(FILE *fplog, int n, int *pind, int *allswaps, int *tmpswap)
671 for (i = 0; i < n; i++)
673 tmpswap[i] = allswaps[i];
675 for (i = 0; i < n; i++)
677 allswaps[i] = tmpswap[pind[i]];
680 fprintf(fplog, "\nAccepted Exchanges: ");
681 for (i = 0; i < n; i++)
683 fprintf(fplog, "%d ", pind[i]);
685 fprintf(fplog, "\n");
687 /* the "Order After Exchange" is the state label corresponding to the configuration that
688 started in state listed in order, i.e.
693 configuration starting in simulation 3 is now in simulation 0,
694 configuration starting in simulation 0 is now in simulation 1,
695 configuration starting in simulation 1 is now in simulation 2,
696 configuration starting in simulation 2 is now in simulation 3
698 fprintf(fplog, "Order After Exchange: ");
699 for (i = 0; i < n; i++)
701 fprintf(fplog, "%d ", allswaps[i]);
703 fprintf(fplog, "\n\n");
706 static void print_prob(FILE *fplog, const char *leg, int n, real *prob)
711 fprintf(fplog, "Repl %2s ", leg);
712 for (i = 1; i < n; i++)
716 sprintf(buf, "%4.2f", prob[i]);
717 fprintf(fplog, " %3s", buf[0] == '1' ? "1.0" : buf+1);
724 fprintf(fplog, "\n");
727 static void print_count(FILE *fplog, const char *leg, int n, int *count)
731 fprintf(fplog, "Repl %2s ", leg);
732 for (i = 1; i < n; i++)
734 fprintf(fplog, " %4d", count[i]);
736 fprintf(fplog, "\n");
739 static real calc_delta(FILE *fplog, gmx_bool bPrint, struct gmx_repl_ex *re, int a, int b, int ap, int bp)
742 real ediff, dpV, delta = 0;
743 real *Epot = re->Epot;
746 real *beta = re->beta;
748 /* Two cases; we are permuted and not. In all cases, setting ap = a and bp = b will reduce
749 to the non permuted case */
755 * Okabe et. al. Chem. Phys. Lett. 335 (2001) 435-439
757 ediff = Epot[b] - Epot[a];
758 delta = -(beta[bp] - beta[ap])*ediff;
761 /* two cases: when we are permuted, and not. */
763 ediff = E_new - E_old
764 = [H_b(x_a) + H_a(x_b)] - [H_b(x_b) + H_a(x_a)]
765 = [H_b(x_a) - H_a(x_a)] + [H_a(x_b) - H_b(x_b)]
766 = de[b][a] + de[a][b] */
769 ediff = E_new - E_old
770 = [H_bp(x_a) + H_ap(x_b)] - [H_bp(x_b) + H_ap(x_a)]
771 = [H_bp(x_a) - H_ap(x_a)] + [H_ap(x_b) - H_bp(x_b)]
772 = [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)]
773 = [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)]
774 = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]) */
775 /* but, in the current code implementation, we flip configurations, not indices . . .
776 So let's examine that.
777 = [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)]
778 = [H_b(x_ap) - H_a(x_ap)] + [H_a(x_bp) - H_b(x_pb)]
779 = (de[b][ap] - de[a][ap]) + (de[a][bp] - de[b][bp]
780 So, if we exchange b<=> bp and a<=> ap, we return to the same result.
781 So the simple solution is to flip the
782 position of perturbed and original indices in the tests.
785 ediff = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]);
786 delta = ediff*beta[a]; /* assume all same temperature in this case */
790 /* delta = reduced E_new - reduced E_old
791 = [beta_b H_b(x_a) + beta_a H_a(x_b)] - [beta_b H_b(x_b) + beta_a H_a(x_a)]
792 = [beta_b H_b(x_a) - beta_a H_a(x_a)] + [beta_a H_a(x_b) - beta_b H_b(x_b)]
793 = [beta_b dH_b(x_a) + beta_b H_a(x_a) - beta_a H_a(x_a)] +
794 [beta_a dH_a(x_b) + beta_a H_b(x_b) - beta_b H_b(x_b)]
795 = [beta_b dH_b(x_a) + [beta_a dH_a(x_b) +
796 beta_b (H_a(x_a) - H_b(x_b)]) - beta_a (H_a(x_a) - H_b(x_b))
797 = beta_b dH_b(x_a) + beta_a dH_a(x_b) - (beta_b - beta_a)(H_b(x_b) - H_a(x_a) */
798 /* delta = beta[b]*de[b][a] + beta[a]*de[a][b] - (beta[b] - beta[a])*(Epot[b] - Epot[a]; */
799 /* permuted (big breath!) */
800 /* delta = reduced E_new - reduced E_old
801 = [beta_bp H_bp(x_a) + beta_ap H_ap(x_b)] - [beta_bp H_bp(x_b) + beta_ap H_ap(x_a)]
802 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
803 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
804 - beta_pb H_a(x_a) + beta_ap H_a(x_a) + beta_pb H_a(x_a) - beta_ap H_a(x_a)
805 - beta_ap H_b(x_b) + beta_bp H_b(x_b) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
806 = [(beta_bp H_bp(x_a) - beta_bp H_a(x_a)) - (beta_ap H_ap(x_a) - beta_ap H_a(x_a))] +
807 [(beta_ap H_ap(x_b) - beta_ap H_b(x_b)) - (beta_bp H_bp(x_b) - beta_bp H_b(x_b))]
808 + beta_pb H_a(x_a) - beta_ap H_a(x_a) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
809 = [beta_bp (H_bp(x_a) - H_a(x_a)) - beta_ap (H_ap(x_a) - H_a(x_a))] +
810 [beta_ap (H_ap(x_b) - H_b(x_b)) - beta_bp (H_bp(x_b) - H_b(x_b))]
811 + beta_pb (H_a(x_a) - H_b(x_b)) - beta_ap (H_a(x_a) - H_b(x_b))
812 = ([beta_bp de[bp][a] - beta_ap de[ap][a]) + beta_ap de[ap][b] - beta_bp de[bp][b])
813 + (beta_pb-beta_ap)(H_a(x_a) - H_b(x_b)) */
814 delta = beta[bp]*(de[bp][a] - de[bp][b]) + beta[ap]*(de[ap][b] - de[ap][a]) - (beta[bp]-beta[ap])*(Epot[b]-Epot[a]);
817 gmx_incons("Unknown replica exchange quantity");
821 fprintf(fplog, "Repl %d <-> %d dE_term = %10.3e (kT)\n", a, b, delta);
825 /* revist the calculation for 5.0. Might be some improvements. */
826 dpV = (beta[ap]*re->pres[ap]-beta[bp]*re->pres[bp])*(Vol[b]-Vol[a])/PRESFAC;
829 fprintf(fplog, " dpV = %10.3e d = %10.3e\n", dpV, delta + dpV);
837 test_for_replica_exchange(FILE *fplog,
838 const gmx_multisim_t *ms,
839 struct gmx_repl_ex *re,
840 const gmx_enerdata_t *enerd,
845 int m, i, j, a, b, ap, bp, i0, i1, tmp;
847 gmx_bool bPrint, bMultiEx;
848 gmx_bool *bEx = re->bEx;
849 real *prob = re->prob;
850 int *pind = re->destinations; /* permuted index */
851 gmx_bool bEpot = FALSE;
852 gmx_bool bDLambda = FALSE;
853 gmx_bool bVol = FALSE;
854 gmx::ThreeFry2x64<64> rng(re->seed, gmx::RandomDomain::ReplicaExchange);
855 gmx::UniformRealDistribution<real> uniformRealDist;
856 gmx::UniformIntDistribution<int> uniformNreplDist(0, re->nrepl-1);
858 bMultiEx = (re->nex > 1); /* multiple exchanges at each state */
859 fprintf(fplog, "Replica exchange at step %" PRId64 " time %.5f\n", step, time);
863 for (i = 0; i < re->nrepl; i++)
868 re->Vol[re->repl] = vol;
870 if ((re->type == ereTEMP || re->type == ereTL))
872 for (i = 0; i < re->nrepl; i++)
877 re->Epot[re->repl] = enerd->term[F_EPOT];
878 /* temperatures of different states*/
879 for (i = 0; i < re->nrepl; i++)
881 re->beta[i] = 1.0/(re->q[ereTEMP][i]*BOLTZ);
886 for (i = 0; i < re->nrepl; i++)
888 re->beta[i] = 1.0/(re->temp*BOLTZ); /* we have a single temperature */
891 if (re->type == ereLAMBDA || re->type == ereTL)
894 /* lambda differences. */
895 /* de[i][j] is the energy of the jth simulation in the ith Hamiltonian
896 minus the energy of the jth simulation in the jth Hamiltonian */
897 for (i = 0; i < re->nrepl; i++)
899 for (j = 0; j < re->nrepl; j++)
904 for (i = 0; i < re->nrepl; i++)
906 re->de[i][re->repl] = (enerd->enerpart_lambda[static_cast<int>(re->q[ereLAMBDA][i])+1]-enerd->enerpart_lambda[0]);
910 /* now actually do the communication */
913 gmx_sum_sim(re->nrepl, re->Vol, ms);
917 gmx_sum_sim(re->nrepl, re->Epot, ms);
921 for (i = 0; i < re->nrepl; i++)
923 gmx_sum_sim(re->nrepl, re->de[i], ms);
927 /* make a duplicate set of indices for shuffling */
928 for (i = 0; i < re->nrepl; i++)
930 pind[i] = re->ind[i];
933 rng.restart( step, 0 );
937 /* multiple random switch exchange */
941 for (i = 0; i < re->nex + nself; i++)
943 // For now this is superfluous, but just in case we ever add more
944 // calls in different branches it is safer to always reset the distribution.
945 uniformNreplDist.reset();
947 /* randomly select a pair */
948 /* in theory, could reduce this by identifying only which switches had a nonneglibible
949 probability of occurring (log p > -100) and only operate on those switches */
950 /* find out which state it is from, and what label that state currently has. Likely
951 more work that useful. */
952 i0 = uniformNreplDist(rng);
953 i1 = uniformNreplDist(rng);
957 continue; /* self-exchange, back up and do it again */
960 a = re->ind[i0]; /* what are the indices of these states? */
965 bPrint = FALSE; /* too noisy */
966 /* calculate the energy difference */
967 /* if the code changes to flip the STATES, rather than the configurations,
968 use the commented version of the code */
969 /* delta = calc_delta(fplog,bPrint,re,a,b,ap,bp); */
970 delta = calc_delta(fplog, bPrint, re, ap, bp, a, b);
972 /* we actually only use the first space in the prob and bEx array,
973 since there are actually many switches between pairs. */
983 if (delta > c_probabilityCutoff)
989 prob[0] = exp(-delta);
991 // roll a number to determine if accepted. For now it is superfluous to
992 // reset, but just in case we ever add more calls in different branches
993 // it is safer to always reset the distribution.
994 uniformRealDist.reset();
995 bEx[0] = uniformRealDist(rng) < prob[0];
997 re->prob_sum[0] += prob[0];
1001 /* swap the states */
1003 pind[i0] = pind[i1];
1007 re->nattempt[0]++; /* keep track of total permutation trials here */
1008 print_allswitchind(fplog, re->nrepl, pind, re->allswaps, re->tmpswap);
1012 /* standard nearest neighbor replica exchange */
1014 m = (step / re->nst) % 2;
1015 for (i = 1; i < re->nrepl; i++)
1020 bPrint = (re->repl == a || re->repl == b);
1023 delta = calc_delta(fplog, bPrint, re, a, b, a, b);
1032 if (delta > c_probabilityCutoff)
1038 prob[i] = exp(-delta);
1040 // roll a number to determine if accepted. For now it is superfluous to
1041 // reset, but just in case we ever add more calls in different branches
1042 // it is safer to always reset the distribution.
1043 uniformRealDist.reset();
1044 bEx[i] = uniformRealDist(rng) < prob[i];
1046 re->prob_sum[i] += prob[i];
1050 /* swap these two */
1052 pind[i-1] = pind[i];
1054 re->nexchange[i]++; /* statistics for back compatibility */
1063 /* print some statistics */
1064 print_ind(fplog, "ex", re->nrepl, re->ind, bEx);
1065 print_prob(fplog, "pr", re->nrepl, prob);
1066 fprintf(fplog, "\n");
1070 /* record which moves were made and accepted */
1071 for (i = 0; i < re->nrepl; i++)
1073 re->nmoves[re->ind[i]][pind[i]] += 1;
1074 re->nmoves[pind[i]][re->ind[i]] += 1;
1076 fflush(fplog); /* make sure we can see what the last exchange was */
1080 cyclic_decomposition(const int *destinations,
1089 for (i = 0; i < nrepl; i++)
1093 for (i = 0; i < nrepl; i++) /* one cycle for each replica */
1104 for (j = 0; j < nrepl; j++) /* potentially all cycles are part, but we will break first */
1106 p = destinations[p]; /* start permuting */
1114 break; /* we've reached the original element, the cycle is complete, and we marked the end. */
1118 cyclic[i][c] = p; /* each permutation gives a new member of the cycle */
1124 *nswap = maxlen - 1;
1128 for (i = 0; i < nrepl; i++)
1130 fprintf(debug, "Cycle %d:", i);
1131 for (j = 0; j < nrepl; j++)
1133 if (cyclic[i][j] < 0)
1137 fprintf(debug, "%2d", cyclic[i][j]);
1139 fprintf(debug, "\n");
1146 compute_exchange_order(int **cyclic,
1153 for (j = 0; j < maxswap; j++)
1155 for (i = 0; i < nrepl; i++)
1157 if (cyclic[i][j+1] >= 0)
1159 order[cyclic[i][j+1]][j] = cyclic[i][j];
1160 order[cyclic[i][j]][j] = cyclic[i][j+1];
1163 for (i = 0; i < nrepl; i++)
1165 if (order[i][j] < 0)
1167 order[i][j] = i; /* if it's not exchanging, it should stay this round*/
1174 fprintf(debug, "Replica Exchange Order\n");
1175 for (i = 0; i < nrepl; i++)
1177 fprintf(debug, "Replica %d:", i);
1178 for (j = 0; j < maxswap; j++)
1180 if (order[i][j] < 0)
1184 fprintf(debug, "%2d", order[i][j]);
1186 fprintf(debug, "\n");
1193 prepare_to_do_exchange(struct gmx_repl_ex *re,
1194 const int replica_id,
1196 gmx_bool *bThisReplicaExchanged)
1199 /* Hold the cyclic decomposition of the (multiple) replica
1201 gmx_bool bAnyReplicaExchanged = FALSE;
1202 *bThisReplicaExchanged = FALSE;
1204 for (i = 0; i < re->nrepl; i++)
1206 if (re->destinations[i] != re->ind[i])
1208 /* only mark as exchanged if the index has been shuffled */
1209 bAnyReplicaExchanged = TRUE;
1213 if (bAnyReplicaExchanged)
1215 /* reinitialize the placeholder arrays */
1216 for (i = 0; i < re->nrepl; i++)
1218 for (j = 0; j < re->nrepl; j++)
1220 re->cyclic[i][j] = -1;
1221 re->order[i][j] = -1;
1225 /* Identify the cyclic decomposition of the permutation (very
1226 * fast if neighbor replica exchange). */
1227 cyclic_decomposition(re->destinations, re->cyclic, re->incycle, re->nrepl, maxswap);
1229 /* Now translate the decomposition into a replica exchange
1230 * order at each step. */
1231 compute_exchange_order(re->cyclic, re->order, re->nrepl, *maxswap);
1233 /* Did this replica do any exchange at any point? */
1234 for (j = 0; j < *maxswap; j++)
1236 if (replica_id != re->order[replica_id][j])
1238 *bThisReplicaExchanged = TRUE;
1245 gmx_bool replica_exchange(FILE *fplog, const t_commrec *cr,
1246 const gmx_multisim_t *ms, struct gmx_repl_ex *re,
1247 t_state *state, const gmx_enerdata_t *enerd,
1248 t_state *state_local, int64_t step, real time)
1252 int exchange_partner;
1254 /* Number of rounds of exchanges needed to deal with any multiple
1256 /* Where each replica ends up after the exchange attempt(s). */
1257 /* The order in which multiple exchanges will occur. */
1258 gmx_bool bThisReplicaExchanged = FALSE;
1262 replica_id = re->repl;
1263 test_for_replica_exchange(fplog, ms, re, enerd, det(state_local->box), step, time);
1264 prepare_to_do_exchange(re, replica_id, &maxswap, &bThisReplicaExchanged);
1266 /* Do intra-simulation broadcast so all processors belonging to
1267 * each simulation know whether they need to participate in
1268 * collecting the state. Otherwise, they might as well get on with
1269 * the next thing to do. */
1270 if (DOMAINDECOMP(cr))
1273 MPI_Bcast(&bThisReplicaExchanged, sizeof(gmx_bool), MPI_BYTE, MASTERRANK(cr),
1274 cr->mpi_comm_mygroup);
1278 if (bThisReplicaExchanged)
1280 /* Exchange the states */
1281 /* Collect the global state on the master node */
1282 if (DOMAINDECOMP(cr))
1284 dd_collect_state(cr->dd, state_local, state);
1288 copy_state_serial(state_local, state);
1293 /* There will be only one swap cycle with standard replica
1294 * exchange, but there may be multiple swap cycles if we
1295 * allow multiple swaps. */
1297 for (j = 0; j < maxswap; j++)
1299 exchange_partner = re->order[replica_id][j];
1301 if (exchange_partner != replica_id)
1303 /* Exchange the global states between the master nodes */
1306 fprintf(debug, "Exchanging %d with %d\n", replica_id, exchange_partner);
1308 exchange_state(ms, exchange_partner, state);
1311 /* For temperature-type replica exchange, we need to scale
1312 * the velocities. */
1313 if (re->type == ereTEMP || re->type == ereTL)
1315 scale_velocities(state->v,
1316 std::sqrt(re->q[ereTEMP][replica_id]/re->q[ereTEMP][re->destinations[replica_id]]));
1321 /* With domain decomposition the global state is distributed later */
1322 if (!DOMAINDECOMP(cr))
1324 /* Copy the global state to the local state data structure */
1325 copy_state_serial(state, state_local);
1329 return bThisReplicaExchanged;
1332 void print_replica_exchange_statistics(FILE *fplog, struct gmx_repl_ex *re)
1336 fprintf(fplog, "\nReplica exchange statistics\n");
1340 fprintf(fplog, "Repl %d attempts, %d odd, %d even\n",
1341 re->nattempt[0]+re->nattempt[1], re->nattempt[1], re->nattempt[0]);
1343 fprintf(fplog, "Repl average probabilities:\n");
1344 for (i = 1; i < re->nrepl; i++)
1346 if (re->nattempt[i%2] == 0)
1352 re->prob[i] = re->prob_sum[i]/re->nattempt[i%2];
1355 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1356 print_prob(fplog, "", re->nrepl, re->prob);
1358 fprintf(fplog, "Repl number of exchanges:\n");
1359 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1360 print_count(fplog, "", re->nrepl, re->nexchange);
1362 fprintf(fplog, "Repl average number of exchanges:\n");
1363 for (i = 1; i < re->nrepl; i++)
1365 if (re->nattempt[i%2] == 0)
1371 re->prob[i] = (static_cast<real>(re->nexchange[i]))/re->nattempt[i%2];
1374 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1375 print_prob(fplog, "", re->nrepl, re->prob);
1377 fprintf(fplog, "\n");
1379 /* print the transition matrix */
1380 print_transition_matrix(fplog, re->nrepl, re->nmoves, re->nattempt);