Stopped header files including state.h
[gromacs/AngularHB.git] / src / programs / mdrun / repl_ex.cpp
blob2a25b7d3c1d106852e5ea8182b661b9ee3548f08
1 /*
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, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
38 #include "gmxpre.h"
40 #include "repl_ex.h"
42 #include "config.h"
44 #include <math.h>
46 #include <random>
48 #include "gromacs/domdec/domdec.h"
49 #include "gromacs/gmxlib/network.h"
50 #include "gromacs/math/units.h"
51 #include "gromacs/math/vec.h"
52 #include "gromacs/mdlib/main.h"
53 #include "gromacs/mdtypes/commrec.h"
54 #include "gromacs/mdtypes/inputrec.h"
55 #include "gromacs/mdtypes/md_enums.h"
56 #include "gromacs/mdtypes/state.h"
57 #include "gromacs/random/threefry.h"
58 #include "gromacs/random/uniformintdistribution.h"
59 #include "gromacs/random/uniformrealdistribution.h"
60 #include "gromacs/utility/fatalerror.h"
61 #include "gromacs/utility/pleasecite.h"
62 #include "gromacs/utility/smalloc.h"
65 #define PROBABILITYCUTOFF 100
66 /* we don't bother evaluating if events are more rare than exp(-100) = 3.7x10^-44 */
68 //! Rank in the multisimulaiton
69 #define MSRANK(ms, nodeid) (nodeid)
71 enum {
72 ereTEMP, ereLAMBDA, ereENDSINGLE, ereTL, ereNR
74 const char *erename[ereNR] = { "temperature", "lambda", "end_single_marker", "temperature and lambda"};
75 /* end_single_marker merely notes the end of single variable replica exchange. All types higher than
76 it are multiple replica exchange methods */
77 /* Eventually, should add 'pressure', 'temperature and pressure', 'lambda_and_pressure', 'temperature_lambda_pressure'?;
78 Let's wait until we feel better about the pressure control methods giving exact ensembles. Right now, we assume constant pressure */
80 typedef struct gmx_repl_ex
82 int repl; /* replica ID */
83 int nrepl; /* total number of replica */
84 real temp; /* temperature */
85 int type; /* replica exchange type from ere enum */
86 real **q; /* quantity, e.g. temperature or lambda; first index is ere, second index is replica ID */
87 gmx_bool bNPT; /* use constant pressure and temperature */
88 real *pres; /* replica pressures */
89 int *ind; /* replica indices */
90 int *allswaps; /* used for keeping track of all the replica swaps */
91 int nst; /* replica exchange interval (number of steps) */
92 int nex; /* number of exchanges per interval */
93 int seed; /* random seed */
94 int nattempt[2]; /* number of even and odd replica change attempts */
95 real *prob_sum; /* sum of probabilities */
96 int **nmoves; /* number of moves between replicas i and j */
97 int *nexchange; /* i-th element of the array is the number of exchanges between replica i-1 and i */
99 /* these are helper arrays for replica exchange; allocated here so they
100 don't have to be allocated each time */
101 int *destinations;
102 int **cyclic;
103 int **order;
104 int *tmpswap;
105 gmx_bool *incycle;
106 gmx_bool *bEx;
108 /* helper arrays to hold the quantities that are exchanged */
109 real *prob;
110 real *Epot;
111 real *beta;
112 real *Vol;
113 real **de;
115 } t_gmx_repl_ex;
117 static gmx_bool repl_quantity(const gmx_multisim_t *ms,
118 struct gmx_repl_ex *re, int ere, real q)
120 real *qall;
121 gmx_bool bDiff;
122 int s;
124 snew(qall, ms->nsim);
125 qall[re->repl] = q;
126 gmx_sum_sim(ms->nsim, qall, ms);
128 bDiff = FALSE;
129 for (s = 1; s < ms->nsim; s++)
131 if (qall[s] != qall[0])
133 bDiff = TRUE;
137 if (bDiff)
139 /* Set the replica exchange type and quantities */
140 re->type = ere;
142 snew(re->q[ere], re->nrepl);
143 for (s = 0; s < ms->nsim; s++)
145 re->q[ere][s] = qall[s];
148 sfree(qall);
149 return bDiff;
152 gmx_repl_ex_t init_replica_exchange(FILE *fplog,
153 const gmx_multisim_t *ms,
154 const t_state *state,
155 const t_inputrec *ir,
156 int nst, int nex, int init_seed)
158 real pres;
159 int i, j, k;
160 struct gmx_repl_ex *re;
161 gmx_bool bTemp;
162 gmx_bool bLambda = FALSE;
164 fprintf(fplog, "\nInitializing Replica Exchange\n");
166 if (ms == nullptr || ms->nsim == 1)
168 gmx_fatal(FARGS, "Nothing to exchange with only one replica, maybe you forgot to set the -multi option of mdrun?");
170 if (!EI_DYNAMICS(ir->eI))
172 gmx_fatal(FARGS, "Replica exchange is only supported by dynamical simulations");
173 /* Note that PAR(cr) is defined by cr->nnodes > 1, which is
174 * distinct from MULTISIM(cr). A multi-simulation only runs
175 * with real MPI parallelism, but this does not imply PAR(cr)
176 * is true!
178 * Since we are using a dynamical integrator, the only
179 * decomposition is DD, so PAR(cr) and DOMAINDECOMP(cr) are
180 * synonymous. The only way for cr->nnodes > 1 to be true is
181 * if we are using DD. */
184 snew(re, 1);
186 re->repl = ms->sim;
187 re->nrepl = ms->nsim;
188 snew(re->q, ereENDSINGLE);
190 fprintf(fplog, "Repl There are %d replicas:\n", re->nrepl);
192 check_multi_int(fplog, ms, state->natoms, "the number of atoms", FALSE);
193 check_multi_int(fplog, ms, ir->eI, "the integrator", FALSE);
194 check_multi_int64(fplog, ms, ir->init_step+ir->nsteps, "init_step+nsteps", FALSE);
195 check_multi_int64(fplog, ms, (ir->init_step+nst-1)/nst,
196 "first exchange step: init_step/-replex", FALSE);
197 check_multi_int(fplog, ms, ir->etc, "the temperature coupling", FALSE);
198 check_multi_int(fplog, ms, ir->opts.ngtc,
199 "the number of temperature coupling groups", FALSE);
200 check_multi_int(fplog, ms, ir->epc, "the pressure coupling", FALSE);
201 check_multi_int(fplog, ms, ir->efep, "free energy", FALSE);
202 check_multi_int(fplog, ms, ir->fepvals->n_lambda, "number of lambda states", FALSE);
204 re->temp = ir->opts.ref_t[0];
205 for (i = 1; (i < ir->opts.ngtc); i++)
207 if (ir->opts.ref_t[i] != re->temp)
209 fprintf(fplog, "\nWARNING: The temperatures of the different temperature coupling groups are not identical\n\n");
210 fprintf(stderr, "\nWARNING: The temperatures of the different temperature coupling groups are not identical\n\n");
214 re->type = -1;
215 bTemp = repl_quantity(ms, re, ereTEMP, re->temp);
216 if (ir->efep != efepNO)
218 bLambda = repl_quantity(ms, re, ereLAMBDA, (real)ir->fepvals->init_fep_state);
220 if (re->type == -1) /* nothing was assigned */
222 gmx_fatal(FARGS, "The properties of the %d systems are all the same, there is nothing to exchange", re->nrepl);
224 if (bLambda && bTemp)
226 re->type = ereTL;
229 if (bTemp)
231 please_cite(fplog, "Sugita1999a");
232 if (ir->epc != epcNO)
234 re->bNPT = TRUE;
235 fprintf(fplog, "Repl Using Constant Pressure REMD.\n");
236 please_cite(fplog, "Okabe2001a");
238 if (ir->etc == etcBERENDSEN)
240 gmx_fatal(FARGS, "REMD with the %s thermostat does not produce correct potential energy distributions, consider using the %s thermostat instead",
241 ETCOUPLTYPE(ir->etc), ETCOUPLTYPE(etcVRESCALE));
244 if (bLambda)
246 if (ir->fepvals->delta_lambda != 0) /* check this? */
248 gmx_fatal(FARGS, "delta_lambda is not zero");
251 if (re->bNPT)
253 snew(re->pres, re->nrepl);
254 if (ir->epct == epctSURFACETENSION)
256 pres = ir->ref_p[ZZ][ZZ];
258 else
260 pres = 0;
261 j = 0;
262 for (i = 0; i < DIM; i++)
264 if (ir->compress[i][i] != 0)
266 pres += ir->ref_p[i][i];
267 j++;
270 pres /= j;
272 re->pres[re->repl] = pres;
273 gmx_sum_sim(re->nrepl, re->pres, ms);
276 /* Make an index for increasing replica order */
277 /* only makes sense if one or the other is varying, not both!
278 if both are varying, we trust the order the person gave. */
279 snew(re->ind, re->nrepl);
280 for (i = 0; i < re->nrepl; i++)
282 re->ind[i] = i;
285 if (re->type < ereENDSINGLE)
288 for (i = 0; i < re->nrepl; i++)
290 for (j = i+1; j < re->nrepl; j++)
292 if (re->q[re->type][re->ind[j]] < re->q[re->type][re->ind[i]])
294 /* Unordered replicas are supposed to work, but there
295 * is still an issues somewhere.
296 * Note that at this point still re->ind[i]=i.
298 gmx_fatal(FARGS, "Replicas with indices %d < %d have %ss %g > %g, please order your replicas on increasing %s",
299 i, j,
300 erename[re->type],
301 re->q[re->type][i], re->q[re->type][j],
302 erename[re->type]);
304 k = re->ind[i];
305 re->ind[i] = re->ind[j];
306 re->ind[j] = k;
308 else if (re->q[re->type][re->ind[j]] == re->q[re->type][re->ind[i]])
310 gmx_fatal(FARGS, "Two replicas have identical %ss", erename[re->type]);
316 /* keep track of all the swaps, starting with the initial placement. */
317 snew(re->allswaps, re->nrepl);
318 for (i = 0; i < re->nrepl; i++)
320 re->allswaps[i] = re->ind[i];
323 switch (re->type)
325 case ereTEMP:
326 fprintf(fplog, "\nReplica exchange in temperature\n");
327 for (i = 0; i < re->nrepl; i++)
329 fprintf(fplog, " %5.1f", re->q[re->type][re->ind[i]]);
331 fprintf(fplog, "\n");
332 break;
333 case ereLAMBDA:
334 fprintf(fplog, "\nReplica exchange in lambda\n");
335 for (i = 0; i < re->nrepl; i++)
337 fprintf(fplog, " %3d", (int)re->q[re->type][re->ind[i]]);
339 fprintf(fplog, "\n");
340 break;
341 case ereTL:
342 fprintf(fplog, "\nReplica exchange in temperature and lambda state\n");
343 for (i = 0; i < re->nrepl; i++)
345 fprintf(fplog, " %5.1f", re->q[ereTEMP][re->ind[i]]);
347 fprintf(fplog, "\n");
348 for (i = 0; i < re->nrepl; i++)
350 fprintf(fplog, " %5d", (int)re->q[ereLAMBDA][re->ind[i]]);
352 fprintf(fplog, "\n");
353 break;
354 default:
355 gmx_incons("Unknown replica exchange quantity");
357 if (re->bNPT)
359 fprintf(fplog, "\nRepl p");
360 for (i = 0; i < re->nrepl; i++)
362 fprintf(fplog, " %5.2f", re->pres[re->ind[i]]);
365 for (i = 0; i < re->nrepl; i++)
367 if ((i > 0) && (re->pres[re->ind[i]] < re->pres[re->ind[i-1]]))
369 fprintf(fplog, "\nWARNING: The reference pressures decrease with increasing temperatures\n\n");
370 fprintf(stderr, "\nWARNING: The reference pressures decrease with increasing temperatures\n\n");
374 re->nst = nst;
375 if (init_seed == -1)
377 if (MASTERSIM(ms))
379 re->seed = static_cast<int>(gmx::makeRandomSeed());
381 else
383 re->seed = 0;
385 gmx_sumi_sim(1, &(re->seed), ms);
387 else
389 re->seed = init_seed;
391 fprintf(fplog, "\nReplica exchange interval: %d\n", re->nst);
392 fprintf(fplog, "\nReplica random seed: %d\n", re->seed);
394 re->nattempt[0] = 0;
395 re->nattempt[1] = 0;
397 snew(re->prob_sum, re->nrepl);
398 snew(re->nexchange, re->nrepl);
399 snew(re->nmoves, re->nrepl);
400 for (i = 0; i < re->nrepl; i++)
402 snew(re->nmoves[i], re->nrepl);
404 fprintf(fplog, "Replica exchange information below: ex and x = exchange, pr = probability\n");
406 /* generate space for the helper functions so we don't have to snew each time */
408 snew(re->destinations, re->nrepl);
409 snew(re->incycle, re->nrepl);
410 snew(re->tmpswap, re->nrepl);
411 snew(re->cyclic, re->nrepl);
412 snew(re->order, re->nrepl);
413 for (i = 0; i < re->nrepl; i++)
415 snew(re->cyclic[i], re->nrepl+1);
416 snew(re->order[i], re->nrepl);
418 /* allocate space for the functions storing the data for the replicas */
419 /* not all of these arrays needed in all cases, but they don't take
420 up much space, since the max size is nrepl**2 */
421 snew(re->prob, re->nrepl);
422 snew(re->bEx, re->nrepl);
423 snew(re->beta, re->nrepl);
424 snew(re->Vol, re->nrepl);
425 snew(re->Epot, re->nrepl);
426 snew(re->de, re->nrepl);
427 for (i = 0; i < re->nrepl; i++)
429 snew(re->de[i], re->nrepl);
431 re->nex = nex;
432 return re;
435 static void exchange_reals(const gmx_multisim_t gmx_unused *ms, int gmx_unused b, real *v, int n)
437 real *buf;
438 int i;
440 if (v)
442 snew(buf, n);
443 #if GMX_MPI
445 MPI_Sendrecv(v, n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
446 buf,n*sizeof(real),MPI_BYTE,MSRANK(ms,b),0,
447 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
450 MPI_Request mpi_req;
452 MPI_Isend(v, n*sizeof(real), MPI_BYTE, MSRANK(ms, b), 0,
453 ms->mpi_comm_masters, &mpi_req);
454 MPI_Recv(buf, n*sizeof(real), MPI_BYTE, MSRANK(ms, b), 0,
455 ms->mpi_comm_masters, MPI_STATUS_IGNORE);
456 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
458 #endif
459 for (i = 0; i < n; i++)
461 v[i] = buf[i];
463 sfree(buf);
468 static void exchange_doubles(const gmx_multisim_t gmx_unused *ms, int gmx_unused b, double *v, int n)
470 double *buf;
471 int i;
473 if (v)
475 snew(buf, n);
476 #if GMX_MPI
478 MPI_Sendrecv(v, n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
479 buf,n*sizeof(double),MPI_BYTE,MSRANK(ms,b),0,
480 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
483 MPI_Request mpi_req;
485 MPI_Isend(v, n*sizeof(double), MPI_BYTE, MSRANK(ms, b), 0,
486 ms->mpi_comm_masters, &mpi_req);
487 MPI_Recv(buf, n*sizeof(double), MPI_BYTE, MSRANK(ms, b), 0,
488 ms->mpi_comm_masters, MPI_STATUS_IGNORE);
489 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
491 #endif
492 for (i = 0; i < n; i++)
494 v[i] = buf[i];
496 sfree(buf);
500 static void exchange_rvecs(const gmx_multisim_t gmx_unused *ms, int gmx_unused b, rvec *v, int n)
502 rvec *buf;
503 int i;
505 if (v)
507 snew(buf, n);
508 #if GMX_MPI
510 MPI_Sendrecv(v[0], n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
511 buf[0],n*sizeof(rvec),MPI_BYTE,MSRANK(ms,b),0,
512 ms->mpi_comm_masters,MPI_STATUS_IGNORE);
515 MPI_Request mpi_req;
517 MPI_Isend(v[0], n*sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0,
518 ms->mpi_comm_masters, &mpi_req);
519 MPI_Recv(buf[0], n*sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0,
520 ms->mpi_comm_masters, MPI_STATUS_IGNORE);
521 MPI_Wait(&mpi_req, MPI_STATUS_IGNORE);
523 #endif
524 for (i = 0; i < n; i++)
526 copy_rvec(buf[i], v[i]);
528 sfree(buf);
532 static void exchange_state(const gmx_multisim_t *ms, int b, t_state *state)
534 /* When t_state changes, this code should be updated. */
535 int ngtc, nnhpres;
536 ngtc = state->ngtc * state->nhchainlength;
537 nnhpres = state->nnhpres* state->nhchainlength;
538 exchange_rvecs(ms, b, state->box, DIM);
539 exchange_rvecs(ms, b, state->box_rel, DIM);
540 exchange_rvecs(ms, b, state->boxv, DIM);
541 exchange_reals(ms, b, &(state->veta), 1);
542 exchange_reals(ms, b, &(state->vol0), 1);
543 exchange_rvecs(ms, b, state->svir_prev, DIM);
544 exchange_rvecs(ms, b, state->fvir_prev, DIM);
545 exchange_rvecs(ms, b, state->pres_prev, DIM);
546 exchange_doubles(ms, b, state->nosehoover_xi.data(), ngtc);
547 exchange_doubles(ms, b, state->nosehoover_vxi.data(), ngtc);
548 exchange_doubles(ms, b, state->nhpres_xi.data(), nnhpres);
549 exchange_doubles(ms, b, state->nhpres_vxi.data(), nnhpres);
550 exchange_doubles(ms, b, state->therm_integral.data(), state->ngtc);
551 exchange_rvecs(ms, b, as_rvec_array(state->x.data()), state->natoms);
552 exchange_rvecs(ms, b, as_rvec_array(state->v.data()), state->natoms);
555 static void copy_state_serial(const t_state *src, t_state *dest)
557 if (dest != src)
559 /* Currently the local state is always a pointer to the global
560 * in serial, so we should never end up here.
561 * TODO: Implement a (trivial) t_state copy once converted to C++.
563 GMX_RELEASE_ASSERT(false, "State copying is currently not implemented in replica exchange");
567 static void scale_velocities(t_state *state, real fac)
569 int i;
571 if (as_rvec_array(state->v.data()))
573 for (i = 0; i < state->natoms; i++)
575 svmul(fac, state->v[i], state->v[i]);
580 static void print_transition_matrix(FILE *fplog, int n, int **nmoves, int *nattempt)
582 int i, j, ntot;
583 float Tprint;
585 ntot = nattempt[0] + nattempt[1];
586 fprintf(fplog, "\n");
587 fprintf(fplog, "Repl");
588 for (i = 0; i < n; i++)
590 fprintf(fplog, " "); /* put the title closer to the center */
592 fprintf(fplog, "Empirical Transition Matrix\n");
594 fprintf(fplog, "Repl");
595 for (i = 0; i < n; i++)
597 fprintf(fplog, "%8d", (i+1));
599 fprintf(fplog, "\n");
601 for (i = 0; i < n; i++)
603 fprintf(fplog, "Repl");
604 for (j = 0; j < n; j++)
606 Tprint = 0.0;
607 if (nmoves[i][j] > 0)
609 Tprint = nmoves[i][j]/(2.0*ntot);
611 fprintf(fplog, "%8.4f", Tprint);
613 fprintf(fplog, "%3d\n", i);
617 static void print_ind(FILE *fplog, const char *leg, int n, int *ind, gmx_bool *bEx)
619 int i;
621 fprintf(fplog, "Repl %2s %2d", leg, ind[0]);
622 for (i = 1; i < n; i++)
624 fprintf(fplog, " %c %2d", (bEx != nullptr && bEx[i]) ? 'x' : ' ', ind[i]);
626 fprintf(fplog, "\n");
629 static void print_allswitchind(FILE *fplog, int n, int *pind, int *allswaps, int *tmpswap)
631 int i;
633 for (i = 0; i < n; i++)
635 tmpswap[i] = allswaps[i];
637 for (i = 0; i < n; i++)
639 allswaps[i] = tmpswap[pind[i]];
642 fprintf(fplog, "\nAccepted Exchanges: ");
643 for (i = 0; i < n; i++)
645 fprintf(fplog, "%d ", pind[i]);
647 fprintf(fplog, "\n");
649 /* the "Order After Exchange" is the state label corresponding to the configuration that
650 started in state listed in order, i.e.
652 3 0 1 2
654 means that the:
655 configuration starting in simulation 3 is now in simulation 0,
656 configuration starting in simulation 0 is now in simulation 1,
657 configuration starting in simulation 1 is now in simulation 2,
658 configuration starting in simulation 2 is now in simulation 3
660 fprintf(fplog, "Order After Exchange: ");
661 for (i = 0; i < n; i++)
663 fprintf(fplog, "%d ", allswaps[i]);
665 fprintf(fplog, "\n\n");
668 static void print_prob(FILE *fplog, const char *leg, int n, real *prob)
670 int i;
671 char buf[8];
673 fprintf(fplog, "Repl %2s ", leg);
674 for (i = 1; i < n; i++)
676 if (prob[i] >= 0)
678 sprintf(buf, "%4.2f", prob[i]);
679 fprintf(fplog, " %3s", buf[0] == '1' ? "1.0" : buf+1);
681 else
683 fprintf(fplog, " ");
686 fprintf(fplog, "\n");
689 static void print_count(FILE *fplog, const char *leg, int n, int *count)
691 int i;
693 fprintf(fplog, "Repl %2s ", leg);
694 for (i = 1; i < n; i++)
696 fprintf(fplog, " %4d", count[i]);
698 fprintf(fplog, "\n");
701 static real calc_delta(FILE *fplog, gmx_bool bPrint, struct gmx_repl_ex *re, int a, int b, int ap, int bp)
704 real ediff, dpV, delta = 0;
705 real *Epot = re->Epot;
706 real *Vol = re->Vol;
707 real **de = re->de;
708 real *beta = re->beta;
710 /* Two cases; we are permuted and not. In all cases, setting ap = a and bp = b will reduce
711 to the non permuted case */
713 switch (re->type)
715 case ereTEMP:
717 * Okabe et. al. Chem. Phys. Lett. 335 (2001) 435-439
719 ediff = Epot[b] - Epot[a];
720 delta = -(beta[bp] - beta[ap])*ediff;
721 break;
722 case ereLAMBDA:
723 /* two cases: when we are permuted, and not. */
724 /* non-permuted:
725 ediff = E_new - E_old
726 = [H_b(x_a) + H_a(x_b)] - [H_b(x_b) + H_a(x_a)]
727 = [H_b(x_a) - H_a(x_a)] + [H_a(x_b) - H_b(x_b)]
728 = de[b][a] + de[a][b] */
730 /* permuted:
731 ediff = E_new - E_old
732 = [H_bp(x_a) + H_ap(x_b)] - [H_bp(x_b) + H_ap(x_a)]
733 = [H_bp(x_a) - H_ap(x_a)] + [H_ap(x_b) - H_bp(x_b)]
734 = [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)]
735 = [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)]
736 = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]) */
737 /* but, in the current code implementation, we flip configurations, not indices . . .
738 So let's examine that.
739 = [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)]
740 = [H_b(x_ap) - H_a(x_ap)] + [H_a(x_bp) - H_b(x_pb)]
741 = (de[b][ap] - de[a][ap]) + (de[a][bp] - de[b][bp]
742 So, if we exchange b<=> bp and a<=> ap, we return to the same result.
743 So the simple solution is to flip the
744 position of perturbed and original indices in the tests.
747 ediff = (de[bp][a] - de[ap][a]) + (de[ap][b] - de[bp][b]);
748 delta = ediff*beta[a]; /* assume all same temperature in this case */
749 break;
750 case ereTL:
751 /* not permuted: */
752 /* delta = reduced E_new - reduced E_old
753 = [beta_b H_b(x_a) + beta_a H_a(x_b)] - [beta_b H_b(x_b) + beta_a H_a(x_a)]
754 = [beta_b H_b(x_a) - beta_a H_a(x_a)] + [beta_a H_a(x_b) - beta_b H_b(x_b)]
755 = [beta_b dH_b(x_a) + beta_b H_a(x_a) - beta_a H_a(x_a)] +
756 [beta_a dH_a(x_b) + beta_a H_b(x_b) - beta_b H_b(x_b)]
757 = [beta_b dH_b(x_a) + [beta_a dH_a(x_b) +
758 beta_b (H_a(x_a) - H_b(x_b)]) - beta_a (H_a(x_a) - H_b(x_b))
759 = beta_b dH_b(x_a) + beta_a dH_a(x_b) - (beta_b - beta_a)(H_b(x_b) - H_a(x_a) */
760 /* delta = beta[b]*de[b][a] + beta[a]*de[a][b] - (beta[b] - beta[a])*(Epot[b] - Epot[a]; */
761 /* permuted (big breath!) */
762 /* delta = reduced E_new - reduced E_old
763 = [beta_bp H_bp(x_a) + beta_ap H_ap(x_b)] - [beta_bp H_bp(x_b) + beta_ap H_ap(x_a)]
764 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
765 = [beta_bp H_bp(x_a) - beta_ap H_ap(x_a)] + [beta_ap H_ap(x_b) - beta_bp H_bp(x_b)]
766 - beta_pb H_a(x_a) + beta_ap H_a(x_a) + beta_pb H_a(x_a) - beta_ap H_a(x_a)
767 - beta_ap H_b(x_b) + beta_bp H_b(x_b) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
768 = [(beta_bp H_bp(x_a) - beta_bp H_a(x_a)) - (beta_ap H_ap(x_a) - beta_ap H_a(x_a))] +
769 [(beta_ap H_ap(x_b) - beta_ap H_b(x_b)) - (beta_bp H_bp(x_b) - beta_bp H_b(x_b))]
770 + beta_pb H_a(x_a) - beta_ap H_a(x_a) + beta_ap H_b(x_b) - beta_bp H_b(x_b)
771 = [beta_bp (H_bp(x_a) - H_a(x_a)) - beta_ap (H_ap(x_a) - H_a(x_a))] +
772 [beta_ap (H_ap(x_b) - H_b(x_b)) - beta_bp (H_bp(x_b) - H_b(x_b))]
773 + beta_pb (H_a(x_a) - H_b(x_b)) - beta_ap (H_a(x_a) - H_b(x_b))
774 = ([beta_bp de[bp][a] - beta_ap de[ap][a]) + beta_ap de[ap][b] - beta_bp de[bp][b])
775 + (beta_pb-beta_ap)(H_a(x_a) - H_b(x_b)) */
776 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]);
777 break;
778 default:
779 gmx_incons("Unknown replica exchange quantity");
781 if (bPrint)
783 fprintf(fplog, "Repl %d <-> %d dE_term = %10.3e (kT)\n", a, b, delta);
785 if (re->bNPT)
787 /* revist the calculation for 5.0. Might be some improvements. */
788 dpV = (beta[ap]*re->pres[ap]-beta[bp]*re->pres[bp])*(Vol[b]-Vol[a])/PRESFAC;
789 if (bPrint)
791 fprintf(fplog, " dpV = %10.3e d = %10.3e\n", dpV, delta + dpV);
793 delta += dpV;
795 return delta;
798 static void
799 test_for_replica_exchange(FILE *fplog,
800 const gmx_multisim_t *ms,
801 struct gmx_repl_ex *re,
802 gmx_enerdata_t *enerd,
803 real vol,
804 gmx_int64_t step,
805 real time)
807 int m, i, j, a, b, ap, bp, i0, i1, tmp;
808 real delta = 0;
809 gmx_bool bPrint, bMultiEx;
810 gmx_bool *bEx = re->bEx;
811 real *prob = re->prob;
812 int *pind = re->destinations; /* permuted index */
813 gmx_bool bEpot = FALSE;
814 gmx_bool bDLambda = FALSE;
815 gmx_bool bVol = FALSE;
816 gmx::ThreeFry2x64<64> rng(re->seed, gmx::RandomDomain::ReplicaExchange);
817 gmx::UniformRealDistribution<real> uniformRealDist;
818 gmx::UniformIntDistribution<int> uniformNreplDist(0, re->nrepl-1);
820 bMultiEx = (re->nex > 1); /* multiple exchanges at each state */
821 fprintf(fplog, "Replica exchange at step %" GMX_PRId64 " time %.5f\n", step, time);
823 if (re->bNPT)
825 for (i = 0; i < re->nrepl; i++)
827 re->Vol[i] = 0;
829 bVol = TRUE;
830 re->Vol[re->repl] = vol;
832 if ((re->type == ereTEMP || re->type == ereTL))
834 for (i = 0; i < re->nrepl; i++)
836 re->Epot[i] = 0;
838 bEpot = TRUE;
839 re->Epot[re->repl] = enerd->term[F_EPOT];
840 /* temperatures of different states*/
841 for (i = 0; i < re->nrepl; i++)
843 re->beta[i] = 1.0/(re->q[ereTEMP][i]*BOLTZ);
846 else
848 for (i = 0; i < re->nrepl; i++)
850 re->beta[i] = 1.0/(re->temp*BOLTZ); /* we have a single temperature */
853 if (re->type == ereLAMBDA || re->type == ereTL)
855 bDLambda = TRUE;
856 /* lambda differences. */
857 /* de[i][j] is the energy of the jth simulation in the ith Hamiltonian
858 minus the energy of the jth simulation in the jth Hamiltonian */
859 for (i = 0; i < re->nrepl; i++)
861 for (j = 0; j < re->nrepl; j++)
863 re->de[i][j] = 0;
866 for (i = 0; i < re->nrepl; i++)
868 re->de[i][re->repl] = (enerd->enerpart_lambda[(int)re->q[ereLAMBDA][i]+1]-enerd->enerpart_lambda[0]);
872 /* now actually do the communication */
873 if (bVol)
875 gmx_sum_sim(re->nrepl, re->Vol, ms);
877 if (bEpot)
879 gmx_sum_sim(re->nrepl, re->Epot, ms);
881 if (bDLambda)
883 for (i = 0; i < re->nrepl; i++)
885 gmx_sum_sim(re->nrepl, re->de[i], ms);
889 /* make a duplicate set of indices for shuffling */
890 for (i = 0; i < re->nrepl; i++)
892 pind[i] = re->ind[i];
895 rng.restart( step, 0 );
897 if (bMultiEx)
899 /* multiple random switch exchange */
900 int nself = 0;
903 for (i = 0; i < re->nex + nself; i++)
905 // For now this is superfluous, but just in case we ever add more
906 // calls in different branches it is safer to always reset the distribution.
907 uniformNreplDist.reset();
909 /* randomly select a pair */
910 /* in theory, could reduce this by identifying only which switches had a nonneglibible
911 probability of occurring (log p > -100) and only operate on those switches */
912 /* find out which state it is from, and what label that state currently has. Likely
913 more work that useful. */
914 i0 = uniformNreplDist(rng);
915 i1 = uniformNreplDist(rng);
916 if (i0 == i1)
918 nself++;
919 continue; /* self-exchange, back up and do it again */
922 a = re->ind[i0]; /* what are the indices of these states? */
923 b = re->ind[i1];
924 ap = pind[i0];
925 bp = pind[i1];
927 bPrint = FALSE; /* too noisy */
928 /* calculate the energy difference */
929 /* if the code changes to flip the STATES, rather than the configurations,
930 use the commented version of the code */
931 /* delta = calc_delta(fplog,bPrint,re,a,b,ap,bp); */
932 delta = calc_delta(fplog, bPrint, re, ap, bp, a, b);
934 /* we actually only use the first space in the prob and bEx array,
935 since there are actually many switches between pairs. */
937 if (delta <= 0)
939 /* accepted */
940 prob[0] = 1;
941 bEx[0] = TRUE;
943 else
945 if (delta > PROBABILITYCUTOFF)
947 prob[0] = 0;
949 else
951 prob[0] = exp(-delta);
953 // roll a number to determine if accepted. For now it is superfluous to
954 // reset, but just in case we ever add more calls in different branches
955 // it is safer to always reset the distribution.
956 uniformRealDist.reset();
957 bEx[0] = uniformRealDist(rng) < prob[0];
959 re->prob_sum[0] += prob[0];
961 if (bEx[0])
963 /* swap the states */
964 tmp = pind[i0];
965 pind[i0] = pind[i1];
966 pind[i1] = tmp;
969 re->nattempt[0]++; /* keep track of total permutation trials here */
970 print_allswitchind(fplog, re->nrepl, pind, re->allswaps, re->tmpswap);
972 else
974 /* standard nearest neighbor replica exchange */
976 m = (step / re->nst) % 2;
977 for (i = 1; i < re->nrepl; i++)
979 a = re->ind[i-1];
980 b = re->ind[i];
982 bPrint = (re->repl == a || re->repl == b);
983 if (i % 2 == m)
985 delta = calc_delta(fplog, bPrint, re, a, b, a, b);
986 if (delta <= 0)
988 /* accepted */
989 prob[i] = 1;
990 bEx[i] = TRUE;
992 else
994 if (delta > PROBABILITYCUTOFF)
996 prob[i] = 0;
998 else
1000 prob[i] = exp(-delta);
1002 // roll a number to determine if accepted. For now it is superfluous to
1003 // reset, but just in case we ever add more calls in different branches
1004 // it is safer to always reset the distribution.
1005 uniformRealDist.reset();
1006 bEx[i] = uniformRealDist(rng) < prob[i];
1008 re->prob_sum[i] += prob[i];
1010 if (bEx[i])
1012 /* swap these two */
1013 tmp = pind[i-1];
1014 pind[i-1] = pind[i];
1015 pind[i] = tmp;
1016 re->nexchange[i]++; /* statistics for back compatibility */
1019 else
1021 prob[i] = -1;
1022 bEx[i] = FALSE;
1025 /* print some statistics */
1026 print_ind(fplog, "ex", re->nrepl, re->ind, bEx);
1027 print_prob(fplog, "pr", re->nrepl, prob);
1028 fprintf(fplog, "\n");
1029 re->nattempt[m]++;
1032 /* record which moves were made and accepted */
1033 for (i = 0; i < re->nrepl; i++)
1035 re->nmoves[re->ind[i]][pind[i]] += 1;
1036 re->nmoves[pind[i]][re->ind[i]] += 1;
1038 fflush(fplog); /* make sure we can see what the last exchange was */
1041 static void
1042 cyclic_decomposition(const int *destinations,
1043 int **cyclic,
1044 gmx_bool *incycle,
1045 const int nrepl,
1046 int *nswap)
1049 int i, j, c, p;
1050 int maxlen = 1;
1051 for (i = 0; i < nrepl; i++)
1053 incycle[i] = FALSE;
1055 for (i = 0; i < nrepl; i++) /* one cycle for each replica */
1057 if (incycle[i])
1059 cyclic[i][0] = -1;
1060 continue;
1062 cyclic[i][0] = i;
1063 incycle[i] = TRUE;
1064 c = 1;
1065 p = i;
1066 for (j = 0; j < nrepl; j++) /* potentially all cycles are part, but we will break first */
1068 p = destinations[p]; /* start permuting */
1069 if (p == i)
1071 cyclic[i][c] = -1;
1072 if (c > maxlen)
1074 maxlen = c;
1076 break; /* we've reached the original element, the cycle is complete, and we marked the end. */
1078 else
1080 cyclic[i][c] = p; /* each permutation gives a new member of the cycle */
1081 incycle[p] = TRUE;
1082 c++;
1086 *nswap = maxlen - 1;
1088 if (debug)
1090 for (i = 0; i < nrepl; i++)
1092 fprintf(debug, "Cycle %d:", i);
1093 for (j = 0; j < nrepl; j++)
1095 if (cyclic[i][j] < 0)
1097 break;
1099 fprintf(debug, "%2d", cyclic[i][j]);
1101 fprintf(debug, "\n");
1103 fflush(debug);
1107 static void
1108 compute_exchange_order(int **cyclic,
1109 int **order,
1110 const int nrepl,
1111 const int maxswap)
1113 int i, j;
1115 for (j = 0; j < maxswap; j++)
1117 for (i = 0; i < nrepl; i++)
1119 if (cyclic[i][j+1] >= 0)
1121 order[cyclic[i][j+1]][j] = cyclic[i][j];
1122 order[cyclic[i][j]][j] = cyclic[i][j+1];
1125 for (i = 0; i < nrepl; i++)
1127 if (order[i][j] < 0)
1129 order[i][j] = i; /* if it's not exchanging, it should stay this round*/
1134 if (debug)
1136 fprintf(debug, "Replica Exchange Order\n");
1137 for (i = 0; i < nrepl; i++)
1139 fprintf(debug, "Replica %d:", i);
1140 for (j = 0; j < maxswap; j++)
1142 if (order[i][j] < 0)
1144 break;
1146 fprintf(debug, "%2d", order[i][j]);
1148 fprintf(debug, "\n");
1150 fflush(debug);
1154 static void
1155 prepare_to_do_exchange(struct gmx_repl_ex *re,
1156 const int replica_id,
1157 int *maxswap,
1158 gmx_bool *bThisReplicaExchanged)
1160 int i, j;
1161 /* Hold the cyclic decomposition of the (multiple) replica
1162 * exchange. */
1163 gmx_bool bAnyReplicaExchanged = FALSE;
1164 *bThisReplicaExchanged = FALSE;
1166 for (i = 0; i < re->nrepl; i++)
1168 if (re->destinations[i] != re->ind[i])
1170 /* only mark as exchanged if the index has been shuffled */
1171 bAnyReplicaExchanged = TRUE;
1172 break;
1175 if (bAnyReplicaExchanged)
1177 /* reinitialize the placeholder arrays */
1178 for (i = 0; i < re->nrepl; i++)
1180 for (j = 0; j < re->nrepl; j++)
1182 re->cyclic[i][j] = -1;
1183 re->order[i][j] = -1;
1187 /* Identify the cyclic decomposition of the permutation (very
1188 * fast if neighbor replica exchange). */
1189 cyclic_decomposition(re->destinations, re->cyclic, re->incycle, re->nrepl, maxswap);
1191 /* Now translate the decomposition into a replica exchange
1192 * order at each step. */
1193 compute_exchange_order(re->cyclic, re->order, re->nrepl, *maxswap);
1195 /* Did this replica do any exchange at any point? */
1196 for (j = 0; j < *maxswap; j++)
1198 if (replica_id != re->order[replica_id][j])
1200 *bThisReplicaExchanged = TRUE;
1201 break;
1207 gmx_bool replica_exchange(FILE *fplog, const t_commrec *cr, struct gmx_repl_ex *re,
1208 t_state *state, gmx_enerdata_t *enerd,
1209 t_state *state_local, gmx_int64_t step, real time)
1211 int j;
1212 int replica_id = 0;
1213 int exchange_partner;
1214 int maxswap = 0;
1215 /* Number of rounds of exchanges needed to deal with any multiple
1216 * exchanges. */
1217 /* Where each replica ends up after the exchange attempt(s). */
1218 /* The order in which multiple exchanges will occur. */
1219 gmx_bool bThisReplicaExchanged = FALSE;
1221 if (MASTER(cr))
1223 replica_id = re->repl;
1224 test_for_replica_exchange(fplog, cr->ms, re, enerd, det(state_local->box), step, time);
1225 prepare_to_do_exchange(re, replica_id, &maxswap, &bThisReplicaExchanged);
1227 /* Do intra-simulation broadcast so all processors belonging to
1228 * each simulation know whether they need to participate in
1229 * collecting the state. Otherwise, they might as well get on with
1230 * the next thing to do. */
1231 if (DOMAINDECOMP(cr))
1233 #if GMX_MPI
1234 MPI_Bcast(&bThisReplicaExchanged, sizeof(gmx_bool), MPI_BYTE, MASTERRANK(cr),
1235 cr->mpi_comm_mygroup);
1236 #endif
1239 if (bThisReplicaExchanged)
1241 /* Exchange the states */
1242 /* Collect the global state on the master node */
1243 if (DOMAINDECOMP(cr))
1245 dd_collect_state(cr->dd, state_local, state);
1247 else
1249 copy_state_serial(state_local, state);
1252 if (MASTER(cr))
1254 /* There will be only one swap cycle with standard replica
1255 * exchange, but there may be multiple swap cycles if we
1256 * allow multiple swaps. */
1258 for (j = 0; j < maxswap; j++)
1260 exchange_partner = re->order[replica_id][j];
1262 if (exchange_partner != replica_id)
1264 /* Exchange the global states between the master nodes */
1265 if (debug)
1267 fprintf(debug, "Exchanging %d with %d\n", replica_id, exchange_partner);
1269 exchange_state(cr->ms, exchange_partner, state);
1272 /* For temperature-type replica exchange, we need to scale
1273 * the velocities. */
1274 if (re->type == ereTEMP || re->type == ereTL)
1276 scale_velocities(state, sqrt(re->q[ereTEMP][replica_id]/re->q[ereTEMP][re->destinations[replica_id]]));
1281 /* With domain decomposition the global state is distributed later */
1282 if (!DOMAINDECOMP(cr))
1284 /* Copy the global state to the local state data structure */
1285 copy_state_serial(state, state_local);
1289 return bThisReplicaExchanged;
1292 void print_replica_exchange_statistics(FILE *fplog, struct gmx_repl_ex *re)
1294 int i;
1296 fprintf(fplog, "\nReplica exchange statistics\n");
1298 if (re->nex == 0)
1300 fprintf(fplog, "Repl %d attempts, %d odd, %d even\n",
1301 re->nattempt[0]+re->nattempt[1], re->nattempt[1], re->nattempt[0]);
1303 fprintf(fplog, "Repl average probabilities:\n");
1304 for (i = 1; i < re->nrepl; i++)
1306 if (re->nattempt[i%2] == 0)
1308 re->prob[i] = 0;
1310 else
1312 re->prob[i] = re->prob_sum[i]/re->nattempt[i%2];
1315 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1316 print_prob(fplog, "", re->nrepl, re->prob);
1318 fprintf(fplog, "Repl number of exchanges:\n");
1319 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1320 print_count(fplog, "", re->nrepl, re->nexchange);
1322 fprintf(fplog, "Repl average number of exchanges:\n");
1323 for (i = 1; i < re->nrepl; i++)
1325 if (re->nattempt[i%2] == 0)
1327 re->prob[i] = 0;
1329 else
1331 re->prob[i] = ((real)re->nexchange[i])/re->nattempt[i%2];
1334 print_ind(fplog, "", re->nrepl, re->ind, nullptr);
1335 print_prob(fplog, "", re->nrepl, re->prob);
1337 fprintf(fplog, "\n");
1339 /* print the transition matrix */
1340 print_transition_matrix(fplog, re->nrepl, re->nmoves, re->nattempt);