Merge branch 'master' of git://git.gromacs.org/gromacs
[gromacs/adressmacs.git] / src / kernel / md.c
blobb0a1e5a218edf68dde5f3909e6e3daddc48a8edf
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
3 *
4 * This source code is part of
5 *
6 * G R O M A C S
7 *
8 * GROningen MAchine for Chemical Simulations
9 *
10 * VERSION 3.2.0
11 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13 * Copyright (c) 2001-2004, The GROMACS development team,
14 * check out http://www.gromacs.org for more information.
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * as published by the Free Software Foundation; either version 2
19 * of the License, or (at your option) any later version.
21 * If you want to redistribute modifications, please consider that
22 * scientific software is very special. Version control is crucial -
23 * bugs must be traceable. We will be happy to consider code for
24 * inclusion in the official distribution, but derived work must not
25 * be called official GROMACS. Details are found in the README & COPYING
26 * files - if they are missing, get the official version at www.gromacs.org.
28 * To help us fund GROMACS development, we humbly ask that you cite
29 * the papers on the package - you can find them in the top README file.
31 * For more info, check our website at http://www.gromacs.org
33 * And Hey:
34 * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
40 #include <signal.h>
41 #include <stdlib.h>
43 #if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
44 /* _isnan() */
45 #include <float.h>
46 #endif
48 #include "typedefs.h"
49 #include "smalloc.h"
50 #include "sysstuff.h"
51 #include "vec.h"
52 #include "statutil.h"
53 #include "vcm.h"
54 #include "mdebin.h"
55 #include "nrnb.h"
56 #include "calcmu.h"
57 #include "index.h"
58 #include "vsite.h"
59 #include "update.h"
60 #include "ns.h"
61 #include "trnio.h"
62 #include "xtcio.h"
63 #include "mdrun.h"
64 #include "confio.h"
65 #include "network.h"
66 #include "pull.h"
67 #include "xvgr.h"
68 #include "physics.h"
69 #include "names.h"
70 #include "xmdrun.h"
71 #include "ionize.h"
72 #include "disre.h"
73 #include "orires.h"
74 #include "dihre.h"
75 #include "pppm.h"
76 #include "pme.h"
77 #include "mdatoms.h"
78 #include "repl_ex.h"
79 #include "qmmm.h"
80 #include "mpelogging.h"
81 #include "domdec.h"
82 #include "partdec.h"
83 #include "topsort.h"
84 #include "coulomb.h"
85 #include "constr.h"
86 #include "shellfc.h"
87 #include "compute_io.h"
88 #include "mvdata.h"
89 #include "checkpoint.h"
90 #include "mtop_util.h"
91 #include "sighandler.h"
92 #include "membed.h"
94 #ifdef GMX_LIB_MPI
95 #include <mpi.h>
96 #endif
97 #ifdef GMX_THREADS
98 #include "tmpi.h"
99 #endif
101 #ifdef GMX_FAHCORE
102 #include "corewrap.h"
103 #endif
106 /* simulation conditions to transmit. Keep in mind that they are
107 transmitted to other nodes through an MPI_Reduce after
108 casting them to a real (so the signals can be sent together with other
109 data). This means that the only meaningful values are positive,
110 negative or zero. */
111 enum { eglsNABNSB, eglsCHKPT, eglsSTOPCOND, eglsRESETCOUNTERS, eglsNR };
112 /* Is the signal in one simulation independent of other simulations? */
113 gmx_bool gs_simlocal[eglsNR] = { TRUE, FALSE, FALSE, TRUE };
115 typedef struct {
116 int nstms; /* The frequency for intersimulation communication */
117 int sig[eglsNR]; /* The signal set by one process in do_md */
118 int set[eglsNR]; /* The communicated signal, equal for all processes */
119 } globsig_t;
122 static int multisim_min(const gmx_multisim_t *ms,int nmin,int n)
124 int *buf;
125 gmx_bool bPos,bEqual;
126 int s,d;
128 snew(buf,ms->nsim);
129 buf[ms->sim] = n;
130 gmx_sumi_sim(ms->nsim,buf,ms);
131 bPos = TRUE;
132 bEqual = TRUE;
133 for(s=0; s<ms->nsim; s++)
135 bPos = bPos && (buf[s] > 0);
136 bEqual = bEqual && (buf[s] == buf[0]);
138 if (bPos)
140 if (bEqual)
142 nmin = min(nmin,buf[0]);
144 else
146 /* Find the least common multiple */
147 for(d=2; d<nmin; d++)
149 s = 0;
150 while (s < ms->nsim && d % buf[s] == 0)
152 s++;
154 if (s == ms->nsim)
156 /* We found the LCM and it is less than nmin */
157 nmin = d;
158 break;
163 sfree(buf);
165 return nmin;
168 static int multisim_nstsimsync(const t_commrec *cr,
169 const t_inputrec *ir,int repl_ex_nst)
171 int nmin;
173 if (MASTER(cr))
175 nmin = INT_MAX;
176 nmin = multisim_min(cr->ms,nmin,ir->nstlist);
177 nmin = multisim_min(cr->ms,nmin,ir->nstcalcenergy);
178 nmin = multisim_min(cr->ms,nmin,repl_ex_nst);
179 if (nmin == INT_MAX)
181 gmx_fatal(FARGS,"Can not find an appropriate interval for inter-simulation communication, since nstlist, nstcalcenergy and -replex are all <= 0");
183 /* Avoid inter-simulation communication at every (second) step */
184 if (nmin <= 2)
186 nmin = 10;
190 gmx_bcast(sizeof(int),&nmin,cr);
192 return nmin;
195 static void init_global_signals(globsig_t *gs,const t_commrec *cr,
196 const t_inputrec *ir,int repl_ex_nst)
198 int i;
200 if (MULTISIM(cr))
202 gs->nstms = multisim_nstsimsync(cr,ir,repl_ex_nst);
203 if (debug)
205 fprintf(debug,"Syncing simulations for checkpointing and termination every %d steps\n",gs->nstms);
208 else
210 gs->nstms = 1;
213 for(i=0; i<eglsNR; i++)
215 gs->sig[i] = 0;
216 gs->set[i] = 0;
220 static void copy_coupling_state(t_state *statea,t_state *stateb,
221 gmx_ekindata_t *ekinda,gmx_ekindata_t *ekindb, t_grpopts* opts)
224 /* MRS note -- might be able to get rid of some of the arguments. Look over it when it's all debugged */
226 int i,j,nc;
228 /* Make sure we have enough space for x and v */
229 if (statea->nalloc > stateb->nalloc)
231 stateb->nalloc = statea->nalloc;
232 srenew(stateb->x,stateb->nalloc);
233 srenew(stateb->v,stateb->nalloc);
236 stateb->natoms = statea->natoms;
237 stateb->ngtc = statea->ngtc;
238 stateb->nnhpres = statea->nnhpres;
239 stateb->veta = statea->veta;
240 if (ekinda)
242 copy_mat(ekinda->ekin,ekindb->ekin);
243 for (i=0; i<stateb->ngtc; i++)
245 ekindb->tcstat[i].T = ekinda->tcstat[i].T;
246 ekindb->tcstat[i].Th = ekinda->tcstat[i].Th;
247 copy_mat(ekinda->tcstat[i].ekinh,ekindb->tcstat[i].ekinh);
248 copy_mat(ekinda->tcstat[i].ekinf,ekindb->tcstat[i].ekinf);
249 ekindb->tcstat[i].ekinscalef_nhc = ekinda->tcstat[i].ekinscalef_nhc;
250 ekindb->tcstat[i].ekinscaleh_nhc = ekinda->tcstat[i].ekinscaleh_nhc;
251 ekindb->tcstat[i].vscale_nhc = ekinda->tcstat[i].vscale_nhc;
254 copy_rvecn(statea->x,stateb->x,0,stateb->natoms);
255 copy_rvecn(statea->v,stateb->v,0,stateb->natoms);
256 copy_mat(statea->box,stateb->box);
257 copy_mat(statea->box_rel,stateb->box_rel);
258 copy_mat(statea->boxv,stateb->boxv);
260 for (i = 0; i<stateb->ngtc; i++)
262 nc = i*opts->nhchainlength;
263 for (j=0; j<opts->nhchainlength; j++)
265 stateb->nosehoover_xi[nc+j] = statea->nosehoover_xi[nc+j];
266 stateb->nosehoover_vxi[nc+j] = statea->nosehoover_vxi[nc+j];
269 if (stateb->nhpres_xi != NULL)
271 for (i = 0; i<stateb->nnhpres; i++)
273 nc = i*opts->nhchainlength;
274 for (j=0; j<opts->nhchainlength; j++)
276 stateb->nhpres_xi[nc+j] = statea->nhpres_xi[nc+j];
277 stateb->nhpres_vxi[nc+j] = statea->nhpres_vxi[nc+j];
283 static real compute_conserved_from_auxiliary(t_inputrec *ir, t_state *state, t_extmass *MassQ)
285 real quantity = 0;
286 switch (ir->etc)
288 case etcNO:
289 break;
290 case etcBERENDSEN:
291 break;
292 case etcNOSEHOOVER:
293 quantity = NPT_energy(ir,state,MassQ);
294 break;
295 case etcVRESCALE:
296 quantity = vrescale_energy(&(ir->opts),state->therm_integral);
297 break;
298 default:
299 break;
301 return quantity;
304 static void compute_globals(FILE *fplog, gmx_global_stat_t gstat, t_commrec *cr, t_inputrec *ir,
305 t_forcerec *fr, gmx_ekindata_t *ekind,
306 t_state *state, t_state *state_global, t_mdatoms *mdatoms,
307 t_nrnb *nrnb, t_vcm *vcm, gmx_wallcycle_t wcycle,
308 gmx_enerdata_t *enerd,tensor force_vir, tensor shake_vir, tensor total_vir,
309 tensor pres, rvec mu_tot, gmx_constr_t constr,
310 globsig_t *gs,gmx_bool bInterSimGS,
311 matrix box, gmx_mtop_t *top_global, real *pcurr,
312 int natoms, gmx_bool *bSumEkinhOld, int flags)
314 int i,gsi;
315 real gs_buf[eglsNR];
316 tensor corr_vir,corr_pres,shakeall_vir;
317 gmx_bool bEner,bPres,bTemp, bVV;
318 gmx_bool bRerunMD, bStopCM, bGStat, bIterate,
319 bFirstIterate,bReadEkin,bEkinAveVel,bScaleEkin, bConstrain;
320 real ekin,temp,prescorr,enercorr,dvdlcorr;
322 /* translate CGLO flags to gmx_booleans */
323 bRerunMD = flags & CGLO_RERUNMD;
324 bStopCM = flags & CGLO_STOPCM;
325 bGStat = flags & CGLO_GSTAT;
327 bReadEkin = (flags & CGLO_READEKIN);
328 bScaleEkin = (flags & CGLO_SCALEEKIN);
329 bEner = flags & CGLO_ENERGY;
330 bTemp = flags & CGLO_TEMPERATURE;
331 bPres = (flags & CGLO_PRESSURE);
332 bConstrain = (flags & CGLO_CONSTRAINT);
333 bIterate = (flags & CGLO_ITERATE);
334 bFirstIterate = (flags & CGLO_FIRSTITERATE);
336 /* we calculate a full state kinetic energy either with full-step velocity verlet
337 or half step where we need the pressure */
339 bEkinAveVel = (ir->eI==eiVV || (ir->eI==eiVVAK && bPres) || bReadEkin);
341 /* in initalization, it sums the shake virial in vv, and to
342 sums ekinh_old in leapfrog (or if we are calculating ekinh_old) for other reasons */
344 /* ########## Kinetic energy ############## */
346 if (bTemp)
348 /* Non-equilibrium MD: this is parallellized, but only does communication
349 * when there really is NEMD.
352 if (PAR(cr) && (ekind->bNEMD))
354 accumulate_u(cr,&(ir->opts),ekind);
356 debug_gmx();
357 if (bReadEkin)
359 restore_ekinstate_from_state(cr,ekind,&state_global->ekinstate);
361 else
364 calc_ke_part(state,&(ir->opts),mdatoms,ekind,nrnb,bEkinAveVel,bIterate);
367 debug_gmx();
369 /* Calculate center of mass velocity if necessary, also parallellized */
370 if (bStopCM && !bRerunMD && bEner)
372 calc_vcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms,
373 state->x,state->v,vcm);
377 if (bTemp || bPres || bEner || bConstrain)
379 if (!bGStat)
381 /* We will not sum ekinh_old,
382 * so signal that we still have to do it.
384 *bSumEkinhOld = TRUE;
387 else
389 if (gs != NULL)
391 for(i=0; i<eglsNR; i++)
393 gs_buf[i] = gs->sig[i];
396 if (PAR(cr))
398 wallcycle_start(wcycle,ewcMoveE);
399 GMX_MPE_LOG(ev_global_stat_start);
400 global_stat(fplog,gstat,cr,enerd,force_vir,shake_vir,mu_tot,
401 ir,ekind,constr,vcm,
402 gs != NULL ? eglsNR : 0,gs_buf,
403 top_global,state,
404 *bSumEkinhOld,flags);
405 GMX_MPE_LOG(ev_global_stat_finish);
406 wallcycle_stop(wcycle,ewcMoveE);
408 if (gs != NULL)
410 if (MULTISIM(cr) && bInterSimGS)
412 if (MASTER(cr))
414 /* Communicate the signals between the simulations */
415 gmx_sum_sim(eglsNR,gs_buf,cr->ms);
417 /* Communicate the signals form the master to the others */
418 gmx_bcast(eglsNR*sizeof(gs_buf[0]),gs_buf,cr);
420 for(i=0; i<eglsNR; i++)
422 if (bInterSimGS || gs_simlocal[i])
424 /* Set the communicated signal only when it is non-zero,
425 * since signals might not be processed at each MD step.
427 gsi = (gs_buf[i] >= 0 ?
428 (int)(gs_buf[i] + 0.5) :
429 (int)(gs_buf[i] - 0.5));
430 if (gsi != 0)
432 gs->set[i] = gsi;
434 /* Turn off the local signal */
435 gs->sig[i] = 0;
439 *bSumEkinhOld = FALSE;
443 if (!ekind->bNEMD && debug && bTemp && (vcm->nr > 0))
445 correct_ekin(debug,
446 mdatoms->start,mdatoms->start+mdatoms->homenr,
447 state->v,vcm->group_p[0],
448 mdatoms->massT,mdatoms->tmass,ekind->ekin);
451 if (bEner) {
452 /* Do center of mass motion removal */
453 if (bStopCM && !bRerunMD) /* is this correct? Does it get called too often with this logic? */
455 check_cm_grp(fplog,vcm,ir,1);
456 do_stopcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms->cVCM,
457 state->x,state->v,vcm);
458 inc_nrnb(nrnb,eNR_STOPCM,mdatoms->homenr);
462 if (bTemp)
464 /* Sum the kinetic energies of the groups & calc temp */
465 /* compute full step kinetic energies if vv, or if vv-avek and we are computing the pressure with IR_NPT_TROTTER */
466 /* three maincase: VV with AveVel (md-vv), vv with AveEkin (md-vv-avek), leap with AveEkin (md).
467 Leap with AveVel is not supported; it's not clear that it will actually work.
468 bEkinAveVel: If TRUE, we simply multiply ekin by ekinscale to get a full step kinetic energy.
469 If FALSE, we average ekinh_old and ekinh*ekinscale_nhc to get an averaged half step kinetic energy.
470 bSaveEkinOld: If TRUE (in the case of iteration = bIterate is TRUE), we don't reset the ekinscale_nhc.
471 If FALSE, we go ahead and erase over it.
473 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,&(enerd->term[F_DKDL]),
474 bEkinAveVel,bIterate,bScaleEkin);
476 enerd->term[F_EKIN] = trace(ekind->ekin);
479 /* ########## Long range energy information ###### */
481 if (bEner || bPres || bConstrain)
483 calc_dispcorr(fplog,ir,fr,0,top_global->natoms,box,state->lambda,
484 corr_pres,corr_vir,&prescorr,&enercorr,&dvdlcorr);
487 if (bEner && bFirstIterate)
489 enerd->term[F_DISPCORR] = enercorr;
490 enerd->term[F_EPOT] += enercorr;
491 enerd->term[F_DVDL] += dvdlcorr;
492 if (fr->efep != efepNO) {
493 enerd->dvdl_lin += dvdlcorr;
497 /* ########## Now pressure ############## */
498 if (bPres || bConstrain)
501 m_add(force_vir,shake_vir,total_vir);
503 /* Calculate pressure and apply LR correction if PPPM is used.
504 * Use the box from last timestep since we already called update().
507 enerd->term[F_PRES] = calc_pres(fr->ePBC,ir->nwall,box,ekind->ekin,total_vir,pres,
508 (fr->eeltype==eelPPPM)?enerd->term[F_COUL_RECIP]:0.0);
510 /* Calculate long range corrections to pressure and energy */
511 /* this adds to enerd->term[F_PRES] and enerd->term[F_ETOT],
512 and computes enerd->term[F_DISPCORR]. Also modifies the
513 total_vir and pres tesors */
515 m_add(total_vir,corr_vir,total_vir);
516 m_add(pres,corr_pres,pres);
517 enerd->term[F_PDISPCORR] = prescorr;
518 enerd->term[F_PRES] += prescorr;
519 *pcurr = enerd->term[F_PRES];
520 /* calculate temperature using virial */
521 enerd->term[F_VTEMP] = calc_temp(trace(total_vir),ir->opts.nrdf[0]);
527 /* Definitions for convergence of iterated constraints */
529 /* iterate constraints up to 50 times */
530 #define MAXITERCONST 50
532 /* data type */
533 typedef struct
535 real f,fprev,x,xprev;
536 int iter_i;
537 gmx_bool bIterate;
538 real allrelerr[MAXITERCONST+2];
539 int num_close; /* number of "close" violations, caused by limited precision. */
540 } gmx_iterate_t;
542 #ifdef GMX_DOUBLE
543 #define CONVERGEITER 0.000000001
544 #define CLOSE_ENOUGH 0.000001000
545 #else
546 #define CONVERGEITER 0.0001
547 #define CLOSE_ENOUGH 0.0050
548 #endif
550 /* we want to keep track of the close calls. If there are too many, there might be some other issues.
551 so we make sure that it's either less than some predetermined number, or if more than that number,
552 only some small fraction of the total. */
553 #define MAX_NUMBER_CLOSE 50
554 #define FRACTION_CLOSE 0.001
556 /* maximum length of cyclic traps to check, emerging from limited numerical precision */
557 #define CYCLEMAX 20
559 static void gmx_iterate_init(gmx_iterate_t *iterate,gmx_bool bIterate)
561 int i;
563 iterate->iter_i = 0;
564 iterate->bIterate = bIterate;
565 iterate->num_close = 0;
566 for (i=0;i<MAXITERCONST+2;i++)
568 iterate->allrelerr[i] = 0;
572 static gmx_bool done_iterating(const t_commrec *cr,FILE *fplog, int nsteps, gmx_iterate_t *iterate, gmx_bool bFirstIterate, real fom, real *newf)
574 /* monitor convergence, and use a secant search to propose new
575 values.
576 x_{i} - x_{i-1}
577 The secant method computes x_{i+1} = x_{i} - f(x_{i}) * ---------------------
578 f(x_{i}) - f(x_{i-1})
580 The function we are trying to zero is fom-x, where fom is the
581 "figure of merit" which is the pressure (or the veta value) we
582 would get by putting in an old value of the pressure or veta into
583 the incrementor function for the step or half step. I have
584 verified that this gives the same answer as self consistent
585 iteration, usually in many fewer steps, especially for small tau_p.
587 We could possibly eliminate an iteration with proper use
588 of the value from the previous step, but that would take a bit
589 more bookkeeping, especially for veta, since tests indicate the
590 function of veta on the last step is not sufficiently close to
591 guarantee convergence this step. This is
592 good enough for now. On my tests, I could use tau_p down to
593 0.02, which is smaller that would ever be necessary in
594 practice. Generally, 3-5 iterations will be sufficient */
596 real relerr,err,xmin;
597 char buf[256];
598 int i;
599 gmx_bool incycle;
601 if (bFirstIterate)
603 iterate->x = fom;
604 iterate->f = fom-iterate->x;
605 iterate->xprev = 0;
606 iterate->fprev = 0;
607 *newf = fom;
609 else
611 iterate->f = fom-iterate->x; /* we want to zero this difference */
612 if ((iterate->iter_i > 1) && (iterate->iter_i < MAXITERCONST))
614 if (iterate->f==iterate->fprev)
616 *newf = iterate->f;
618 else
620 *newf = iterate->x - (iterate->x-iterate->xprev)*(iterate->f)/(iterate->f-iterate->fprev);
623 else
625 /* just use self-consistent iteration the first step to initialize, or
626 if it's not converging (which happens occasionally -- need to investigate why) */
627 *newf = fom;
630 /* Consider a slight shortcut allowing us to exit one sooner -- we check the
631 difference between the closest of x and xprev to the new
632 value. To be 100% certain, we should check the difference between
633 the last result, and the previous result, or
635 relerr = (fabs((x-xprev)/fom));
637 but this is pretty much never necessary under typical conditions.
638 Checking numerically, it seems to lead to almost exactly the same
639 trajectories, but there are small differences out a few decimal
640 places in the pressure, and eventually in the v_eta, but it could
641 save an interation.
643 if (fabs(*newf-x) < fabs(*newf - xprev)) { xmin = x;} else { xmin = xprev;}
644 relerr = (fabs((*newf-xmin) / *newf));
647 err = fabs((iterate->f-iterate->fprev));
648 relerr = fabs(err/fom);
650 iterate->allrelerr[iterate->iter_i] = relerr;
652 if (iterate->iter_i > 0)
654 if (debug)
656 fprintf(debug,"Iterating NPT constraints: %6i %20.12f%14.6g%20.12f\n",
657 iterate->iter_i,fom,relerr,*newf);
660 if ((relerr < CONVERGEITER) || (err < CONVERGEITER) || (fom==0) || ((iterate->x == iterate->xprev) && iterate->iter_i > 1))
662 iterate->bIterate = FALSE;
663 if (debug)
665 fprintf(debug,"Iterating NPT constraints: CONVERGED\n");
667 return TRUE;
669 if (iterate->iter_i > MAXITERCONST)
671 if (relerr < CLOSE_ENOUGH)
673 incycle = FALSE;
674 for (i=1;i<CYCLEMAX;i++) {
675 if ((iterate->allrelerr[iterate->iter_i-(1+i)] == iterate->allrelerr[iterate->iter_i-1]) &&
676 (iterate->allrelerr[iterate->iter_i-(1+i)] == iterate->allrelerr[iterate->iter_i-(1+2*i)])) {
677 incycle = TRUE;
678 if (debug)
680 fprintf(debug,"Exiting from an NPT iterating cycle of length %d\n",i);
682 break;
686 if (incycle) {
687 /* step 1: trapped in a numerical attractor */
688 /* we are trapped in a numerical attractor, and can't converge any more, and are close to the final result.
689 Better to give up convergence here than have the simulation die.
691 iterate->num_close++;
692 return TRUE;
694 else
696 /* Step #2: test if we are reasonably close for other reasons, then monitor the number. If not, die */
698 /* how many close calls have we had? If less than a few, we're OK */
699 if (iterate->num_close < MAX_NUMBER_CLOSE)
701 sprintf(buf,"Slight numerical convergence deviation with NPT at step %d, relative error only %10.5g, likely not a problem, continuing\n",nsteps,relerr);
702 md_print_warning(cr,fplog,buf);
703 iterate->num_close++;
704 return TRUE;
705 /* if more than a few, check the total fraction. If too high, die. */
706 } else if (iterate->num_close/(double)nsteps > FRACTION_CLOSE) {
707 gmx_fatal(FARGS,"Could not converge NPT constraints, too many exceptions (%d%%\n",iterate->num_close/(double)nsteps);
711 else
713 gmx_fatal(FARGS,"Could not converge NPT constraints\n");
718 iterate->xprev = iterate->x;
719 iterate->x = *newf;
720 iterate->fprev = iterate->f;
721 iterate->iter_i++;
723 return FALSE;
726 static void check_nst_param(FILE *fplog,t_commrec *cr,
727 const char *desc_nst,int nst,
728 const char *desc_p,int *p)
730 char buf[STRLEN];
732 if (*p > 0 && *p % nst != 0)
734 /* Round up to the next multiple of nst */
735 *p = ((*p)/nst + 1)*nst;
736 sprintf(buf,"NOTE: %s changes %s to %d\n",desc_nst,desc_p,*p);
737 md_print_warning(cr,fplog,buf);
741 static void reset_all_counters(FILE *fplog,t_commrec *cr,
742 gmx_large_int_t step,
743 gmx_large_int_t *step_rel,t_inputrec *ir,
744 gmx_wallcycle_t wcycle,t_nrnb *nrnb,
745 gmx_runtime_t *runtime)
747 char buf[STRLEN],sbuf[STEPSTRSIZE];
749 /* Reset all the counters related to performance over the run */
750 sprintf(buf,"Step %s: resetting all time and cycle counters\n",
751 gmx_step_str(step,sbuf));
752 md_print_warning(cr,fplog,buf);
754 wallcycle_stop(wcycle,ewcRUN);
755 wallcycle_reset_all(wcycle);
756 if (DOMAINDECOMP(cr))
758 reset_dd_statistics_counters(cr->dd);
760 init_nrnb(nrnb);
761 ir->init_step += *step_rel;
762 ir->nsteps -= *step_rel;
763 *step_rel = 0;
764 wallcycle_start(wcycle,ewcRUN);
765 runtime_start(runtime);
766 print_date_and_time(fplog,cr->nodeid,"Restarted time",runtime);
769 static void min_zero(int *n,int i)
771 if (i > 0 && (*n == 0 || i < *n))
773 *n = i;
777 static int lcd4(int i1,int i2,int i3,int i4)
779 int nst;
781 nst = 0;
782 min_zero(&nst,i1);
783 min_zero(&nst,i2);
784 min_zero(&nst,i3);
785 min_zero(&nst,i4);
786 if (nst == 0)
788 gmx_incons("All 4 inputs for determininig nstglobalcomm are <= 0");
791 while (nst > 1 && ((i1 > 0 && i1 % nst != 0) ||
792 (i2 > 0 && i2 % nst != 0) ||
793 (i3 > 0 && i3 % nst != 0) ||
794 (i4 > 0 && i4 % nst != 0)))
796 nst--;
799 return nst;
802 static int check_nstglobalcomm(FILE *fplog,t_commrec *cr,
803 int nstglobalcomm,t_inputrec *ir)
805 char buf[STRLEN];
807 if (!EI_DYNAMICS(ir->eI))
809 nstglobalcomm = 1;
812 if (nstglobalcomm == -1)
814 if (!(ir->nstcalcenergy > 0 ||
815 ir->nstlist > 0 ||
816 ir->etc != etcNO ||
817 ir->epc != epcNO))
819 nstglobalcomm = 10;
820 if (ir->nstenergy > 0 && ir->nstenergy < nstglobalcomm)
822 nstglobalcomm = ir->nstenergy;
825 else
827 /* Ensure that we do timely global communication for
828 * (possibly) each of the four following options.
830 nstglobalcomm = lcd4(ir->nstcalcenergy,
831 ir->nstlist,
832 ir->etc != etcNO ? ir->nsttcouple : 0,
833 ir->epc != epcNO ? ir->nstpcouple : 0);
836 else
838 if (ir->nstlist > 0 &&
839 nstglobalcomm > ir->nstlist && nstglobalcomm % ir->nstlist != 0)
841 nstglobalcomm = (nstglobalcomm / ir->nstlist)*ir->nstlist;
842 sprintf(buf,"WARNING: nstglobalcomm is larger than nstlist, but not a multiple, setting it to %d\n",nstglobalcomm);
843 md_print_warning(cr,fplog,buf);
845 if (ir->nstcalcenergy > 0)
847 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
848 "nstcalcenergy",&ir->nstcalcenergy);
850 if (ir->etc != etcNO && ir->nsttcouple > 0)
852 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
853 "nsttcouple",&ir->nsttcouple);
855 if (ir->epc != epcNO && ir->nstpcouple > 0)
857 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
858 "nstpcouple",&ir->nstpcouple);
861 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
862 "nstenergy",&ir->nstenergy);
864 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
865 "nstlog",&ir->nstlog);
868 if (ir->comm_mode != ecmNO && ir->nstcomm < nstglobalcomm)
870 sprintf(buf,"WARNING: Changing nstcomm from %d to %d\n",
871 ir->nstcomm,nstglobalcomm);
872 md_print_warning(cr,fplog,buf);
873 ir->nstcomm = nstglobalcomm;
876 return nstglobalcomm;
879 void check_ir_old_tpx_versions(t_commrec *cr,FILE *fplog,
880 t_inputrec *ir,gmx_mtop_t *mtop)
882 /* Check required for old tpx files */
883 if (IR_TWINRANGE(*ir) && ir->nstlist > 1 &&
884 ir->nstcalcenergy % ir->nstlist != 0)
886 md_print_warning(cr,fplog,"Old tpr file with twin-range settings: modifying energy calculation and/or T/P-coupling frequencies");
888 if (gmx_mtop_ftype_count(mtop,F_CONSTR) +
889 gmx_mtop_ftype_count(mtop,F_CONSTRNC) > 0 &&
890 ir->eConstrAlg == econtSHAKE)
892 md_print_warning(cr,fplog,"With twin-range cut-off's and SHAKE the virial and pressure are incorrect");
893 if (ir->epc != epcNO)
895 gmx_fatal(FARGS,"Can not do pressure coupling with twin-range cut-off's and SHAKE");
898 check_nst_param(fplog,cr,"nstlist",ir->nstlist,
899 "nstcalcenergy",&ir->nstcalcenergy);
900 if (ir->epc != epcNO)
902 check_nst_param(fplog,cr,"nstlist",ir->nstlist,
903 "nstpcouple",&ir->nstpcouple);
905 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
906 "nstenergy",&ir->nstenergy);
907 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
908 "nstlog",&ir->nstlog);
909 if (ir->efep != efepNO)
911 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
912 "nstdhdl",&ir->nstdhdl);
917 typedef struct {
918 gmx_bool bGStatEveryStep;
919 gmx_large_int_t step_ns;
920 gmx_large_int_t step_nscheck;
921 gmx_large_int_t nns;
922 matrix scale_tot;
923 int nabnsb;
924 double s1;
925 double s2;
926 double ab;
927 double lt_runav;
928 double lt_runav2;
929 } gmx_nlheur_t;
931 static void reset_nlistheuristics(gmx_nlheur_t *nlh,gmx_large_int_t step)
933 nlh->lt_runav = 0;
934 nlh->lt_runav2 = 0;
935 nlh->step_nscheck = step;
938 static void init_nlistheuristics(gmx_nlheur_t *nlh,
939 gmx_bool bGStatEveryStep,gmx_large_int_t step)
941 nlh->bGStatEveryStep = bGStatEveryStep;
942 nlh->nns = 0;
943 nlh->nabnsb = 0;
944 nlh->s1 = 0;
945 nlh->s2 = 0;
946 nlh->ab = 0;
948 reset_nlistheuristics(nlh,step);
951 static void update_nliststatistics(gmx_nlheur_t *nlh,gmx_large_int_t step)
953 gmx_large_int_t nl_lt;
954 char sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
956 /* Determine the neighbor list life time */
957 nl_lt = step - nlh->step_ns;
958 if (debug)
960 fprintf(debug,"%d atoms beyond ns buffer, updating neighbor list after %s steps\n",nlh->nabnsb,gmx_step_str(nl_lt,sbuf));
962 nlh->nns++;
963 nlh->s1 += nl_lt;
964 nlh->s2 += nl_lt*nl_lt;
965 nlh->ab += nlh->nabnsb;
966 if (nlh->lt_runav == 0)
968 nlh->lt_runav = nl_lt;
969 /* Initialize the fluctuation average
970 * such that at startup we check after 0 steps.
972 nlh->lt_runav2 = sqr(nl_lt/2.0);
974 /* Running average with 0.9 gives an exp. history of 9.5 */
975 nlh->lt_runav2 = 0.9*nlh->lt_runav2 + 0.1*sqr(nlh->lt_runav - nl_lt);
976 nlh->lt_runav = 0.9*nlh->lt_runav + 0.1*nl_lt;
977 if (nlh->bGStatEveryStep)
979 /* Always check the nlist validity */
980 nlh->step_nscheck = step;
982 else
984 /* We check after: <life time> - 2*sigma
985 * The factor 2 is quite conservative,
986 * but we assume that with nstlist=-1 the user
987 * prefers exact integration over performance.
989 nlh->step_nscheck = step
990 + (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)) - 1;
992 if (debug)
994 fprintf(debug,"nlist life time %s run av. %4.1f sig %3.1f check %s check with -gcom %d\n",
995 gmx_step_str(nl_lt,sbuf),nlh->lt_runav,sqrt(nlh->lt_runav2),
996 gmx_step_str(nlh->step_nscheck-step+1,sbuf2),
997 (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)));
1001 static void set_nlistheuristics(gmx_nlheur_t *nlh,gmx_bool bReset,gmx_large_int_t step)
1003 int d;
1005 if (bReset)
1007 reset_nlistheuristics(nlh,step);
1009 else
1011 update_nliststatistics(nlh,step);
1014 nlh->step_ns = step;
1015 /* Initialize the cumulative coordinate scaling matrix */
1016 clear_mat(nlh->scale_tot);
1017 for(d=0; d<DIM; d++)
1019 nlh->scale_tot[d][d] = 1.0;
1023 static void rerun_parallel_comm(t_commrec *cr,t_trxframe *fr,
1024 gmx_bool *bNotLastFrame)
1026 gmx_bool bAlloc;
1027 rvec *xp,*vp;
1029 bAlloc = (fr->natoms == 0);
1031 if (MASTER(cr) && !*bNotLastFrame)
1033 fr->natoms = -1;
1035 xp = fr->x;
1036 vp = fr->v;
1037 gmx_bcast(sizeof(*fr),fr,cr);
1038 fr->x = xp;
1039 fr->v = vp;
1041 *bNotLastFrame = (fr->natoms >= 0);
1043 if (*bNotLastFrame && PARTDECOMP(cr))
1045 /* x and v are the only variable size quantities stored in trr
1046 * that are required for rerun (f is not needed).
1048 if (bAlloc)
1050 snew(fr->x,fr->natoms);
1051 snew(fr->v,fr->natoms);
1053 if (fr->bX)
1055 gmx_bcast(fr->natoms*sizeof(fr->x[0]),fr->x[0],cr);
1057 if (fr->bV)
1059 gmx_bcast(fr->natoms*sizeof(fr->v[0]),fr->v[0],cr);
1064 double do_md(FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
1065 const output_env_t oenv, gmx_bool bVerbose,gmx_bool bCompact,
1066 int nstglobalcomm,
1067 gmx_vsite_t *vsite,gmx_constr_t constr,
1068 int stepout,t_inputrec *ir,
1069 gmx_mtop_t *top_global,
1070 t_fcdata *fcd,
1071 t_state *state_global,
1072 t_mdatoms *mdatoms,
1073 t_nrnb *nrnb,gmx_wallcycle_t wcycle,
1074 gmx_edsam_t ed,t_forcerec *fr,
1075 int repl_ex_nst,int repl_ex_seed,gmx_membed_t *membed,
1076 real cpt_period,real max_hours,
1077 const char *deviceOptions,
1078 unsigned long Flags,
1079 gmx_runtime_t *runtime)
1081 gmx_mdoutf_t *outf;
1082 gmx_large_int_t step,step_rel;
1083 double run_time;
1084 double t,t0,lam0;
1085 gmx_bool bGStatEveryStep,bGStat,bNstEner,bCalcEnerPres;
1086 gmx_bool bNS,bNStList,bSimAnn,bStopCM,bRerunMD,bNotLastFrame=FALSE,
1087 bFirstStep,bStateFromTPX,bInitStep,bLastStep,
1088 bBornRadii,bStartingFromCpt;
1089 gmx_bool bDoDHDL=FALSE;
1090 gmx_bool do_ene,do_log,do_verbose,bRerunWarnNoV=TRUE,
1091 bForceUpdate=FALSE,bCPT;
1092 int mdof_flags;
1093 gmx_bool bMasterState;
1094 int force_flags,cglo_flags;
1095 tensor force_vir,shake_vir,total_vir,tmp_vir,pres;
1096 int i,m;
1097 t_trxstatus *status;
1098 rvec mu_tot;
1099 t_vcm *vcm;
1100 t_state *bufstate=NULL;
1101 matrix *scale_tot,pcoupl_mu,M,ebox;
1102 gmx_nlheur_t nlh;
1103 t_trxframe rerun_fr;
1104 gmx_repl_ex_t repl_ex=NULL;
1105 int nchkpt=1;
1107 gmx_localtop_t *top;
1108 t_mdebin *mdebin=NULL;
1109 t_state *state=NULL;
1110 rvec *f_global=NULL;
1111 int n_xtc=-1;
1112 rvec *x_xtc=NULL;
1113 gmx_enerdata_t *enerd;
1114 rvec *f=NULL;
1115 gmx_global_stat_t gstat;
1116 gmx_update_t upd=NULL;
1117 t_graph *graph=NULL;
1118 globsig_t gs;
1120 gmx_bool bFFscan;
1121 gmx_groups_t *groups;
1122 gmx_ekindata_t *ekind, *ekind_save;
1123 gmx_shellfc_t shellfc;
1124 int count,nconverged=0;
1125 real timestep=0;
1126 double tcount=0;
1127 gmx_bool bIonize=FALSE;
1128 gmx_bool bTCR=FALSE,bConverged=TRUE,bOK,bSumEkinhOld,bExchanged;
1129 gmx_bool bAppend;
1130 gmx_bool bResetCountersHalfMaxH=FALSE;
1131 gmx_bool bVV,bIterations,bFirstIterate,bTemp,bPres,bTrotter;
1132 real temp0,mu_aver=0,dvdl;
1133 int a0,a1,gnx=0,ii;
1134 atom_id *grpindex=NULL;
1135 char *grpname;
1136 t_coupl_rec *tcr=NULL;
1137 rvec *xcopy=NULL,*vcopy=NULL,*cbuf=NULL;
1138 matrix boxcopy={{0}},lastbox;
1139 tensor tmpvir;
1140 real fom,oldfom,veta_save,pcurr,scalevir,tracevir;
1141 real vetanew = 0;
1142 double cycles;
1143 real saved_conserved_quantity = 0;
1144 real last_ekin = 0;
1145 int iter_i;
1146 t_extmass MassQ;
1147 int **trotter_seq;
1148 char sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
1149 int handled_stop_condition=gmx_stop_cond_none; /* compare to get_stop_condition*/
1150 gmx_iterate_t iterate;
1151 #ifdef GMX_FAHCORE
1152 /* Temporary addition for FAHCORE checkpointing */
1153 int chkpt_ret;
1154 #endif
1156 /* Check for special mdrun options */
1157 bRerunMD = (Flags & MD_RERUN);
1158 bIonize = (Flags & MD_IONIZE);
1159 bFFscan = (Flags & MD_FFSCAN);
1160 bAppend = (Flags & MD_APPENDFILES);
1161 if (Flags & MD_RESETCOUNTERSHALFWAY)
1163 if (ir->nsteps > 0)
1165 /* Signal to reset the counters half the simulation steps. */
1166 wcycle_set_reset_counters(wcycle,ir->nsteps/2);
1168 /* Signal to reset the counters halfway the simulation time. */
1169 bResetCountersHalfMaxH = (max_hours > 0);
1172 /* md-vv uses averaged full step velocities for T-control
1173 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
1174 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
1175 bVV = EI_VV(ir->eI);
1176 if (bVV) /* to store the initial velocities while computing virial */
1178 snew(cbuf,top_global->natoms);
1180 /* all the iteratative cases - only if there are constraints */
1181 bIterations = ((IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
1182 bTrotter = (bVV && (IR_NPT_TROTTER(ir) || (IR_NVT_TROTTER(ir))));
1184 if (bRerunMD)
1186 /* Since we don't know if the frames read are related in any way,
1187 * rebuild the neighborlist at every step.
1189 ir->nstlist = 1;
1190 ir->nstcalcenergy = 1;
1191 nstglobalcomm = 1;
1194 check_ir_old_tpx_versions(cr,fplog,ir,top_global);
1196 nstglobalcomm = check_nstglobalcomm(fplog,cr,nstglobalcomm,ir);
1197 bGStatEveryStep = (nstglobalcomm == 1);
1199 if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
1201 fprintf(fplog,
1202 "To reduce the energy communication with nstlist = -1\n"
1203 "the neighbor list validity should not be checked at every step,\n"
1204 "this means that exact integration is not guaranteed.\n"
1205 "The neighbor list validity is checked after:\n"
1206 " <n.list life time> - 2*std.dev.(n.list life time) steps.\n"
1207 "In most cases this will result in exact integration.\n"
1208 "This reduces the energy communication by a factor of 2 to 3.\n"
1209 "If you want less energy communication, set nstlist > 3.\n\n");
1212 if (bRerunMD || bFFscan)
1214 ir->nstxtcout = 0;
1216 groups = &top_global->groups;
1218 /* Initial values */
1219 init_md(fplog,cr,ir,oenv,&t,&t0,&state_global->lambda,&lam0,
1220 nrnb,top_global,&upd,
1221 nfile,fnm,&outf,&mdebin,
1222 force_vir,shake_vir,mu_tot,&bSimAnn,&vcm,state_global,Flags);
1224 clear_mat(total_vir);
1225 clear_mat(pres);
1226 /* Energy terms and groups */
1227 snew(enerd,1);
1228 init_enerdata(top_global->groups.grps[egcENER].nr,ir->n_flambda,enerd);
1229 if (DOMAINDECOMP(cr))
1231 f = NULL;
1233 else
1235 snew(f,top_global->natoms);
1238 /* Kinetic energy data */
1239 snew(ekind,1);
1240 init_ekindata(fplog,top_global,&(ir->opts),ekind);
1241 /* needed for iteration of constraints */
1242 snew(ekind_save,1);
1243 init_ekindata(fplog,top_global,&(ir->opts),ekind_save);
1244 /* Copy the cos acceleration to the groups struct */
1245 ekind->cosacc.cos_accel = ir->cos_accel;
1247 gstat = global_stat_init(ir);
1248 debug_gmx();
1250 /* Check for polarizable models and flexible constraints */
1251 shellfc = init_shell_flexcon(fplog,
1252 top_global,n_flexible_constraints(constr),
1253 (ir->bContinuation ||
1254 (DOMAINDECOMP(cr) && !MASTER(cr))) ?
1255 NULL : state_global->x);
1257 if (DEFORM(*ir))
1259 #ifdef GMX_THREADS
1260 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
1261 #endif
1262 set_deform_reference_box(upd,
1263 deform_init_init_step_tpx,
1264 deform_init_box_tpx);
1265 #ifdef GMX_THREADS
1266 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
1267 #endif
1271 double io = compute_io(ir,top_global->natoms,groups,mdebin->ebin->nener,1);
1272 if ((io > 2000) && MASTER(cr))
1273 fprintf(stderr,
1274 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
1275 io);
1278 if (DOMAINDECOMP(cr)) {
1279 top = dd_init_local_top(top_global);
1281 snew(state,1);
1282 dd_init_local_state(cr->dd,state_global,state);
1284 if (DDMASTER(cr->dd) && ir->nstfout) {
1285 snew(f_global,state_global->natoms);
1287 } else {
1288 if (PAR(cr)) {
1289 /* Initialize the particle decomposition and split the topology */
1290 top = split_system(fplog,top_global,ir,cr);
1292 pd_cg_range(cr,&fr->cg0,&fr->hcg);
1293 pd_at_range(cr,&a0,&a1);
1294 } else {
1295 top = gmx_mtop_generate_local_top(top_global,ir);
1297 a0 = 0;
1298 a1 = top_global->natoms;
1301 state = partdec_init_local_state(cr,state_global);
1302 f_global = f;
1304 atoms2md(top_global,ir,0,NULL,a0,a1-a0,mdatoms);
1306 if (vsite) {
1307 set_vsite_top(vsite,top,mdatoms,cr);
1310 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols) {
1311 graph = mk_graph(fplog,&(top->idef),0,top_global->natoms,FALSE,FALSE);
1314 if (shellfc) {
1315 make_local_shells(cr,mdatoms,shellfc);
1318 if (ir->pull && PAR(cr)) {
1319 dd_make_local_pull_groups(NULL,ir->pull,mdatoms);
1323 if (DOMAINDECOMP(cr))
1325 /* Distribute the charge groups over the nodes from the master node */
1326 dd_partition_system(fplog,ir->init_step,cr,TRUE,1,
1327 state_global,top_global,ir,
1328 state,&f,mdatoms,top,fr,
1329 vsite,shellfc,constr,
1330 nrnb,wcycle,FALSE);
1333 update_mdatoms(mdatoms,state->lambda);
1335 if (MASTER(cr))
1337 if (opt2bSet("-cpi",nfile,fnm))
1339 /* Update mdebin with energy history if appending to output files */
1340 if ( Flags & MD_APPENDFILES )
1342 restore_energyhistory_from_state(mdebin,&state_global->enerhist);
1344 else
1346 /* We might have read an energy history from checkpoint,
1347 * free the allocated memory and reset the counts.
1349 done_energyhistory(&state_global->enerhist);
1350 init_energyhistory(&state_global->enerhist);
1353 /* Set the initial energy history in state by updating once */
1354 update_energyhistory(&state_global->enerhist,mdebin);
1357 if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG)) {
1358 /* Set the random state if we read a checkpoint file */
1359 set_stochd_state(upd,state);
1362 /* Initialize constraints */
1363 if (constr) {
1364 if (!DOMAINDECOMP(cr))
1365 set_constraints(constr,top,ir,mdatoms,cr);
1368 /* Check whether we have to GCT stuff */
1369 bTCR = ftp2bSet(efGCT,nfile,fnm);
1370 if (bTCR) {
1371 if (MASTER(cr)) {
1372 fprintf(stderr,"Will do General Coupling Theory!\n");
1374 gnx = top_global->mols.nr;
1375 snew(grpindex,gnx);
1376 for(i=0; (i<gnx); i++) {
1377 grpindex[i] = i;
1381 if (repl_ex_nst > 0 && MASTER(cr))
1382 repl_ex = init_replica_exchange(fplog,cr->ms,state_global,ir,
1383 repl_ex_nst,repl_ex_seed);
1385 if (!ir->bContinuation && !bRerunMD)
1387 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
1389 /* Set the velocities of frozen particles to zero */
1390 for(i=mdatoms->start; i<mdatoms->start+mdatoms->homenr; i++)
1392 for(m=0; m<DIM; m++)
1394 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
1396 state->v[i][m] = 0;
1402 if (constr)
1404 /* Constrain the initial coordinates and velocities */
1405 do_constrain_first(fplog,constr,ir,mdatoms,state,f,
1406 graph,cr,nrnb,fr,top,shake_vir);
1408 if (vsite)
1410 /* Construct the virtual sites for the initial configuration */
1411 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,NULL,
1412 top->idef.iparams,top->idef.il,
1413 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1417 debug_gmx();
1419 /* I'm assuming we need global communication the first time! MRS */
1420 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
1421 | (bVV ? CGLO_PRESSURE:0)
1422 | (bVV ? CGLO_CONSTRAINT:0)
1423 | (bRerunMD ? CGLO_RERUNMD:0)
1424 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN:0));
1426 bSumEkinhOld = FALSE;
1427 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1428 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1429 constr,NULL,FALSE,state->box,
1430 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,cglo_flags);
1431 if (ir->eI == eiVVAK) {
1432 /* a second call to get the half step temperature initialized as well */
1433 /* we do the same call as above, but turn the pressure off -- internally to
1434 compute_globals, this is recognized as a velocity verlet half-step
1435 kinetic energy calculation. This minimized excess variables, but
1436 perhaps loses some logic?*/
1438 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1439 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1440 constr,NULL,FALSE,state->box,
1441 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1442 cglo_flags &~ CGLO_PRESSURE);
1445 /* Calculate the initial half step temperature, and save the ekinh_old */
1446 if (!(Flags & MD_STARTFROMCPT))
1448 for(i=0; (i<ir->opts.ngtc); i++)
1450 copy_mat(ekind->tcstat[i].ekinh,ekind->tcstat[i].ekinh_old);
1453 if (ir->eI != eiVV)
1455 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
1456 and there is no previous step */
1458 temp0 = enerd->term[F_TEMP];
1460 /* if using an iterative algorithm, we need to create a working directory for the state. */
1461 if (bIterations)
1463 bufstate = init_bufstate(state);
1465 if (bFFscan)
1467 snew(xcopy,state->natoms);
1468 snew(vcopy,state->natoms);
1469 copy_rvecn(state->x,xcopy,0,state->natoms);
1470 copy_rvecn(state->v,vcopy,0,state->natoms);
1471 copy_mat(state->box,boxcopy);
1474 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
1475 temperature control */
1476 trotter_seq = init_npt_vars(ir,state,&MassQ,bTrotter);
1478 if (MASTER(cr))
1480 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
1482 fprintf(fplog,
1483 "RMS relative constraint deviation after constraining: %.2e\n",
1484 constr_rmsd(constr,FALSE));
1486 fprintf(fplog,"Initial temperature: %g K\n",enerd->term[F_TEMP]);
1487 if (bRerunMD)
1489 fprintf(stderr,"starting md rerun '%s', reading coordinates from"
1490 " input trajectory '%s'\n\n",
1491 *(top_global->name),opt2fn("-rerun",nfile,fnm));
1492 if (bVerbose)
1494 fprintf(stderr,"Calculated time to finish depends on nsteps from "
1495 "run input file,\nwhich may not correspond to the time "
1496 "needed to process input trajectory.\n\n");
1499 else
1501 char tbuf[20];
1502 fprintf(stderr,"starting mdrun '%s'\n",
1503 *(top_global->name));
1504 if (ir->nsteps >= 0)
1506 sprintf(tbuf,"%8.1f",(ir->init_step+ir->nsteps)*ir->delta_t);
1508 else
1510 sprintf(tbuf,"%s","infinite");
1512 if (ir->init_step > 0)
1514 fprintf(stderr,"%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
1515 gmx_step_str(ir->init_step+ir->nsteps,sbuf),tbuf,
1516 gmx_step_str(ir->init_step,sbuf2),
1517 ir->init_step*ir->delta_t);
1519 else
1521 fprintf(stderr,"%s steps, %s ps.\n",
1522 gmx_step_str(ir->nsteps,sbuf),tbuf);
1525 fprintf(fplog,"\n");
1528 /* Set and write start time */
1529 runtime_start(runtime);
1530 print_date_and_time(fplog,cr->nodeid,"Started mdrun",runtime);
1531 wallcycle_start(wcycle,ewcRUN);
1532 if (fplog)
1533 fprintf(fplog,"\n");
1535 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
1536 #ifdef GMX_FAHCORE
1537 chkpt_ret=fcCheckPointParallel( cr->nodeid,
1538 NULL,0);
1539 if ( chkpt_ret == 0 )
1540 gmx_fatal( 3,__FILE__,__LINE__, "Checkpoint error on step %d\n", 0 );
1541 #endif
1543 debug_gmx();
1544 /***********************************************************
1546 * Loop over MD steps
1548 ************************************************************/
1550 /* if rerunMD then read coordinates and velocities from input trajectory */
1551 if (bRerunMD)
1553 if (getenv("GMX_FORCE_UPDATE"))
1555 bForceUpdate = TRUE;
1558 rerun_fr.natoms = 0;
1559 if (MASTER(cr))
1561 bNotLastFrame = read_first_frame(oenv,&status,
1562 opt2fn("-rerun",nfile,fnm),
1563 &rerun_fr,TRX_NEED_X | TRX_READ_V);
1564 if (rerun_fr.natoms != top_global->natoms)
1566 gmx_fatal(FARGS,
1567 "Number of atoms in trajectory (%d) does not match the "
1568 "run input file (%d)\n",
1569 rerun_fr.natoms,top_global->natoms);
1571 if (ir->ePBC != epbcNONE)
1573 if (!rerun_fr.bBox)
1575 gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f does not contain a box, while pbc is used",rerun_fr.step,rerun_fr.time);
1577 if (max_cutoff2(ir->ePBC,rerun_fr.box) < sqr(fr->rlistlong))
1579 gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f has too small box dimensions",rerun_fr.step,rerun_fr.time);
1584 if (PAR(cr))
1586 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
1589 if (ir->ePBC != epbcNONE)
1591 /* Set the shift vectors.
1592 * Necessary here when have a static box different from the tpr box.
1594 calc_shifts(rerun_fr.box,fr->shift_vec);
1598 /* loop over MD steps or if rerunMD to end of input trajectory */
1599 bFirstStep = TRUE;
1600 /* Skip the first Nose-Hoover integration when we get the state from tpx */
1601 bStateFromTPX = !opt2bSet("-cpi",nfile,fnm);
1602 bInitStep = bFirstStep && (bStateFromTPX || bVV);
1603 bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
1604 bLastStep = FALSE;
1605 bSumEkinhOld = FALSE;
1606 bExchanged = FALSE;
1608 init_global_signals(&gs,cr,ir,repl_ex_nst);
1610 step = ir->init_step;
1611 step_rel = 0;
1613 if (ir->nstlist == -1)
1615 init_nlistheuristics(&nlh,bGStatEveryStep,step);
1618 bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps));
1619 while (!bLastStep || (bRerunMD && bNotLastFrame)) {
1621 wallcycle_start(wcycle,ewcSTEP);
1623 GMX_MPE_LOG(ev_timestep1);
1625 if (bRerunMD) {
1626 if (rerun_fr.bStep) {
1627 step = rerun_fr.step;
1628 step_rel = step - ir->init_step;
1630 if (rerun_fr.bTime) {
1631 t = rerun_fr.time;
1633 else
1635 t = step;
1638 else
1640 bLastStep = (step_rel == ir->nsteps);
1641 t = t0 + step*ir->delta_t;
1644 if (ir->efep != efepNO)
1646 if (bRerunMD && rerun_fr.bLambda && (ir->delta_lambda!=0))
1648 state_global->lambda = rerun_fr.lambda;
1650 else
1652 state_global->lambda = lam0 + step*ir->delta_lambda;
1654 state->lambda = state_global->lambda;
1655 bDoDHDL = do_per_step(step,ir->nstdhdl);
1658 if (bSimAnn)
1660 update_annealing_target_temp(&(ir->opts),t);
1663 if (bRerunMD)
1665 if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
1667 for(i=0; i<state_global->natoms; i++)
1669 copy_rvec(rerun_fr.x[i],state_global->x[i]);
1671 if (rerun_fr.bV)
1673 for(i=0; i<state_global->natoms; i++)
1675 copy_rvec(rerun_fr.v[i],state_global->v[i]);
1678 else
1680 for(i=0; i<state_global->natoms; i++)
1682 clear_rvec(state_global->v[i]);
1684 if (bRerunWarnNoV)
1686 fprintf(stderr,"\nWARNING: Some frames do not contain velocities.\n"
1687 " Ekin, temperature and pressure are incorrect,\n"
1688 " the virial will be incorrect when constraints are present.\n"
1689 "\n");
1690 bRerunWarnNoV = FALSE;
1694 copy_mat(rerun_fr.box,state_global->box);
1695 copy_mat(state_global->box,state->box);
1697 if (vsite && (Flags & MD_RERUN_VSITE))
1699 if (DOMAINDECOMP(cr))
1701 gmx_fatal(FARGS,"Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
1703 if (graph)
1705 /* Following is necessary because the graph may get out of sync
1706 * with the coordinates if we only have every N'th coordinate set
1708 mk_mshift(fplog,graph,fr->ePBC,state->box,state->x);
1709 shift_self(graph,state->box,state->x);
1711 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
1712 top->idef.iparams,top->idef.il,
1713 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1714 if (graph)
1716 unshift_self(graph,state->box,state->x);
1721 /* Stop Center of Mass motion */
1722 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step,ir->nstcomm));
1724 /* Copy back starting coordinates in case we're doing a forcefield scan */
1725 if (bFFscan)
1727 for(ii=0; (ii<state->natoms); ii++)
1729 copy_rvec(xcopy[ii],state->x[ii]);
1730 copy_rvec(vcopy[ii],state->v[ii]);
1732 copy_mat(boxcopy,state->box);
1735 if (bRerunMD)
1737 /* for rerun MD always do Neighbour Searching */
1738 bNS = (bFirstStep || ir->nstlist != 0);
1739 bNStList = bNS;
1741 else
1743 /* Determine whether or not to do Neighbour Searching and LR */
1744 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
1746 bNS = (bFirstStep || bExchanged || bNStList ||
1747 (ir->nstlist == -1 && nlh.nabnsb > 0));
1749 if (bNS && ir->nstlist == -1)
1751 set_nlistheuristics(&nlh,bFirstStep || bExchanged,step);
1755 /* < 0 means stop at next step, > 0 means stop at next NS step */
1756 if ( (gs.set[eglsSTOPCOND] < 0 ) ||
1757 ( (gs.set[eglsSTOPCOND] > 0 ) && ( bNS || ir->nstlist==0)) )
1759 bLastStep = TRUE;
1762 /* Determine whether or not to update the Born radii if doing GB */
1763 bBornRadii=bFirstStep;
1764 if (ir->implicit_solvent && (step % ir->nstgbradii==0))
1766 bBornRadii=TRUE;
1769 do_log = do_per_step(step,ir->nstlog) || bFirstStep || bLastStep;
1770 do_verbose = bVerbose &&
1771 (step % stepout == 0 || bFirstStep || bLastStep);
1773 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
1775 if (bRerunMD)
1777 bMasterState = TRUE;
1779 else
1781 bMasterState = FALSE;
1782 /* Correct the new box if it is too skewed */
1783 if (DYNAMIC_BOX(*ir))
1785 if (correct_box(fplog,step,state->box,graph))
1787 bMasterState = TRUE;
1790 if (DOMAINDECOMP(cr) && bMasterState)
1792 dd_collect_state(cr->dd,state,state_global);
1796 if (DOMAINDECOMP(cr))
1798 /* Repartition the domain decomposition */
1799 wallcycle_start(wcycle,ewcDOMDEC);
1800 dd_partition_system(fplog,step,cr,
1801 bMasterState,nstglobalcomm,
1802 state_global,top_global,ir,
1803 state,&f,mdatoms,top,fr,
1804 vsite,shellfc,constr,
1805 nrnb,wcycle,do_verbose);
1806 wallcycle_stop(wcycle,ewcDOMDEC);
1807 /* If using an iterative integrator, reallocate space to match the decomposition */
1811 if (MASTER(cr) && do_log && !bFFscan)
1813 print_ebin_header(fplog,step,t,state->lambda);
1816 if (ir->efep != efepNO)
1818 update_mdatoms(mdatoms,state->lambda);
1821 if (bRerunMD && rerun_fr.bV)
1824 /* We need the kinetic energy at minus the half step for determining
1825 * the full step kinetic energy and possibly for T-coupling.*/
1826 /* This may not be quite working correctly yet . . . . */
1827 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1828 wcycle,enerd,NULL,NULL,NULL,NULL,mu_tot,
1829 constr,NULL,FALSE,state->box,
1830 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1831 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1833 clear_mat(force_vir);
1835 /* Ionize the atoms if necessary */
1836 if (bIonize)
1838 ionize(fplog,oenv,mdatoms,top_global,t,ir,state->x,state->v,
1839 mdatoms->start,mdatoms->start+mdatoms->homenr,state->box,cr);
1842 /* Update force field in ffscan program */
1843 if (bFFscan)
1845 if (update_forcefield(fplog,
1846 nfile,fnm,fr,
1847 mdatoms->nr,state->x,state->box)) {
1848 if (gmx_parallel_env_initialized())
1850 gmx_finalize();
1852 exit(0);
1856 GMX_MPE_LOG(ev_timestep2);
1858 /* We write a checkpoint at this MD step when:
1859 * either at an NS step when we signalled through gs,
1860 * or at the last step (but not when we do not want confout),
1861 * but never at the first step or with rerun.
1863 bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
1864 (bLastStep && (Flags & MD_CONFOUT))) &&
1865 step > ir->init_step && !bRerunMD);
1866 if (bCPT)
1868 gs.set[eglsCHKPT] = 0;
1871 /* Determine the energy and pressure:
1872 * at nstcalcenergy steps and at energy output steps (set below).
1874 bNstEner = do_per_step(step,ir->nstcalcenergy);
1875 bCalcEnerPres =
1876 (bNstEner ||
1877 (ir->epc != epcNO && do_per_step(step,ir->nstpcouple)));
1879 /* Do we need global communication ? */
1880 bGStat = (bCalcEnerPres || bStopCM ||
1881 do_per_step(step,nstglobalcomm) ||
1882 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
1884 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
1886 if (do_ene || do_log)
1888 bCalcEnerPres = TRUE;
1889 bGStat = TRUE;
1892 /* these CGLO_ options remain the same throughout the iteration */
1893 cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
1894 (bStopCM ? CGLO_STOPCM : 0) |
1895 (bGStat ? CGLO_GSTAT : 0)
1898 force_flags = (GMX_FORCE_STATECHANGED |
1899 ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1900 GMX_FORCE_ALLFORCES |
1901 (bNStList ? GMX_FORCE_DOLR : 0) |
1902 GMX_FORCE_SEPLRF |
1903 (bCalcEnerPres ? GMX_FORCE_VIRIAL : 0) |
1904 (bDoDHDL ? GMX_FORCE_DHDL : 0)
1907 if (shellfc)
1909 /* Now is the time to relax the shells */
1910 count=relax_shell_flexcon(fplog,cr,bVerbose,bFFscan ? step+1 : step,
1911 ir,bNS,force_flags,
1912 bStopCM,top,top_global,
1913 constr,enerd,fcd,
1914 state,f,force_vir,mdatoms,
1915 nrnb,wcycle,graph,groups,
1916 shellfc,fr,bBornRadii,t,mu_tot,
1917 state->natoms,&bConverged,vsite,
1918 outf->fp_field);
1919 tcount+=count;
1921 if (bConverged)
1923 nconverged++;
1926 else
1928 /* The coordinates (x) are shifted (to get whole molecules)
1929 * in do_force.
1930 * This is parallellized as well, and does communication too.
1931 * Check comments in sim_util.c
1934 do_force(fplog,cr,ir,step,nrnb,wcycle,top,top_global,groups,
1935 state->box,state->x,&state->hist,
1936 f,force_vir,mdatoms,enerd,fcd,
1937 state->lambda,graph,
1938 fr,vsite,mu_tot,t,outf->fp_field,ed,bBornRadii,
1939 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1942 GMX_BARRIER(cr->mpi_comm_mygroup);
1944 if (bTCR)
1946 mu_aver = calc_mu_aver(cr,state->x,mdatoms->chargeA,
1947 mu_tot,&top_global->mols,mdatoms,gnx,grpindex);
1950 if (bTCR && bFirstStep)
1952 tcr=init_coupling(fplog,nfile,fnm,cr,fr,mdatoms,&(top->idef));
1953 fprintf(fplog,"Done init_coupling\n");
1954 fflush(fplog);
1957 if (bVV && !bStartingFromCpt && !bRerunMD)
1958 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1960 if (ir->eI==eiVV && bInitStep)
1962 /* if using velocity verlet with full time step Ekin,
1963 * take the first half step only to compute the
1964 * virial for the first step. From there,
1965 * revert back to the initial coordinates
1966 * so that the input is actually the initial step.
1968 copy_rvecn(state->v,cbuf,0,state->natoms); /* should make this better for parallelizing? */
1969 } else {
1970 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1971 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ1);
1974 update_coords(fplog,step,ir,mdatoms,state,
1975 f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1976 ekind,M,wcycle,upd,bInitStep,etrtVELOCITY1,
1977 cr,nrnb,constr,&top->idef);
1979 if (bIterations)
1981 gmx_iterate_init(&iterate,bIterations && !bInitStep);
1983 /* for iterations, we save these vectors, as we will be self-consistently iterating
1984 the calculations */
1986 /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1988 /* save the state */
1989 if (bIterations && iterate.bIterate) {
1990 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1993 bFirstIterate = TRUE;
1994 while (bFirstIterate || (bIterations && iterate.bIterate))
1996 if (bIterations && iterate.bIterate)
1998 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
1999 if (bFirstIterate && bTrotter)
2001 /* The first time through, we need a decent first estimate
2002 of veta(t+dt) to compute the constraints. Do
2003 this by computing the box volume part of the
2004 trotter integration at this time. Nothing else
2005 should be changed by this routine here. If
2006 !(first time), we start with the previous value
2007 of veta. */
2009 veta_save = state->veta;
2010 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ0);
2011 vetanew = state->veta;
2012 state->veta = veta_save;
2016 bOK = TRUE;
2017 if ( !bRerunMD || rerun_fr.bV || bForceUpdate) { /* Why is rerun_fr.bV here? Unclear. */
2018 dvdl = 0;
2020 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2021 &top->idef,shake_vir,NULL,
2022 cr,nrnb,wcycle,upd,constr,
2023 bInitStep,TRUE,bCalcEnerPres,vetanew);
2025 if (!bOK && !bFFscan)
2027 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2031 else if (graph)
2032 { /* Need to unshift here if a do_force has been
2033 called in the previous step */
2034 unshift_self(graph,state->box,state->x);
2038 /* if VV, compute the pressure and constraints */
2039 /* For VV2, we strictly only need this if using pressure
2040 * control, but we really would like to have accurate pressures
2041 * printed out.
2042 * Think about ways around this in the future?
2043 * For now, keep this choice in comments.
2045 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
2046 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
2047 bPres = TRUE;
2048 bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK));
2049 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2050 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2051 constr,NULL,FALSE,state->box,
2052 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2053 cglo_flags
2054 | CGLO_ENERGY
2055 | (bTemp ? CGLO_TEMPERATURE:0)
2056 | (bPres ? CGLO_PRESSURE : 0)
2057 | (bPres ? CGLO_CONSTRAINT : 0)
2058 | ((bIterations && iterate.bIterate) ? CGLO_ITERATE : 0)
2059 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
2060 | CGLO_SCALEEKIN
2062 /* explanation of above:
2063 a) We compute Ekin at the full time step
2064 if 1) we are using the AveVel Ekin, and it's not the
2065 initial step, or 2) if we are using AveEkin, but need the full
2066 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
2067 b) If we are using EkinAveEkin for the kinetic energy for the temperture control, we still feed in
2068 EkinAveVel because it's needed for the pressure */
2070 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
2071 if (!bInitStep)
2073 if (bTrotter)
2075 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ2);
2077 else
2079 update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
2083 if (bIterations &&
2084 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
2085 state->veta,&vetanew))
2087 break;
2089 bFirstIterate = FALSE;
2092 if (bTrotter && !bInitStep) {
2093 copy_mat(shake_vir,state->svir_prev);
2094 copy_mat(force_vir,state->fvir_prev);
2095 if (IR_NVT_TROTTER(ir) && ir->eI==eiVV) {
2096 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
2097 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,NULL,(ir->eI==eiVV),FALSE,FALSE);
2098 enerd->term[F_EKIN] = trace(ekind->ekin);
2101 /* if it's the initial step, we performed this first step just to get the constraint virial */
2102 if (bInitStep && ir->eI==eiVV) {
2103 copy_rvecn(cbuf,state->v,0,state->natoms);
2106 if (fr->bSepDVDL && fplog && do_log)
2108 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2110 enerd->term[F_DHDL_CON] += dvdl;
2112 GMX_MPE_LOG(ev_timestep1);
2115 /* MRS -- now done iterating -- compute the conserved quantity */
2116 if (bVV) {
2117 saved_conserved_quantity = compute_conserved_from_auxiliary(ir,state,&MassQ);
2118 if (ir->eI==eiVV)
2120 last_ekin = enerd->term[F_EKIN]; /* does this get preserved through checkpointing? */
2122 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
2124 saved_conserved_quantity -= enerd->term[F_DISPCORR];
2128 /* ######## END FIRST UPDATE STEP ############## */
2129 /* ######## If doing VV, we now have v(dt) ###### */
2131 /* ################## START TRAJECTORY OUTPUT ################# */
2133 /* Now we have the energies and forces corresponding to the
2134 * coordinates at time t. We must output all of this before
2135 * the update.
2136 * for RerunMD t is read from input trajectory
2138 GMX_MPE_LOG(ev_output_start);
2140 mdof_flags = 0;
2141 if (do_per_step(step,ir->nstxout)) { mdof_flags |= MDOF_X; }
2142 if (do_per_step(step,ir->nstvout)) { mdof_flags |= MDOF_V; }
2143 if (do_per_step(step,ir->nstfout)) { mdof_flags |= MDOF_F; }
2144 if (do_per_step(step,ir->nstxtcout)) { mdof_flags |= MDOF_XTC; }
2145 if (bCPT) { mdof_flags |= MDOF_CPT; };
2147 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
2148 if (bLastStep)
2150 /* Enforce writing positions and velocities at end of run */
2151 mdof_flags |= (MDOF_X | MDOF_V);
2153 #endif
2154 #ifdef GMX_FAHCORE
2155 if (MASTER(cr))
2156 fcReportProgress( ir->nsteps, step );
2158 /* sync bCPT and fc record-keeping */
2159 if (bCPT && MASTER(cr))
2160 fcRequestCheckPoint();
2161 #endif
2163 if (mdof_flags != 0)
2165 wallcycle_start(wcycle,ewcTRAJ);
2166 if (bCPT)
2168 if (state->flags & (1<<estLD_RNG))
2170 get_stochd_state(upd,state);
2172 if (MASTER(cr))
2174 if (bSumEkinhOld)
2176 state_global->ekinstate.bUpToDate = FALSE;
2178 else
2180 update_ekinstate(&state_global->ekinstate,ekind);
2181 state_global->ekinstate.bUpToDate = TRUE;
2183 update_energyhistory(&state_global->enerhist,mdebin);
2186 write_traj(fplog,cr,outf,mdof_flags,top_global,
2187 step,t,state,state_global,f,f_global,&n_xtc,&x_xtc);
2188 if (bCPT)
2190 nchkpt++;
2191 bCPT = FALSE;
2193 debug_gmx();
2194 if (bLastStep && step_rel == ir->nsteps &&
2195 (Flags & MD_CONFOUT) && MASTER(cr) &&
2196 !bRerunMD && !bFFscan)
2198 /* x and v have been collected in write_traj,
2199 * because a checkpoint file will always be written
2200 * at the last step.
2202 fprintf(stderr,"\nWriting final coordinates.\n");
2203 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols &&
2204 DOMAINDECOMP(cr))
2206 /* Make molecules whole only for confout writing */
2207 do_pbc_mtop(fplog,ir->ePBC,state->box,top_global,state_global->x);
2209 write_sto_conf_mtop(ftp2fn(efSTO,nfile,fnm),
2210 *top_global->name,top_global,
2211 state_global->x,state_global->v,
2212 ir->ePBC,state->box);
2213 debug_gmx();
2215 wallcycle_stop(wcycle,ewcTRAJ);
2217 GMX_MPE_LOG(ev_output_finish);
2219 /* kludge -- virial is lost with restart for NPT control. Must restart */
2220 if (bStartingFromCpt && bVV)
2222 copy_mat(state->svir_prev,shake_vir);
2223 copy_mat(state->fvir_prev,force_vir);
2225 /* ################## END TRAJECTORY OUTPUT ################ */
2227 /* Determine the pressure:
2228 * always when we want exact averages in the energy file,
2229 * at ns steps when we have pressure coupling,
2230 * otherwise only at energy output steps (set below).
2233 bNstEner = (bGStatEveryStep || do_per_step(step,ir->nstcalcenergy));
2234 bCalcEnerPres = bNstEner;
2236 /* Do we need global communication ? */
2237 bGStat = (bGStatEveryStep || bStopCM || bNS ||
2238 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
2240 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
2242 if (do_ene || do_log)
2244 bCalcEnerPres = TRUE;
2245 bGStat = TRUE;
2248 /* Determine the wallclock run time up till now */
2249 run_time = gmx_gettime() - (double)runtime->real;
2251 /* Check whether everything is still allright */
2252 if (((int)gmx_get_stop_condition() > handled_stop_condition)
2253 #ifdef GMX_THREADS
2254 && MASTER(cr)
2255 #endif
2258 /* this is just make gs.sig compatible with the hack
2259 of sending signals around by MPI_Reduce with together with
2260 other floats */
2261 if ( gmx_get_stop_condition() == gmx_stop_cond_next_ns )
2262 gs.sig[eglsSTOPCOND]=1;
2263 if ( gmx_get_stop_condition() == gmx_stop_cond_next )
2264 gs.sig[eglsSTOPCOND]=-1;
2265 /* < 0 means stop at next step, > 0 means stop at next NS step */
2266 if (fplog)
2268 fprintf(fplog,
2269 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2270 gmx_get_signal_name(),
2271 gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
2272 fflush(fplog);
2274 fprintf(stderr,
2275 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2276 gmx_get_signal_name(),
2277 gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
2278 fflush(stderr);
2279 handled_stop_condition=(int)gmx_get_stop_condition();
2281 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
2282 (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
2283 gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
2285 /* Signal to terminate the run */
2286 gs.sig[eglsSTOPCOND] = 1;
2287 if (fplog)
2289 fprintf(fplog,"\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2291 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2294 if (bResetCountersHalfMaxH && MASTER(cr) &&
2295 run_time > max_hours*60.0*60.0*0.495)
2297 gs.sig[eglsRESETCOUNTERS] = 1;
2300 if (ir->nstlist == -1 && !bRerunMD)
2302 /* When bGStatEveryStep=FALSE, global_stat is only called
2303 * when we check the atom displacements, not at NS steps.
2304 * This means that also the bonded interaction count check is not
2305 * performed immediately after NS. Therefore a few MD steps could
2306 * be performed with missing interactions.
2307 * But wrong energies are never written to file,
2308 * since energies are only written after global_stat
2309 * has been called.
2311 if (step >= nlh.step_nscheck)
2313 nlh.nabnsb = natoms_beyond_ns_buffer(ir,fr,&top->cgs,
2314 nlh.scale_tot,state->x);
2316 else
2318 /* This is not necessarily true,
2319 * but step_nscheck is determined quite conservatively.
2321 nlh.nabnsb = 0;
2325 /* In parallel we only have to check for checkpointing in steps
2326 * where we do global communication,
2327 * otherwise the other nodes don't know.
2329 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
2330 cpt_period >= 0 &&
2331 (cpt_period == 0 ||
2332 run_time >= nchkpt*cpt_period*60.0)) &&
2333 gs.set[eglsCHKPT] == 0)
2335 gs.sig[eglsCHKPT] = 1;
2338 if (bIterations)
2340 gmx_iterate_init(&iterate,bIterations);
2343 /* for iterations, we save these vectors, as we will be redoing the calculations */
2344 if (bIterations && iterate.bIterate)
2346 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
2348 bFirstIterate = TRUE;
2349 while (bFirstIterate || (bIterations && iterate.bIterate))
2351 /* We now restore these vectors to redo the calculation with improved extended variables */
2352 if (bIterations)
2354 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
2357 /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
2358 so scroll down for that logic */
2360 /* ######### START SECOND UPDATE STEP ################# */
2361 GMX_MPE_LOG(ev_update_start);
2362 /* Box is changed in update() when we do pressure coupling,
2363 * but we should still use the old box for energy corrections and when
2364 * writing it to the energy file, so it matches the trajectory files for
2365 * the same timestep above. Make a copy in a separate array.
2367 copy_mat(state->box,lastbox);
2369 bOK = TRUE;
2370 if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
2372 wallcycle_start(wcycle,ewcUPDATE);
2373 dvdl = 0;
2374 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
2375 if (bTrotter)
2377 if (bIterations && iterate.bIterate)
2379 if (bFirstIterate)
2381 scalevir = 1;
2383 else
2385 /* we use a new value of scalevir to converge the iterations faster */
2386 scalevir = tracevir/trace(shake_vir);
2388 msmul(shake_vir,scalevir,shake_vir);
2389 m_add(force_vir,shake_vir,total_vir);
2390 clear_mat(shake_vir);
2392 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ3);
2393 /* We can only do Berendsen coupling after we have summed
2394 * the kinetic energy or virial. Since the happens
2395 * in global_state after update, we should only do it at
2396 * step % nstlist = 1 with bGStatEveryStep=FALSE.
2399 else
2401 update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
2402 update_pcouple(fplog,step,ir,state,pcoupl_mu,M,wcycle,
2403 upd,bInitStep);
2406 if (bVV)
2408 /* velocity half-step update */
2409 update_coords(fplog,step,ir,mdatoms,state,f,
2410 fr->bTwinRange && bNStList,fr->f_twin,fcd,
2411 ekind,M,wcycle,upd,FALSE,etrtVELOCITY2,
2412 cr,nrnb,constr,&top->idef);
2415 /* Above, initialize just copies ekinh into ekin,
2416 * it doesn't copy position (for VV),
2417 * and entire integrator for MD.
2420 if (ir->eI==eiVVAK)
2422 copy_rvecn(state->x,cbuf,0,state->natoms);
2425 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2426 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2427 wallcycle_stop(wcycle,ewcUPDATE);
2429 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2430 &top->idef,shake_vir,force_vir,
2431 cr,nrnb,wcycle,upd,constr,
2432 bInitStep,FALSE,bCalcEnerPres,state->veta);
2434 if (ir->eI==eiVVAK)
2436 /* erase F_EKIN and F_TEMP here? */
2437 /* just compute the kinetic energy at the half step to perform a trotter step */
2438 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2439 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2440 constr,NULL,FALSE,lastbox,
2441 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2442 cglo_flags | CGLO_TEMPERATURE
2444 wallcycle_start(wcycle,ewcUPDATE);
2445 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ4);
2446 /* now we know the scaling, we can compute the positions again again */
2447 copy_rvecn(cbuf,state->x,0,state->natoms);
2449 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2450 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2451 wallcycle_stop(wcycle,ewcUPDATE);
2453 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
2454 /* are the small terms in the shake_vir here due
2455 * to numerical errors, or are they important
2456 * physically? I'm thinking they are just errors, but not completely sure.
2457 * For now, will call without actually constraining, constr=NULL*/
2458 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2459 &top->idef,tmp_vir,force_vir,
2460 cr,nrnb,wcycle,upd,NULL,
2461 bInitStep,FALSE,bCalcEnerPres,
2462 state->veta);
2464 if (!bOK && !bFFscan)
2466 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2469 if (fr->bSepDVDL && fplog && do_log)
2471 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2473 enerd->term[F_DHDL_CON] += dvdl;
2475 else if (graph)
2477 /* Need to unshift here */
2478 unshift_self(graph,state->box,state->x);
2481 GMX_BARRIER(cr->mpi_comm_mygroup);
2482 GMX_MPE_LOG(ev_update_finish);
2484 if (vsite != NULL)
2486 wallcycle_start(wcycle,ewcVSITECONSTR);
2487 if (graph != NULL)
2489 shift_self(graph,state->box,state->x);
2491 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
2492 top->idef.iparams,top->idef.il,
2493 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
2495 if (graph != NULL)
2497 unshift_self(graph,state->box,state->x);
2499 wallcycle_stop(wcycle,ewcVSITECONSTR);
2502 /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
2503 if (ir->nstlist == -1 && bFirstIterate)
2505 gs.sig[eglsNABNSB] = nlh.nabnsb;
2507 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2508 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2509 constr,
2510 bFirstIterate ? &gs : NULL,(step % gs.nstms == 0),
2511 lastbox,
2512 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2513 cglo_flags
2514 | (!EI_VV(ir->eI) ? CGLO_ENERGY : 0)
2515 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
2516 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
2517 | (bIterations && iterate.bIterate ? CGLO_ITERATE : 0)
2518 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
2519 | CGLO_CONSTRAINT
2521 if (ir->nstlist == -1 && bFirstIterate)
2523 nlh.nabnsb = gs.set[eglsNABNSB];
2524 gs.set[eglsNABNSB] = 0;
2526 /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
2527 /* ############# END CALC EKIN AND PRESSURE ################# */
2529 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
2530 the virial that should probably be addressed eventually. state->veta has better properies,
2531 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
2532 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
2534 if (bIterations &&
2535 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
2536 trace(shake_vir),&tracevir))
2538 break;
2540 bFirstIterate = FALSE;
2543 update_box(fplog,step,ir,mdatoms,state,graph,f,
2544 ir->nstlist==-1 ? &nlh.scale_tot : NULL,pcoupl_mu,nrnb,wcycle,upd,bInitStep,FALSE);
2546 /* ################# END UPDATE STEP 2 ################# */
2547 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
2549 /* The coordinates (x) were unshifted in update */
2550 if (bFFscan && (shellfc==NULL || bConverged))
2552 if (print_forcefield(fplog,enerd->term,mdatoms->homenr,
2553 f,NULL,xcopy,
2554 &(top_global->mols),mdatoms->massT,pres))
2556 if (gmx_parallel_env_initialized())
2558 gmx_finalize();
2560 fprintf(stderr,"\n");
2561 exit(0);
2564 if (!bGStat)
2566 /* We will not sum ekinh_old,
2567 * so signal that we still have to do it.
2569 bSumEkinhOld = TRUE;
2572 if (bTCR)
2574 /* Only do GCT when the relaxation of shells (minimization) has converged,
2575 * otherwise we might be coupling to bogus energies.
2576 * In parallel we must always do this, because the other sims might
2577 * update the FF.
2580 /* Since this is called with the new coordinates state->x, I assume
2581 * we want the new box state->box too. / EL 20040121
2583 do_coupling(fplog,oenv,nfile,fnm,tcr,t,step,enerd->term,fr,
2584 ir,MASTER(cr),
2585 mdatoms,&(top->idef),mu_aver,
2586 top_global->mols.nr,cr,
2587 state->box,total_vir,pres,
2588 mu_tot,state->x,f,bConverged);
2589 debug_gmx();
2592 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
2594 /* sum up the foreign energy and dhdl terms */
2595 sum_dhdl(enerd,state->lambda,ir);
2597 /* use the directly determined last velocity, not actually the averaged half steps */
2598 if (bTrotter && ir->eI==eiVV)
2600 enerd->term[F_EKIN] = last_ekin;
2602 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
2604 if (bVV)
2606 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
2608 else
2610 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir,state,&MassQ);
2612 /* Check for excessively large energies */
2613 if (bIonize)
2615 #ifdef GMX_DOUBLE
2616 real etot_max = 1e200;
2617 #else
2618 real etot_max = 1e30;
2619 #endif
2620 if (fabs(enerd->term[F_ETOT]) > etot_max)
2622 fprintf(stderr,"Energy too large (%g), giving up\n",
2623 enerd->term[F_ETOT]);
2626 /* ######### END PREPARING EDR OUTPUT ########### */
2628 /* Time for performance */
2629 if (((step % stepout) == 0) || bLastStep)
2631 runtime_upd_proc(runtime);
2634 /* Output stuff */
2635 if (MASTER(cr))
2637 gmx_bool do_dr,do_or;
2639 if (!(bStartingFromCpt && (EI_VV(ir->eI))))
2641 if (bNstEner)
2643 upd_mdebin(mdebin,bDoDHDL, TRUE,
2644 t,mdatoms->tmass,enerd,state,lastbox,
2645 shake_vir,force_vir,total_vir,pres,
2646 ekind,mu_tot,constr);
2648 else
2650 upd_mdebin_step(mdebin);
2653 do_dr = do_per_step(step,ir->nstdisreout);
2654 do_or = do_per_step(step,ir->nstorireout);
2656 print_ebin(outf->fp_ene,do_ene,do_dr,do_or,do_log?fplog:NULL,
2657 step,t,
2658 eprNORMAL,bCompact,mdebin,fcd,groups,&(ir->opts));
2660 if (ir->ePull != epullNO)
2662 pull_print_output(ir->pull,step,t);
2665 if (do_per_step(step,ir->nstlog))
2667 if(fflush(fplog) != 0)
2669 gmx_fatal(FARGS,"Cannot flush logfile - maybe you are out of quota?");
2675 /* Remaining runtime */
2676 if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal() ))
2678 if (shellfc)
2680 fprintf(stderr,"\n");
2682 print_time(stderr,runtime,step,ir,cr);
2685 /* Replica exchange */
2686 bExchanged = FALSE;
2687 if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
2688 do_per_step(step,repl_ex_nst))
2690 bExchanged = replica_exchange(fplog,cr,repl_ex,
2691 state_global,enerd->term,
2692 state,step,t);
2694 if (bExchanged && DOMAINDECOMP(cr))
2696 dd_partition_system(fplog,step,cr,TRUE,1,
2697 state_global,top_global,ir,
2698 state,&f,mdatoms,top,fr,
2699 vsite,shellfc,constr,
2700 nrnb,wcycle,FALSE);
2704 bFirstStep = FALSE;
2705 bInitStep = FALSE;
2706 bStartingFromCpt = FALSE;
2708 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
2709 /* With all integrators, except VV, we need to retain the pressure
2710 * at the current step for coupling at the next step.
2712 if ((state->flags & (1<<estPRES_PREV)) &&
2713 (bGStatEveryStep ||
2714 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
2716 /* Store the pressure in t_state for pressure coupling
2717 * at the next MD step.
2719 copy_mat(pres,state->pres_prev);
2722 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
2724 if ( (membed!=NULL) && (!bLastStep) )
2725 rescale_membed(step_rel,membed,state_global->x);
2727 if (bRerunMD)
2729 if (MASTER(cr))
2731 /* read next frame from input trajectory */
2732 bNotLastFrame = read_next_frame(oenv,status,&rerun_fr);
2735 if (PAR(cr))
2737 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
2741 if (!bRerunMD || !rerun_fr.bStep)
2743 /* increase the MD step number */
2744 step++;
2745 step_rel++;
2748 cycles = wallcycle_stop(wcycle,ewcSTEP);
2749 if (DOMAINDECOMP(cr) && wcycle)
2751 dd_cycles_add(cr->dd,cycles,ddCyclStep);
2754 if (step_rel == wcycle_get_reset_counters(wcycle) ||
2755 gs.set[eglsRESETCOUNTERS] != 0)
2757 /* Reset all the counters related to performance over the run */
2758 reset_all_counters(fplog,cr,step,&step_rel,ir,wcycle,nrnb,runtime);
2759 wcycle_set_reset_counters(wcycle,-1);
2760 /* Correct max_hours for the elapsed time */
2761 max_hours -= run_time/(60.0*60.0);
2762 bResetCountersHalfMaxH = FALSE;
2763 gs.set[eglsRESETCOUNTERS] = 0;
2766 /* End of main MD loop */
2767 debug_gmx();
2769 /* Stop the time */
2770 runtime_end(runtime);
2772 if (bRerunMD && MASTER(cr))
2774 close_trj(status);
2777 if (!(cr->duty & DUTY_PME))
2779 /* Tell the PME only node to finish */
2780 gmx_pme_finish(cr);
2783 if (MASTER(cr))
2785 if (ir->nstcalcenergy > 0 && !bRerunMD)
2787 print_ebin(outf->fp_ene,FALSE,FALSE,FALSE,fplog,step,t,
2788 eprAVER,FALSE,mdebin,fcd,groups,&(ir->opts));
2792 done_mdoutf(outf);
2794 debug_gmx();
2796 if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
2798 fprintf(fplog,"Average neighborlist lifetime: %.1f steps, std.dev.: %.1f steps\n",nlh.s1/nlh.nns,sqrt(nlh.s2/nlh.nns - sqr(nlh.s1/nlh.nns)));
2799 fprintf(fplog,"Average number of atoms that crossed the half buffer length: %.1f\n\n",nlh.ab/nlh.nns);
2802 if (shellfc && fplog)
2804 fprintf(fplog,"Fraction of iterations that converged: %.2f %%\n",
2805 (nconverged*100.0)/step_rel);
2806 fprintf(fplog,"Average number of force evaluations per MD step: %.2f\n\n",
2807 tcount/step_rel);
2810 if (repl_ex_nst > 0 && MASTER(cr))
2812 print_replica_exchange_statistics(fplog,repl_ex);
2815 runtime->nsteps_done = step_rel;
2817 return 0;