fixed zero viscosity energy/log file output with cos_acceleration
[gromacs.git] / src / kernel / md.c
blobdde06c1b46aac184ab06afdc31149a6d51eff6d1
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"
93 #ifdef GMX_LIB_MPI
94 #include <mpi.h>
95 #endif
96 #ifdef GMX_THREADS
97 #include "tmpi.h"
98 #endif
100 #ifdef GMX_FAHCORE
101 #include "corewrap.h"
102 #endif
105 /* simulation conditions to transmit. Keep in mind that they are
106 transmitted to other nodes through an MPI_Reduce after
107 casting them to a real (so the signals can be sent together with other
108 data). This means that the only meaningful values are positive,
109 negative or zero. */
110 enum { eglsNABNSB, eglsCHKPT, eglsSTOPCOND, eglsRESETCOUNTERS, eglsNR };
111 /* Is the signal in one simulation independent of other simulations? */
112 gmx_bool gs_simlocal[eglsNR] = { TRUE, FALSE, FALSE, TRUE };
114 typedef struct {
115 int nstms; /* The frequency for intersimulation communication */
116 int sig[eglsNR]; /* The signal set by one process in do_md */
117 int set[eglsNR]; /* The communicated signal, equal for all processes */
118 } globsig_t;
121 static int multisim_min(const gmx_multisim_t *ms,int nmin,int n)
123 int *buf;
124 gmx_bool bPos,bEqual;
125 int s,d;
127 snew(buf,ms->nsim);
128 buf[ms->sim] = n;
129 gmx_sumi_sim(ms->nsim,buf,ms);
130 bPos = TRUE;
131 bEqual = TRUE;
132 for(s=0; s<ms->nsim; s++)
134 bPos = bPos && (buf[s] > 0);
135 bEqual = bEqual && (buf[s] == buf[0]);
137 if (bPos)
139 if (bEqual)
141 nmin = min(nmin,buf[0]);
143 else
145 /* Find the least common multiple */
146 for(d=2; d<nmin; d++)
148 s = 0;
149 while (s < ms->nsim && d % buf[s] == 0)
151 s++;
153 if (s == ms->nsim)
155 /* We found the LCM and it is less than nmin */
156 nmin = d;
157 break;
162 sfree(buf);
164 return nmin;
167 static int multisim_nstsimsync(const t_commrec *cr,
168 const t_inputrec *ir,int repl_ex_nst)
170 int nmin;
172 if (MASTER(cr))
174 nmin = INT_MAX;
175 nmin = multisim_min(cr->ms,nmin,ir->nstlist);
176 nmin = multisim_min(cr->ms,nmin,ir->nstcalcenergy);
177 nmin = multisim_min(cr->ms,nmin,repl_ex_nst);
178 if (nmin == INT_MAX)
180 gmx_fatal(FARGS,"Can not find an appropriate interval for inter-simulation communication, since nstlist, nstcalcenergy and -replex are all <= 0");
182 /* Avoid inter-simulation communication at every (second) step */
183 if (nmin <= 2)
185 nmin = 10;
189 gmx_bcast(sizeof(int),&nmin,cr);
191 return nmin;
194 static void init_global_signals(globsig_t *gs,const t_commrec *cr,
195 const t_inputrec *ir,int repl_ex_nst)
197 int i;
199 if (MULTISIM(cr))
201 gs->nstms = multisim_nstsimsync(cr,ir,repl_ex_nst);
202 if (debug)
204 fprintf(debug,"Syncing simulations for checkpointing and termination every %d steps\n",gs->nstms);
207 else
209 gs->nstms = 1;
212 for(i=0; i<eglsNR; i++)
214 gs->sig[i] = 0;
215 gs->set[i] = 0;
219 static void copy_coupling_state(t_state *statea,t_state *stateb,
220 gmx_ekindata_t *ekinda,gmx_ekindata_t *ekindb, t_grpopts* opts)
223 /* MRS note -- might be able to get rid of some of the arguments. Look over it when it's all debugged */
225 int i,j,nc;
227 /* Make sure we have enough space for x and v */
228 if (statea->nalloc > stateb->nalloc)
230 stateb->nalloc = statea->nalloc;
231 srenew(stateb->x,stateb->nalloc);
232 srenew(stateb->v,stateb->nalloc);
235 stateb->natoms = statea->natoms;
236 stateb->ngtc = statea->ngtc;
237 stateb->nnhpres = statea->nnhpres;
238 stateb->veta = statea->veta;
239 if (ekinda)
241 copy_mat(ekinda->ekin,ekindb->ekin);
242 for (i=0; i<stateb->ngtc; i++)
244 ekindb->tcstat[i].T = ekinda->tcstat[i].T;
245 ekindb->tcstat[i].Th = ekinda->tcstat[i].Th;
246 copy_mat(ekinda->tcstat[i].ekinh,ekindb->tcstat[i].ekinh);
247 copy_mat(ekinda->tcstat[i].ekinf,ekindb->tcstat[i].ekinf);
248 ekindb->tcstat[i].ekinscalef_nhc = ekinda->tcstat[i].ekinscalef_nhc;
249 ekindb->tcstat[i].ekinscaleh_nhc = ekinda->tcstat[i].ekinscaleh_nhc;
250 ekindb->tcstat[i].vscale_nhc = ekinda->tcstat[i].vscale_nhc;
253 copy_rvecn(statea->x,stateb->x,0,stateb->natoms);
254 copy_rvecn(statea->v,stateb->v,0,stateb->natoms);
255 copy_mat(statea->box,stateb->box);
256 copy_mat(statea->box_rel,stateb->box_rel);
257 copy_mat(statea->boxv,stateb->boxv);
259 for (i = 0; i<stateb->ngtc; i++)
261 nc = i*opts->nhchainlength;
262 for (j=0; j<opts->nhchainlength; j++)
264 stateb->nosehoover_xi[nc+j] = statea->nosehoover_xi[nc+j];
265 stateb->nosehoover_vxi[nc+j] = statea->nosehoover_vxi[nc+j];
268 if (stateb->nhpres_xi != NULL)
270 for (i = 0; i<stateb->nnhpres; i++)
272 nc = i*opts->nhchainlength;
273 for (j=0; j<opts->nhchainlength; j++)
275 stateb->nhpres_xi[nc+j] = statea->nhpres_xi[nc+j];
276 stateb->nhpres_vxi[nc+j] = statea->nhpres_vxi[nc+j];
282 static real compute_conserved_from_auxiliary(t_inputrec *ir, t_state *state, t_extmass *MassQ)
284 real quantity = 0;
285 switch (ir->etc)
287 case etcNO:
288 break;
289 case etcBERENDSEN:
290 break;
291 case etcNOSEHOOVER:
292 quantity = NPT_energy(ir,state,MassQ);
293 break;
294 case etcVRESCALE:
295 quantity = vrescale_energy(&(ir->opts),state->therm_integral);
296 break;
297 default:
298 break;
300 return quantity;
303 static void compute_globals(FILE *fplog, gmx_global_stat_t gstat, t_commrec *cr, t_inputrec *ir,
304 t_forcerec *fr, gmx_ekindata_t *ekind,
305 t_state *state, t_state *state_global, t_mdatoms *mdatoms,
306 t_nrnb *nrnb, t_vcm *vcm, gmx_wallcycle_t wcycle,
307 gmx_enerdata_t *enerd,tensor force_vir, tensor shake_vir, tensor total_vir,
308 tensor pres, rvec mu_tot, gmx_constr_t constr,
309 globsig_t *gs,gmx_bool bInterSimGS,
310 matrix box, gmx_mtop_t *top_global, real *pcurr,
311 int natoms, gmx_bool *bSumEkinhOld, int flags)
313 int i,gsi;
314 real gs_buf[eglsNR];
315 tensor corr_vir,corr_pres,shakeall_vir;
316 gmx_bool bEner,bPres,bTemp, bVV;
317 gmx_bool bRerunMD, bStopCM, bGStat, bIterate,
318 bFirstIterate,bReadEkin,bEkinAveVel,bScaleEkin, bConstrain;
319 real ekin,temp,prescorr,enercorr,dvdlcorr;
321 /* translate CGLO flags to gmx_booleans */
322 bRerunMD = flags & CGLO_RERUNMD;
323 bStopCM = flags & CGLO_STOPCM;
324 bGStat = flags & CGLO_GSTAT;
326 bReadEkin = (flags & CGLO_READEKIN);
327 bScaleEkin = (flags & CGLO_SCALEEKIN);
328 bEner = flags & CGLO_ENERGY;
329 bTemp = flags & CGLO_TEMPERATURE;
330 bPres = (flags & CGLO_PRESSURE);
331 bConstrain = (flags & CGLO_CONSTRAINT);
332 bIterate = (flags & CGLO_ITERATE);
333 bFirstIterate = (flags & CGLO_FIRSTITERATE);
335 /* we calculate a full state kinetic energy either with full-step velocity verlet
336 or half step where we need the pressure */
338 bEkinAveVel = (ir->eI==eiVV || (ir->eI==eiVVAK && bPres) || bReadEkin);
340 /* in initalization, it sums the shake virial in vv, and to
341 sums ekinh_old in leapfrog (or if we are calculating ekinh_old) for other reasons */
343 /* ########## Kinetic energy ############## */
345 if (bTemp)
347 /* Non-equilibrium MD: this is parallellized, but only does communication
348 * when there really is NEMD.
351 if (PAR(cr) && (ekind->bNEMD))
353 accumulate_u(cr,&(ir->opts),ekind);
355 debug_gmx();
356 if (bReadEkin)
358 restore_ekinstate_from_state(cr,ekind,&state_global->ekinstate);
360 else
363 calc_ke_part(state,&(ir->opts),mdatoms,ekind,nrnb,bEkinAveVel,bIterate);
366 debug_gmx();
368 /* Calculate center of mass velocity if necessary, also parallellized */
369 if (bStopCM && !bRerunMD && bEner)
371 calc_vcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms,
372 state->x,state->v,vcm);
376 if (bTemp || bPres || bEner || bConstrain)
378 if (!bGStat)
380 /* We will not sum ekinh_old,
381 * so signal that we still have to do it.
383 *bSumEkinhOld = TRUE;
386 else
388 if (gs != NULL)
390 for(i=0; i<eglsNR; i++)
392 gs_buf[i] = gs->sig[i];
395 if (PAR(cr))
397 wallcycle_start(wcycle,ewcMoveE);
398 GMX_MPE_LOG(ev_global_stat_start);
399 global_stat(fplog,gstat,cr,enerd,force_vir,shake_vir,mu_tot,
400 ir,ekind,constr,vcm,
401 gs != NULL ? eglsNR : 0,gs_buf,
402 top_global,state,
403 *bSumEkinhOld,flags);
404 GMX_MPE_LOG(ev_global_stat_finish);
405 wallcycle_stop(wcycle,ewcMoveE);
407 if (gs != NULL)
409 if (MULTISIM(cr) && bInterSimGS)
411 if (MASTER(cr))
413 /* Communicate the signals between the simulations */
414 gmx_sum_sim(eglsNR,gs_buf,cr->ms);
416 /* Communicate the signals form the master to the others */
417 gmx_bcast(eglsNR*sizeof(gs_buf[0]),gs_buf,cr);
419 for(i=0; i<eglsNR; i++)
421 if (bInterSimGS || gs_simlocal[i])
423 /* Set the communicated signal only when it is non-zero,
424 * since signals might not be processed at each MD step.
426 gsi = (gs_buf[i] >= 0 ?
427 (int)(gs_buf[i] + 0.5) :
428 (int)(gs_buf[i] - 0.5));
429 if (gsi != 0)
431 gs->set[i] = gsi;
433 /* Turn off the local signal */
434 gs->sig[i] = 0;
438 *bSumEkinhOld = FALSE;
442 if (!ekind->bNEMD && debug && bTemp && (vcm->nr > 0))
444 correct_ekin(debug,
445 mdatoms->start,mdatoms->start+mdatoms->homenr,
446 state->v,vcm->group_p[0],
447 mdatoms->massT,mdatoms->tmass,ekind->ekin);
450 if (bEner) {
451 /* Do center of mass motion removal */
452 if (bStopCM && !bRerunMD) /* is this correct? Does it get called too often with this logic? */
454 check_cm_grp(fplog,vcm,ir,1);
455 do_stopcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms->cVCM,
456 state->x,state->v,vcm);
457 inc_nrnb(nrnb,eNR_STOPCM,mdatoms->homenr);
460 /* Calculate the amplitude of the cosine velocity profile */
461 ekind->cosacc.vcos = ekind->cosacc.mvcos/mdatoms->tmass;
464 if (bTemp)
466 /* Sum the kinetic energies of the groups & calc temp */
467 /* compute full step kinetic energies if vv, or if vv-avek and we are computing the pressure with IR_NPT_TROTTER */
468 /* three maincase: VV with AveVel (md-vv), vv with AveEkin (md-vv-avek), leap with AveEkin (md).
469 Leap with AveVel is not supported; it's not clear that it will actually work.
470 bEkinAveVel: If TRUE, we simply multiply ekin by ekinscale to get a full step kinetic energy.
471 If FALSE, we average ekinh_old and ekinh*ekinscale_nhc to get an averaged half step kinetic energy.
472 bSaveEkinOld: If TRUE (in the case of iteration = bIterate is TRUE), we don't reset the ekinscale_nhc.
473 If FALSE, we go ahead and erase over it.
475 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,&(enerd->term[F_DKDL]),
476 bEkinAveVel,bIterate,bScaleEkin);
478 enerd->term[F_EKIN] = trace(ekind->ekin);
481 /* ########## Long range energy information ###### */
483 if (bEner || bPres || bConstrain)
485 calc_dispcorr(fplog,ir,fr,0,top_global->natoms,box,state->lambda,
486 corr_pres,corr_vir,&prescorr,&enercorr,&dvdlcorr);
489 if (bEner && bFirstIterate)
491 enerd->term[F_DISPCORR] = enercorr;
492 enerd->term[F_EPOT] += enercorr;
493 enerd->term[F_DVDL] += dvdlcorr;
494 if (fr->efep != efepNO) {
495 enerd->dvdl_lin += dvdlcorr;
499 /* ########## Now pressure ############## */
500 if (bPres || bConstrain)
503 m_add(force_vir,shake_vir,total_vir);
505 /* Calculate pressure and apply LR correction if PPPM is used.
506 * Use the box from last timestep since we already called update().
509 enerd->term[F_PRES] = calc_pres(fr->ePBC,ir->nwall,box,ekind->ekin,total_vir,pres,
510 (fr->eeltype==eelPPPM)?enerd->term[F_COUL_RECIP]:0.0);
512 /* Calculate long range corrections to pressure and energy */
513 /* this adds to enerd->term[F_PRES] and enerd->term[F_ETOT],
514 and computes enerd->term[F_DISPCORR]. Also modifies the
515 total_vir and pres tesors */
517 m_add(total_vir,corr_vir,total_vir);
518 m_add(pres,corr_pres,pres);
519 enerd->term[F_PDISPCORR] = prescorr;
520 enerd->term[F_PRES] += prescorr;
521 *pcurr = enerd->term[F_PRES];
522 /* calculate temperature using virial */
523 enerd->term[F_VTEMP] = calc_temp(trace(total_vir),ir->opts.nrdf[0]);
529 /* Definitions for convergence of iterated constraints */
531 /* iterate constraints up to 50 times */
532 #define MAXITERCONST 50
534 /* data type */
535 typedef struct
537 real f,fprev,x,xprev;
538 int iter_i;
539 gmx_bool bIterate;
540 real allrelerr[MAXITERCONST+2];
541 int num_close; /* number of "close" violations, caused by limited precision. */
542 } gmx_iterate_t;
544 #ifdef GMX_DOUBLE
545 #define CONVERGEITER 0.000000001
546 #define CLOSE_ENOUGH 0.000001000
547 #else
548 #define CONVERGEITER 0.0001
549 #define CLOSE_ENOUGH 0.0050
550 #endif
552 /* we want to keep track of the close calls. If there are too many, there might be some other issues.
553 so we make sure that it's either less than some predetermined number, or if more than that number,
554 only some small fraction of the total. */
555 #define MAX_NUMBER_CLOSE 50
556 #define FRACTION_CLOSE 0.001
558 /* maximum length of cyclic traps to check, emerging from limited numerical precision */
559 #define CYCLEMAX 20
561 static void gmx_iterate_init(gmx_iterate_t *iterate,gmx_bool bIterate)
563 int i;
565 iterate->iter_i = 0;
566 iterate->bIterate = bIterate;
567 iterate->num_close = 0;
568 for (i=0;i<MAXITERCONST+2;i++)
570 iterate->allrelerr[i] = 0;
574 static gmx_bool done_iterating(const t_commrec *cr,FILE *fplog, int nsteps, gmx_iterate_t *iterate, gmx_bool bFirstIterate, real fom, real *newf)
576 /* monitor convergence, and use a secant search to propose new
577 values.
578 x_{i} - x_{i-1}
579 The secant method computes x_{i+1} = x_{i} - f(x_{i}) * ---------------------
580 f(x_{i}) - f(x_{i-1})
582 The function we are trying to zero is fom-x, where fom is the
583 "figure of merit" which is the pressure (or the veta value) we
584 would get by putting in an old value of the pressure or veta into
585 the incrementor function for the step or half step. I have
586 verified that this gives the same answer as self consistent
587 iteration, usually in many fewer steps, especially for small tau_p.
589 We could possibly eliminate an iteration with proper use
590 of the value from the previous step, but that would take a bit
591 more bookkeeping, especially for veta, since tests indicate the
592 function of veta on the last step is not sufficiently close to
593 guarantee convergence this step. This is
594 good enough for now. On my tests, I could use tau_p down to
595 0.02, which is smaller that would ever be necessary in
596 practice. Generally, 3-5 iterations will be sufficient */
598 real relerr,err,xmin;
599 char buf[256];
600 int i;
601 gmx_bool incycle;
603 if (bFirstIterate)
605 iterate->x = fom;
606 iterate->f = fom-iterate->x;
607 iterate->xprev = 0;
608 iterate->fprev = 0;
609 *newf = fom;
611 else
613 iterate->f = fom-iterate->x; /* we want to zero this difference */
614 if ((iterate->iter_i > 1) && (iterate->iter_i < MAXITERCONST))
616 if (iterate->f==iterate->fprev)
618 *newf = iterate->f;
620 else
622 *newf = iterate->x - (iterate->x-iterate->xprev)*(iterate->f)/(iterate->f-iterate->fprev);
625 else
627 /* just use self-consistent iteration the first step to initialize, or
628 if it's not converging (which happens occasionally -- need to investigate why) */
629 *newf = fom;
632 /* Consider a slight shortcut allowing us to exit one sooner -- we check the
633 difference between the closest of x and xprev to the new
634 value. To be 100% certain, we should check the difference between
635 the last result, and the previous result, or
637 relerr = (fabs((x-xprev)/fom));
639 but this is pretty much never necessary under typical conditions.
640 Checking numerically, it seems to lead to almost exactly the same
641 trajectories, but there are small differences out a few decimal
642 places in the pressure, and eventually in the v_eta, but it could
643 save an interation.
645 if (fabs(*newf-x) < fabs(*newf - xprev)) { xmin = x;} else { xmin = xprev;}
646 relerr = (fabs((*newf-xmin) / *newf));
649 err = fabs((iterate->f-iterate->fprev));
650 relerr = fabs(err/fom);
652 iterate->allrelerr[iterate->iter_i] = relerr;
654 if (iterate->iter_i > 0)
656 if (debug)
658 fprintf(debug,"Iterating NPT constraints: %6i %20.12f%14.6g%20.12f\n",
659 iterate->iter_i,fom,relerr,*newf);
662 if ((relerr < CONVERGEITER) || (err < CONVERGEITER) || (fom==0) || ((iterate->x == iterate->xprev) && iterate->iter_i > 1))
664 iterate->bIterate = FALSE;
665 if (debug)
667 fprintf(debug,"Iterating NPT constraints: CONVERGED\n");
669 return TRUE;
671 if (iterate->iter_i > MAXITERCONST)
673 if (relerr < CLOSE_ENOUGH)
675 incycle = FALSE;
676 for (i=1;i<CYCLEMAX;i++) {
677 if ((iterate->allrelerr[iterate->iter_i-(1+i)] == iterate->allrelerr[iterate->iter_i-1]) &&
678 (iterate->allrelerr[iterate->iter_i-(1+i)] == iterate->allrelerr[iterate->iter_i-(1+2*i)])) {
679 incycle = TRUE;
680 if (debug)
682 fprintf(debug,"Exiting from an NPT iterating cycle of length %d\n",i);
684 break;
688 if (incycle) {
689 /* step 1: trapped in a numerical attractor */
690 /* we are trapped in a numerical attractor, and can't converge any more, and are close to the final result.
691 Better to give up convergence here than have the simulation die.
693 iterate->num_close++;
694 return TRUE;
696 else
698 /* Step #2: test if we are reasonably close for other reasons, then monitor the number. If not, die */
700 /* how many close calls have we had? If less than a few, we're OK */
701 if (iterate->num_close < MAX_NUMBER_CLOSE)
703 sprintf(buf,"Slight numerical convergence deviation with NPT at step %d, relative error only %10.5g, likely not a problem, continuing\n",nsteps,relerr);
704 md_print_warning(cr,fplog,buf);
705 iterate->num_close++;
706 return TRUE;
707 /* if more than a few, check the total fraction. If too high, die. */
708 } else if (iterate->num_close/(double)nsteps > FRACTION_CLOSE) {
709 gmx_fatal(FARGS,"Could not converge NPT constraints, too many exceptions (%d%%\n",iterate->num_close/(double)nsteps);
713 else
715 gmx_fatal(FARGS,"Could not converge NPT constraints\n");
720 iterate->xprev = iterate->x;
721 iterate->x = *newf;
722 iterate->fprev = iterate->f;
723 iterate->iter_i++;
725 return FALSE;
728 static void check_nst_param(FILE *fplog,t_commrec *cr,
729 const char *desc_nst,int nst,
730 const char *desc_p,int *p)
732 char buf[STRLEN];
734 if (*p > 0 && *p % nst != 0)
736 /* Round up to the next multiple of nst */
737 *p = ((*p)/nst + 1)*nst;
738 sprintf(buf,"NOTE: %s changes %s to %d\n",desc_nst,desc_p,*p);
739 md_print_warning(cr,fplog,buf);
743 static void reset_all_counters(FILE *fplog,t_commrec *cr,
744 gmx_large_int_t step,
745 gmx_large_int_t *step_rel,t_inputrec *ir,
746 gmx_wallcycle_t wcycle,t_nrnb *nrnb,
747 gmx_runtime_t *runtime)
749 char buf[STRLEN],sbuf[STEPSTRSIZE];
751 /* Reset all the counters related to performance over the run */
752 sprintf(buf,"Step %s: resetting all time and cycle counters\n",
753 gmx_step_str(step,sbuf));
754 md_print_warning(cr,fplog,buf);
756 wallcycle_stop(wcycle,ewcRUN);
757 wallcycle_reset_all(wcycle);
758 if (DOMAINDECOMP(cr))
760 reset_dd_statistics_counters(cr->dd);
762 init_nrnb(nrnb);
763 ir->init_step += *step_rel;
764 ir->nsteps -= *step_rel;
765 *step_rel = 0;
766 wallcycle_start(wcycle,ewcRUN);
767 runtime_start(runtime);
768 print_date_and_time(fplog,cr->nodeid,"Restarted time",runtime);
771 static void min_zero(int *n,int i)
773 if (i > 0 && (*n == 0 || i < *n))
775 *n = i;
779 static int lcd4(int i1,int i2,int i3,int i4)
781 int nst;
783 nst = 0;
784 min_zero(&nst,i1);
785 min_zero(&nst,i2);
786 min_zero(&nst,i3);
787 min_zero(&nst,i4);
788 if (nst == 0)
790 gmx_incons("All 4 inputs for determininig nstglobalcomm are <= 0");
793 while (nst > 1 && ((i1 > 0 && i1 % nst != 0) ||
794 (i2 > 0 && i2 % nst != 0) ||
795 (i3 > 0 && i3 % nst != 0) ||
796 (i4 > 0 && i4 % nst != 0)))
798 nst--;
801 return nst;
804 static int check_nstglobalcomm(FILE *fplog,t_commrec *cr,
805 int nstglobalcomm,t_inputrec *ir)
807 char buf[STRLEN];
809 if (!EI_DYNAMICS(ir->eI))
811 nstglobalcomm = 1;
814 if (nstglobalcomm == -1)
816 if (!(ir->nstcalcenergy > 0 ||
817 ir->nstlist > 0 ||
818 ir->etc != etcNO ||
819 ir->epc != epcNO))
821 nstglobalcomm = 10;
822 if (ir->nstenergy > 0 && ir->nstenergy < nstglobalcomm)
824 nstglobalcomm = ir->nstenergy;
827 else
829 /* Ensure that we do timely global communication for
830 * (possibly) each of the four following options.
832 nstglobalcomm = lcd4(ir->nstcalcenergy,
833 ir->nstlist,
834 ir->etc != etcNO ? ir->nsttcouple : 0,
835 ir->epc != epcNO ? ir->nstpcouple : 0);
838 else
840 if (ir->nstlist > 0 &&
841 nstglobalcomm > ir->nstlist && nstglobalcomm % ir->nstlist != 0)
843 nstglobalcomm = (nstglobalcomm / ir->nstlist)*ir->nstlist;
844 sprintf(buf,"WARNING: nstglobalcomm is larger than nstlist, but not a multiple, setting it to %d\n",nstglobalcomm);
845 md_print_warning(cr,fplog,buf);
847 if (ir->nstcalcenergy > 0)
849 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
850 "nstcalcenergy",&ir->nstcalcenergy);
852 if (ir->etc != etcNO && ir->nsttcouple > 0)
854 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
855 "nsttcouple",&ir->nsttcouple);
857 if (ir->epc != epcNO && ir->nstpcouple > 0)
859 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
860 "nstpcouple",&ir->nstpcouple);
863 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
864 "nstenergy",&ir->nstenergy);
866 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
867 "nstlog",&ir->nstlog);
870 if (ir->comm_mode != ecmNO && ir->nstcomm < nstglobalcomm)
872 sprintf(buf,"WARNING: Changing nstcomm from %d to %d\n",
873 ir->nstcomm,nstglobalcomm);
874 md_print_warning(cr,fplog,buf);
875 ir->nstcomm = nstglobalcomm;
878 return nstglobalcomm;
881 void check_ir_old_tpx_versions(t_commrec *cr,FILE *fplog,
882 t_inputrec *ir,gmx_mtop_t *mtop)
884 /* Check required for old tpx files */
885 if (IR_TWINRANGE(*ir) && ir->nstlist > 1 &&
886 ir->nstcalcenergy % ir->nstlist != 0)
888 md_print_warning(cr,fplog,"Old tpr file with twin-range settings: modifying energy calculation and/or T/P-coupling frequencies");
890 if (gmx_mtop_ftype_count(mtop,F_CONSTR) +
891 gmx_mtop_ftype_count(mtop,F_CONSTRNC) > 0 &&
892 ir->eConstrAlg == econtSHAKE)
894 md_print_warning(cr,fplog,"With twin-range cut-off's and SHAKE the virial and pressure are incorrect");
895 if (ir->epc != epcNO)
897 gmx_fatal(FARGS,"Can not do pressure coupling with twin-range cut-off's and SHAKE");
900 check_nst_param(fplog,cr,"nstlist",ir->nstlist,
901 "nstcalcenergy",&ir->nstcalcenergy);
902 if (ir->epc != epcNO)
904 check_nst_param(fplog,cr,"nstlist",ir->nstlist,
905 "nstpcouple",&ir->nstpcouple);
907 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
908 "nstenergy",&ir->nstenergy);
909 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
910 "nstlog",&ir->nstlog);
911 if (ir->efep != efepNO)
913 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
914 "nstdhdl",&ir->nstdhdl);
919 typedef struct {
920 gmx_bool bGStatEveryStep;
921 gmx_large_int_t step_ns;
922 gmx_large_int_t step_nscheck;
923 gmx_large_int_t nns;
924 matrix scale_tot;
925 int nabnsb;
926 double s1;
927 double s2;
928 double ab;
929 double lt_runav;
930 double lt_runav2;
931 } gmx_nlheur_t;
933 static void reset_nlistheuristics(gmx_nlheur_t *nlh,gmx_large_int_t step)
935 nlh->lt_runav = 0;
936 nlh->lt_runav2 = 0;
937 nlh->step_nscheck = step;
940 static void init_nlistheuristics(gmx_nlheur_t *nlh,
941 gmx_bool bGStatEveryStep,gmx_large_int_t step)
943 nlh->bGStatEveryStep = bGStatEveryStep;
944 nlh->nns = 0;
945 nlh->nabnsb = 0;
946 nlh->s1 = 0;
947 nlh->s2 = 0;
948 nlh->ab = 0;
950 reset_nlistheuristics(nlh,step);
953 static void update_nliststatistics(gmx_nlheur_t *nlh,gmx_large_int_t step)
955 gmx_large_int_t nl_lt;
956 char sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
958 /* Determine the neighbor list life time */
959 nl_lt = step - nlh->step_ns;
960 if (debug)
962 fprintf(debug,"%d atoms beyond ns buffer, updating neighbor list after %s steps\n",nlh->nabnsb,gmx_step_str(nl_lt,sbuf));
964 nlh->nns++;
965 nlh->s1 += nl_lt;
966 nlh->s2 += nl_lt*nl_lt;
967 nlh->ab += nlh->nabnsb;
968 if (nlh->lt_runav == 0)
970 nlh->lt_runav = nl_lt;
971 /* Initialize the fluctuation average
972 * such that at startup we check after 0 steps.
974 nlh->lt_runav2 = sqr(nl_lt/2.0);
976 /* Running average with 0.9 gives an exp. history of 9.5 */
977 nlh->lt_runav2 = 0.9*nlh->lt_runav2 + 0.1*sqr(nlh->lt_runav - nl_lt);
978 nlh->lt_runav = 0.9*nlh->lt_runav + 0.1*nl_lt;
979 if (nlh->bGStatEveryStep)
981 /* Always check the nlist validity */
982 nlh->step_nscheck = step;
984 else
986 /* We check after: <life time> - 2*sigma
987 * The factor 2 is quite conservative,
988 * but we assume that with nstlist=-1 the user
989 * prefers exact integration over performance.
991 nlh->step_nscheck = step
992 + (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)) - 1;
994 if (debug)
996 fprintf(debug,"nlist life time %s run av. %4.1f sig %3.1f check %s check with -gcom %d\n",
997 gmx_step_str(nl_lt,sbuf),nlh->lt_runav,sqrt(nlh->lt_runav2),
998 gmx_step_str(nlh->step_nscheck-step+1,sbuf2),
999 (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)));
1003 static void set_nlistheuristics(gmx_nlheur_t *nlh,gmx_bool bReset,gmx_large_int_t step)
1005 int d;
1007 if (bReset)
1009 reset_nlistheuristics(nlh,step);
1011 else
1013 update_nliststatistics(nlh,step);
1016 nlh->step_ns = step;
1017 /* Initialize the cumulative coordinate scaling matrix */
1018 clear_mat(nlh->scale_tot);
1019 for(d=0; d<DIM; d++)
1021 nlh->scale_tot[d][d] = 1.0;
1025 static void rerun_parallel_comm(t_commrec *cr,t_trxframe *fr,
1026 gmx_bool *bNotLastFrame)
1028 gmx_bool bAlloc;
1029 rvec *xp,*vp;
1031 bAlloc = (fr->natoms == 0);
1033 if (MASTER(cr) && !*bNotLastFrame)
1035 fr->natoms = -1;
1037 xp = fr->x;
1038 vp = fr->v;
1039 gmx_bcast(sizeof(*fr),fr,cr);
1040 fr->x = xp;
1041 fr->v = vp;
1043 *bNotLastFrame = (fr->natoms >= 0);
1045 if (*bNotLastFrame && PARTDECOMP(cr))
1047 /* x and v are the only variable size quantities stored in trr
1048 * that are required for rerun (f is not needed).
1050 if (bAlloc)
1052 snew(fr->x,fr->natoms);
1053 snew(fr->v,fr->natoms);
1055 if (fr->bX)
1057 gmx_bcast(fr->natoms*sizeof(fr->x[0]),fr->x[0],cr);
1059 if (fr->bV)
1061 gmx_bcast(fr->natoms*sizeof(fr->v[0]),fr->v[0],cr);
1066 double do_md(FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
1067 const output_env_t oenv, gmx_bool bVerbose,gmx_bool bCompact,
1068 int nstglobalcomm,
1069 gmx_vsite_t *vsite,gmx_constr_t constr,
1070 int stepout,t_inputrec *ir,
1071 gmx_mtop_t *top_global,
1072 t_fcdata *fcd,
1073 t_state *state_global,
1074 t_mdatoms *mdatoms,
1075 t_nrnb *nrnb,gmx_wallcycle_t wcycle,
1076 gmx_edsam_t ed,t_forcerec *fr,
1077 int repl_ex_nst,int repl_ex_seed,
1078 real cpt_period,real max_hours,
1079 const char *deviceOptions,
1080 unsigned long Flags,
1081 gmx_runtime_t *runtime)
1083 gmx_mdoutf_t *outf;
1084 gmx_large_int_t step,step_rel;
1085 double run_time;
1086 double t,t0,lam0;
1087 gmx_bool bGStatEveryStep,bGStat,bNstEner,bCalcEnerPres;
1088 gmx_bool bNS,bNStList,bSimAnn,bStopCM,bRerunMD,bNotLastFrame=FALSE,
1089 bFirstStep,bStateFromTPX,bInitStep,bLastStep,
1090 bBornRadii,bStartingFromCpt;
1091 gmx_bool bDoDHDL=FALSE;
1092 gmx_bool do_ene,do_log,do_verbose,bRerunWarnNoV=TRUE,
1093 bForceUpdate=FALSE,bCPT;
1094 int mdof_flags;
1095 gmx_bool bMasterState;
1096 int force_flags,cglo_flags;
1097 tensor force_vir,shake_vir,total_vir,tmp_vir,pres;
1098 int i,m;
1099 t_trxstatus *status;
1100 rvec mu_tot;
1101 t_vcm *vcm;
1102 t_state *bufstate=NULL;
1103 matrix *scale_tot,pcoupl_mu,M,ebox;
1104 gmx_nlheur_t nlh;
1105 t_trxframe rerun_fr;
1106 gmx_repl_ex_t repl_ex=NULL;
1107 int nchkpt=1;
1109 gmx_localtop_t *top;
1110 t_mdebin *mdebin=NULL;
1111 t_state *state=NULL;
1112 rvec *f_global=NULL;
1113 int n_xtc=-1;
1114 rvec *x_xtc=NULL;
1115 gmx_enerdata_t *enerd;
1116 rvec *f=NULL;
1117 gmx_global_stat_t gstat;
1118 gmx_update_t upd=NULL;
1119 t_graph *graph=NULL;
1120 globsig_t gs;
1122 gmx_bool bFFscan;
1123 gmx_groups_t *groups;
1124 gmx_ekindata_t *ekind, *ekind_save;
1125 gmx_shellfc_t shellfc;
1126 int count,nconverged=0;
1127 real timestep=0;
1128 double tcount=0;
1129 gmx_bool bIonize=FALSE;
1130 gmx_bool bTCR=FALSE,bConverged=TRUE,bOK,bSumEkinhOld,bExchanged;
1131 gmx_bool bAppend;
1132 gmx_bool bResetCountersHalfMaxH=FALSE;
1133 gmx_bool bVV,bIterations,bFirstIterate,bTemp,bPres,bTrotter;
1134 real temp0,mu_aver=0,dvdl;
1135 int a0,a1,gnx=0,ii;
1136 atom_id *grpindex=NULL;
1137 char *grpname;
1138 t_coupl_rec *tcr=NULL;
1139 rvec *xcopy=NULL,*vcopy=NULL,*cbuf=NULL;
1140 matrix boxcopy={{0}},lastbox;
1141 tensor tmpvir;
1142 real fom,oldfom,veta_save,pcurr,scalevir,tracevir;
1143 real vetanew = 0;
1144 double cycles;
1145 real saved_conserved_quantity = 0;
1146 real last_ekin = 0;
1147 int iter_i;
1148 t_extmass MassQ;
1149 int **trotter_seq;
1150 char sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
1151 int handled_stop_condition=gmx_stop_cond_none; /* compare to get_stop_condition*/
1152 gmx_iterate_t iterate;
1153 #ifdef GMX_FAHCORE
1154 /* Temporary addition for FAHCORE checkpointing */
1155 int chkpt_ret;
1156 #endif
1158 /* Check for special mdrun options */
1159 bRerunMD = (Flags & MD_RERUN);
1160 bIonize = (Flags & MD_IONIZE);
1161 bFFscan = (Flags & MD_FFSCAN);
1162 bAppend = (Flags & MD_APPENDFILES);
1163 if (Flags & MD_RESETCOUNTERSHALFWAY)
1165 if (ir->nsteps > 0)
1167 /* Signal to reset the counters half the simulation steps. */
1168 wcycle_set_reset_counters(wcycle,ir->nsteps/2);
1170 /* Signal to reset the counters halfway the simulation time. */
1171 bResetCountersHalfMaxH = (max_hours > 0);
1174 /* md-vv uses averaged full step velocities for T-control
1175 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
1176 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
1177 bVV = EI_VV(ir->eI);
1178 if (bVV) /* to store the initial velocities while computing virial */
1180 snew(cbuf,top_global->natoms);
1182 /* all the iteratative cases - only if there are constraints */
1183 bIterations = ((IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
1184 bTrotter = (bVV && (IR_NPT_TROTTER(ir) || (IR_NVT_TROTTER(ir))));
1186 if (bRerunMD)
1188 /* Since we don't know if the frames read are related in any way,
1189 * rebuild the neighborlist at every step.
1191 ir->nstlist = 1;
1192 ir->nstcalcenergy = 1;
1193 nstglobalcomm = 1;
1196 check_ir_old_tpx_versions(cr,fplog,ir,top_global);
1198 nstglobalcomm = check_nstglobalcomm(fplog,cr,nstglobalcomm,ir);
1199 bGStatEveryStep = (nstglobalcomm == 1);
1201 if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
1203 fprintf(fplog,
1204 "To reduce the energy communication with nstlist = -1\n"
1205 "the neighbor list validity should not be checked at every step,\n"
1206 "this means that exact integration is not guaranteed.\n"
1207 "The neighbor list validity is checked after:\n"
1208 " <n.list life time> - 2*std.dev.(n.list life time) steps.\n"
1209 "In most cases this will result in exact integration.\n"
1210 "This reduces the energy communication by a factor of 2 to 3.\n"
1211 "If you want less energy communication, set nstlist > 3.\n\n");
1214 if (bRerunMD || bFFscan)
1216 ir->nstxtcout = 0;
1218 groups = &top_global->groups;
1220 /* Initial values */
1221 init_md(fplog,cr,ir,oenv,&t,&t0,&state_global->lambda,&lam0,
1222 nrnb,top_global,&upd,
1223 nfile,fnm,&outf,&mdebin,
1224 force_vir,shake_vir,mu_tot,&bSimAnn,&vcm,state_global,Flags);
1226 clear_mat(total_vir);
1227 clear_mat(pres);
1228 /* Energy terms and groups */
1229 snew(enerd,1);
1230 init_enerdata(top_global->groups.grps[egcENER].nr,ir->n_flambda,enerd);
1231 if (DOMAINDECOMP(cr))
1233 f = NULL;
1235 else
1237 snew(f,top_global->natoms);
1240 /* Kinetic energy data */
1241 snew(ekind,1);
1242 init_ekindata(fplog,top_global,&(ir->opts),ekind);
1243 /* needed for iteration of constraints */
1244 snew(ekind_save,1);
1245 init_ekindata(fplog,top_global,&(ir->opts),ekind_save);
1246 /* Copy the cos acceleration to the groups struct */
1247 ekind->cosacc.cos_accel = ir->cos_accel;
1249 gstat = global_stat_init(ir);
1250 debug_gmx();
1252 /* Check for polarizable models and flexible constraints */
1253 shellfc = init_shell_flexcon(fplog,
1254 top_global,n_flexible_constraints(constr),
1255 (ir->bContinuation ||
1256 (DOMAINDECOMP(cr) && !MASTER(cr))) ?
1257 NULL : state_global->x);
1259 if (DEFORM(*ir))
1261 #ifdef GMX_THREADS
1262 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
1263 #endif
1264 set_deform_reference_box(upd,
1265 deform_init_init_step_tpx,
1266 deform_init_box_tpx);
1267 #ifdef GMX_THREADS
1268 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
1269 #endif
1273 double io = compute_io(ir,top_global->natoms,groups,mdebin->ebin->nener,1);
1274 if ((io > 2000) && MASTER(cr))
1275 fprintf(stderr,
1276 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
1277 io);
1280 if (DOMAINDECOMP(cr)) {
1281 top = dd_init_local_top(top_global);
1283 snew(state,1);
1284 dd_init_local_state(cr->dd,state_global,state);
1286 if (DDMASTER(cr->dd) && ir->nstfout) {
1287 snew(f_global,state_global->natoms);
1289 } else {
1290 if (PAR(cr)) {
1291 /* Initialize the particle decomposition and split the topology */
1292 top = split_system(fplog,top_global,ir,cr);
1294 pd_cg_range(cr,&fr->cg0,&fr->hcg);
1295 pd_at_range(cr,&a0,&a1);
1296 } else {
1297 top = gmx_mtop_generate_local_top(top_global,ir);
1299 a0 = 0;
1300 a1 = top_global->natoms;
1303 state = partdec_init_local_state(cr,state_global);
1304 f_global = f;
1306 atoms2md(top_global,ir,0,NULL,a0,a1-a0,mdatoms);
1308 if (vsite) {
1309 set_vsite_top(vsite,top,mdatoms,cr);
1312 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols) {
1313 graph = mk_graph(fplog,&(top->idef),0,top_global->natoms,FALSE,FALSE);
1316 if (shellfc) {
1317 make_local_shells(cr,mdatoms,shellfc);
1320 if (ir->pull && PAR(cr)) {
1321 dd_make_local_pull_groups(NULL,ir->pull,mdatoms);
1325 if (DOMAINDECOMP(cr))
1327 /* Distribute the charge groups over the nodes from the master node */
1328 dd_partition_system(fplog,ir->init_step,cr,TRUE,1,
1329 state_global,top_global,ir,
1330 state,&f,mdatoms,top,fr,
1331 vsite,shellfc,constr,
1332 nrnb,wcycle,FALSE);
1335 update_mdatoms(mdatoms,state->lambda);
1337 if (MASTER(cr))
1339 if (opt2bSet("-cpi",nfile,fnm))
1341 /* Update mdebin with energy history if appending to output files */
1342 if ( Flags & MD_APPENDFILES )
1344 restore_energyhistory_from_state(mdebin,&state_global->enerhist);
1346 else
1348 /* We might have read an energy history from checkpoint,
1349 * free the allocated memory and reset the counts.
1351 done_energyhistory(&state_global->enerhist);
1352 init_energyhistory(&state_global->enerhist);
1355 /* Set the initial energy history in state by updating once */
1356 update_energyhistory(&state_global->enerhist,mdebin);
1359 if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG)) {
1360 /* Set the random state if we read a checkpoint file */
1361 set_stochd_state(upd,state);
1364 /* Initialize constraints */
1365 if (constr) {
1366 if (!DOMAINDECOMP(cr))
1367 set_constraints(constr,top,ir,mdatoms,cr);
1370 /* Check whether we have to GCT stuff */
1371 bTCR = ftp2bSet(efGCT,nfile,fnm);
1372 if (bTCR) {
1373 if (MASTER(cr)) {
1374 fprintf(stderr,"Will do General Coupling Theory!\n");
1376 gnx = top_global->mols.nr;
1377 snew(grpindex,gnx);
1378 for(i=0; (i<gnx); i++) {
1379 grpindex[i] = i;
1383 if (repl_ex_nst > 0 && MASTER(cr))
1384 repl_ex = init_replica_exchange(fplog,cr->ms,state_global,ir,
1385 repl_ex_nst,repl_ex_seed);
1387 if (!ir->bContinuation && !bRerunMD)
1389 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
1391 /* Set the velocities of frozen particles to zero */
1392 for(i=mdatoms->start; i<mdatoms->start+mdatoms->homenr; i++)
1394 for(m=0; m<DIM; m++)
1396 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
1398 state->v[i][m] = 0;
1404 if (constr)
1406 /* Constrain the initial coordinates and velocities */
1407 do_constrain_first(fplog,constr,ir,mdatoms,state,f,
1408 graph,cr,nrnb,fr,top,shake_vir);
1410 if (vsite)
1412 /* Construct the virtual sites for the initial configuration */
1413 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,NULL,
1414 top->idef.iparams,top->idef.il,
1415 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1419 debug_gmx();
1421 /* I'm assuming we need global communication the first time! MRS */
1422 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
1423 | (bVV ? CGLO_PRESSURE:0)
1424 | (bVV ? CGLO_CONSTRAINT:0)
1425 | (bRerunMD ? CGLO_RERUNMD:0)
1426 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN:0));
1428 bSumEkinhOld = FALSE;
1429 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1430 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1431 constr,NULL,FALSE,state->box,
1432 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,cglo_flags);
1433 if (ir->eI == eiVVAK) {
1434 /* a second call to get the half step temperature initialized as well */
1435 /* we do the same call as above, but turn the pressure off -- internally to
1436 compute_globals, this is recognized as a velocity verlet half-step
1437 kinetic energy calculation. This minimized excess variables, but
1438 perhaps loses some logic?*/
1440 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1441 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1442 constr,NULL,FALSE,state->box,
1443 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1444 cglo_flags &~ CGLO_PRESSURE);
1447 /* Calculate the initial half step temperature, and save the ekinh_old */
1448 if (!(Flags & MD_STARTFROMCPT))
1450 for(i=0; (i<ir->opts.ngtc); i++)
1452 copy_mat(ekind->tcstat[i].ekinh,ekind->tcstat[i].ekinh_old);
1455 if (ir->eI != eiVV)
1457 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
1458 and there is no previous step */
1460 temp0 = enerd->term[F_TEMP];
1462 /* if using an iterative algorithm, we need to create a working directory for the state. */
1463 if (bIterations)
1465 bufstate = init_bufstate(state);
1467 if (bFFscan)
1469 snew(xcopy,state->natoms);
1470 snew(vcopy,state->natoms);
1471 copy_rvecn(state->x,xcopy,0,state->natoms);
1472 copy_rvecn(state->v,vcopy,0,state->natoms);
1473 copy_mat(state->box,boxcopy);
1476 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
1477 temperature control */
1478 trotter_seq = init_npt_vars(ir,state,&MassQ,bTrotter);
1480 if (MASTER(cr))
1482 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
1484 fprintf(fplog,
1485 "RMS relative constraint deviation after constraining: %.2e\n",
1486 constr_rmsd(constr,FALSE));
1488 fprintf(fplog,"Initial temperature: %g K\n",enerd->term[F_TEMP]);
1489 if (bRerunMD)
1491 fprintf(stderr,"starting md rerun '%s', reading coordinates from"
1492 " input trajectory '%s'\n\n",
1493 *(top_global->name),opt2fn("-rerun",nfile,fnm));
1494 if (bVerbose)
1496 fprintf(stderr,"Calculated time to finish depends on nsteps from "
1497 "run input file,\nwhich may not correspond to the time "
1498 "needed to process input trajectory.\n\n");
1501 else
1503 char tbuf[20];
1504 fprintf(stderr,"starting mdrun '%s'\n",
1505 *(top_global->name));
1506 if (ir->nsteps >= 0)
1508 sprintf(tbuf,"%8.1f",(ir->init_step+ir->nsteps)*ir->delta_t);
1510 else
1512 sprintf(tbuf,"%s","infinite");
1514 if (ir->init_step > 0)
1516 fprintf(stderr,"%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
1517 gmx_step_str(ir->init_step+ir->nsteps,sbuf),tbuf,
1518 gmx_step_str(ir->init_step,sbuf2),
1519 ir->init_step*ir->delta_t);
1521 else
1523 fprintf(stderr,"%s steps, %s ps.\n",
1524 gmx_step_str(ir->nsteps,sbuf),tbuf);
1527 fprintf(fplog,"\n");
1530 /* Set and write start time */
1531 runtime_start(runtime);
1532 print_date_and_time(fplog,cr->nodeid,"Started mdrun",runtime);
1533 wallcycle_start(wcycle,ewcRUN);
1534 if (fplog)
1535 fprintf(fplog,"\n");
1537 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
1538 #ifdef GMX_FAHCORE
1539 chkpt_ret=fcCheckPointParallel( cr->nodeid,
1540 NULL,0);
1541 if ( chkpt_ret == 0 )
1542 gmx_fatal( 3,__FILE__,__LINE__, "Checkpoint error on step %d\n", 0 );
1543 #endif
1545 debug_gmx();
1546 /***********************************************************
1548 * Loop over MD steps
1550 ************************************************************/
1552 /* if rerunMD then read coordinates and velocities from input trajectory */
1553 if (bRerunMD)
1555 if (getenv("GMX_FORCE_UPDATE"))
1557 bForceUpdate = TRUE;
1560 rerun_fr.natoms = 0;
1561 if (MASTER(cr))
1563 bNotLastFrame = read_first_frame(oenv,&status,
1564 opt2fn("-rerun",nfile,fnm),
1565 &rerun_fr,TRX_NEED_X | TRX_READ_V);
1566 if (rerun_fr.natoms != top_global->natoms)
1568 gmx_fatal(FARGS,
1569 "Number of atoms in trajectory (%d) does not match the "
1570 "run input file (%d)\n",
1571 rerun_fr.natoms,top_global->natoms);
1573 if (ir->ePBC != epbcNONE)
1575 if (!rerun_fr.bBox)
1577 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);
1579 if (max_cutoff2(ir->ePBC,rerun_fr.box) < sqr(fr->rlistlong))
1581 gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f has too small box dimensions",rerun_fr.step,rerun_fr.time);
1586 if (PAR(cr))
1588 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
1591 if (ir->ePBC != epbcNONE)
1593 /* Set the shift vectors.
1594 * Necessary here when have a static box different from the tpr box.
1596 calc_shifts(rerun_fr.box,fr->shift_vec);
1600 /* loop over MD steps or if rerunMD to end of input trajectory */
1601 bFirstStep = TRUE;
1602 /* Skip the first Nose-Hoover integration when we get the state from tpx */
1603 bStateFromTPX = !opt2bSet("-cpi",nfile,fnm);
1604 bInitStep = bFirstStep && (bStateFromTPX || bVV);
1605 bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
1606 bLastStep = FALSE;
1607 bSumEkinhOld = FALSE;
1608 bExchanged = FALSE;
1610 init_global_signals(&gs,cr,ir,repl_ex_nst);
1612 step = ir->init_step;
1613 step_rel = 0;
1615 if (ir->nstlist == -1)
1617 init_nlistheuristics(&nlh,bGStatEveryStep,step);
1620 bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps));
1621 while (!bLastStep || (bRerunMD && bNotLastFrame)) {
1623 wallcycle_start(wcycle,ewcSTEP);
1625 GMX_MPE_LOG(ev_timestep1);
1627 if (bRerunMD) {
1628 if (rerun_fr.bStep) {
1629 step = rerun_fr.step;
1630 step_rel = step - ir->init_step;
1632 if (rerun_fr.bTime) {
1633 t = rerun_fr.time;
1635 else
1637 t = step;
1640 else
1642 bLastStep = (step_rel == ir->nsteps);
1643 t = t0 + step*ir->delta_t;
1646 if (ir->efep != efepNO)
1648 if (bRerunMD && rerun_fr.bLambda && (ir->delta_lambda!=0))
1650 state_global->lambda = rerun_fr.lambda;
1652 else
1654 state_global->lambda = lam0 + step*ir->delta_lambda;
1656 state->lambda = state_global->lambda;
1657 bDoDHDL = do_per_step(step,ir->nstdhdl);
1660 if (bSimAnn)
1662 update_annealing_target_temp(&(ir->opts),t);
1665 if (bRerunMD)
1667 if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
1669 for(i=0; i<state_global->natoms; i++)
1671 copy_rvec(rerun_fr.x[i],state_global->x[i]);
1673 if (rerun_fr.bV)
1675 for(i=0; i<state_global->natoms; i++)
1677 copy_rvec(rerun_fr.v[i],state_global->v[i]);
1680 else
1682 for(i=0; i<state_global->natoms; i++)
1684 clear_rvec(state_global->v[i]);
1686 if (bRerunWarnNoV)
1688 fprintf(stderr,"\nWARNING: Some frames do not contain velocities.\n"
1689 " Ekin, temperature and pressure are incorrect,\n"
1690 " the virial will be incorrect when constraints are present.\n"
1691 "\n");
1692 bRerunWarnNoV = FALSE;
1696 copy_mat(rerun_fr.box,state_global->box);
1697 copy_mat(state_global->box,state->box);
1699 if (vsite && (Flags & MD_RERUN_VSITE))
1701 if (DOMAINDECOMP(cr))
1703 gmx_fatal(FARGS,"Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
1705 if (graph)
1707 /* Following is necessary because the graph may get out of sync
1708 * with the coordinates if we only have every N'th coordinate set
1710 mk_mshift(fplog,graph,fr->ePBC,state->box,state->x);
1711 shift_self(graph,state->box,state->x);
1713 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
1714 top->idef.iparams,top->idef.il,
1715 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1716 if (graph)
1718 unshift_self(graph,state->box,state->x);
1723 /* Stop Center of Mass motion */
1724 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step,ir->nstcomm));
1726 /* Copy back starting coordinates in case we're doing a forcefield scan */
1727 if (bFFscan)
1729 for(ii=0; (ii<state->natoms); ii++)
1731 copy_rvec(xcopy[ii],state->x[ii]);
1732 copy_rvec(vcopy[ii],state->v[ii]);
1734 copy_mat(boxcopy,state->box);
1737 if (bRerunMD)
1739 /* for rerun MD always do Neighbour Searching */
1740 bNS = (bFirstStep || ir->nstlist != 0);
1741 bNStList = bNS;
1743 else
1745 /* Determine whether or not to do Neighbour Searching and LR */
1746 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
1748 bNS = (bFirstStep || bExchanged || bNStList ||
1749 (ir->nstlist == -1 && nlh.nabnsb > 0));
1751 if (bNS && ir->nstlist == -1)
1753 set_nlistheuristics(&nlh,bFirstStep || bExchanged,step);
1757 /* < 0 means stop at next step, > 0 means stop at next NS step */
1758 if ( (gs.set[eglsSTOPCOND] < 0 ) ||
1759 ( (gs.set[eglsSTOPCOND] > 0 ) && ( bNS || ir->nstlist==0)) )
1761 bLastStep = TRUE;
1764 /* Determine whether or not to update the Born radii if doing GB */
1765 bBornRadii=bFirstStep;
1766 if (ir->implicit_solvent && (step % ir->nstgbradii==0))
1768 bBornRadii=TRUE;
1771 do_log = do_per_step(step,ir->nstlog) || bFirstStep || bLastStep;
1772 do_verbose = bVerbose &&
1773 (step % stepout == 0 || bFirstStep || bLastStep);
1775 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
1777 if (bRerunMD)
1779 bMasterState = TRUE;
1781 else
1783 bMasterState = FALSE;
1784 /* Correct the new box if it is too skewed */
1785 if (DYNAMIC_BOX(*ir))
1787 if (correct_box(fplog,step,state->box,graph))
1789 bMasterState = TRUE;
1792 if (DOMAINDECOMP(cr) && bMasterState)
1794 dd_collect_state(cr->dd,state,state_global);
1798 if (DOMAINDECOMP(cr))
1800 /* Repartition the domain decomposition */
1801 wallcycle_start(wcycle,ewcDOMDEC);
1802 dd_partition_system(fplog,step,cr,
1803 bMasterState,nstglobalcomm,
1804 state_global,top_global,ir,
1805 state,&f,mdatoms,top,fr,
1806 vsite,shellfc,constr,
1807 nrnb,wcycle,do_verbose);
1808 wallcycle_stop(wcycle,ewcDOMDEC);
1809 /* If using an iterative integrator, reallocate space to match the decomposition */
1813 if (MASTER(cr) && do_log && !bFFscan)
1815 print_ebin_header(fplog,step,t,state->lambda);
1818 if (ir->efep != efepNO)
1820 update_mdatoms(mdatoms,state->lambda);
1823 if (bRerunMD && rerun_fr.bV)
1826 /* We need the kinetic energy at minus the half step for determining
1827 * the full step kinetic energy and possibly for T-coupling.*/
1828 /* This may not be quite working correctly yet . . . . */
1829 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1830 wcycle,enerd,NULL,NULL,NULL,NULL,mu_tot,
1831 constr,NULL,FALSE,state->box,
1832 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1833 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1835 clear_mat(force_vir);
1837 /* Ionize the atoms if necessary */
1838 if (bIonize)
1840 ionize(fplog,oenv,mdatoms,top_global,t,ir,state->x,state->v,
1841 mdatoms->start,mdatoms->start+mdatoms->homenr,state->box,cr);
1844 /* Update force field in ffscan program */
1845 if (bFFscan)
1847 if (update_forcefield(fplog,
1848 nfile,fnm,fr,
1849 mdatoms->nr,state->x,state->box)) {
1850 if (gmx_parallel_env_initialized())
1852 gmx_finalize();
1854 exit(0);
1858 GMX_MPE_LOG(ev_timestep2);
1860 /* We write a checkpoint at this MD step when:
1861 * either at an NS step when we signalled through gs,
1862 * or at the last step (but not when we do not want confout),
1863 * but never at the first step or with rerun.
1865 bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
1866 (bLastStep && (Flags & MD_CONFOUT))) &&
1867 step > ir->init_step && !bRerunMD);
1868 if (bCPT)
1870 gs.set[eglsCHKPT] = 0;
1873 /* Determine the energy and pressure:
1874 * at nstcalcenergy steps and at energy output steps (set below).
1876 bNstEner = do_per_step(step,ir->nstcalcenergy);
1877 bCalcEnerPres =
1878 (bNstEner ||
1879 (ir->epc != epcNO && do_per_step(step,ir->nstpcouple)));
1881 /* Do we need global communication ? */
1882 bGStat = (bCalcEnerPres || bStopCM ||
1883 do_per_step(step,nstglobalcomm) ||
1884 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
1886 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
1888 if (do_ene || do_log)
1890 bCalcEnerPres = TRUE;
1891 bGStat = TRUE;
1894 /* these CGLO_ options remain the same throughout the iteration */
1895 cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
1896 (bStopCM ? CGLO_STOPCM : 0) |
1897 (bGStat ? CGLO_GSTAT : 0)
1900 force_flags = (GMX_FORCE_STATECHANGED |
1901 ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1902 GMX_FORCE_ALLFORCES |
1903 (bNStList ? GMX_FORCE_DOLR : 0) |
1904 GMX_FORCE_SEPLRF |
1905 (bCalcEnerPres ? GMX_FORCE_VIRIAL : 0) |
1906 (bDoDHDL ? GMX_FORCE_DHDL : 0)
1909 if (shellfc)
1911 /* Now is the time to relax the shells */
1912 count=relax_shell_flexcon(fplog,cr,bVerbose,bFFscan ? step+1 : step,
1913 ir,bNS,force_flags,
1914 bStopCM,top,top_global,
1915 constr,enerd,fcd,
1916 state,f,force_vir,mdatoms,
1917 nrnb,wcycle,graph,groups,
1918 shellfc,fr,bBornRadii,t,mu_tot,
1919 state->natoms,&bConverged,vsite,
1920 outf->fp_field);
1921 tcount+=count;
1923 if (bConverged)
1925 nconverged++;
1928 else
1930 /* The coordinates (x) are shifted (to get whole molecules)
1931 * in do_force.
1932 * This is parallellized as well, and does communication too.
1933 * Check comments in sim_util.c
1936 do_force(fplog,cr,ir,step,nrnb,wcycle,top,top_global,groups,
1937 state->box,state->x,&state->hist,
1938 f,force_vir,mdatoms,enerd,fcd,
1939 state->lambda,graph,
1940 fr,vsite,mu_tot,t,outf->fp_field,ed,bBornRadii,
1941 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1944 GMX_BARRIER(cr->mpi_comm_mygroup);
1946 if (bTCR)
1948 mu_aver = calc_mu_aver(cr,state->x,mdatoms->chargeA,
1949 mu_tot,&top_global->mols,mdatoms,gnx,grpindex);
1952 if (bTCR && bFirstStep)
1954 tcr=init_coupling(fplog,nfile,fnm,cr,fr,mdatoms,&(top->idef));
1955 fprintf(fplog,"Done init_coupling\n");
1956 fflush(fplog);
1959 if (bVV && !bStartingFromCpt && !bRerunMD)
1960 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1962 if (ir->eI==eiVV && bInitStep)
1964 /* if using velocity verlet with full time step Ekin,
1965 * take the first half step only to compute the
1966 * virial for the first step. From there,
1967 * revert back to the initial coordinates
1968 * so that the input is actually the initial step.
1970 copy_rvecn(state->v,cbuf,0,state->natoms); /* should make this better for parallelizing? */
1971 } else {
1972 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1973 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ1);
1976 update_coords(fplog,step,ir,mdatoms,state,
1977 f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1978 ekind,M,wcycle,upd,bInitStep,etrtVELOCITY1,
1979 cr,nrnb,constr,&top->idef);
1981 if (bIterations)
1983 gmx_iterate_init(&iterate,bIterations && !bInitStep);
1985 /* for iterations, we save these vectors, as we will be self-consistently iterating
1986 the calculations */
1988 /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1990 /* save the state */
1991 if (bIterations && iterate.bIterate) {
1992 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1995 bFirstIterate = TRUE;
1996 while (bFirstIterate || (bIterations && iterate.bIterate))
1998 if (bIterations && iterate.bIterate)
2000 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
2001 if (bFirstIterate && bTrotter)
2003 /* The first time through, we need a decent first estimate
2004 of veta(t+dt) to compute the constraints. Do
2005 this by computing the box volume part of the
2006 trotter integration at this time. Nothing else
2007 should be changed by this routine here. If
2008 !(first time), we start with the previous value
2009 of veta. */
2011 veta_save = state->veta;
2012 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ0);
2013 vetanew = state->veta;
2014 state->veta = veta_save;
2018 bOK = TRUE;
2019 if ( !bRerunMD || rerun_fr.bV || bForceUpdate) { /* Why is rerun_fr.bV here? Unclear. */
2020 dvdl = 0;
2022 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2023 &top->idef,shake_vir,NULL,
2024 cr,nrnb,wcycle,upd,constr,
2025 bInitStep,TRUE,bCalcEnerPres,vetanew);
2027 if (!bOK && !bFFscan)
2029 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2033 else if (graph)
2034 { /* Need to unshift here if a do_force has been
2035 called in the previous step */
2036 unshift_self(graph,state->box,state->x);
2040 /* if VV, compute the pressure and constraints */
2041 /* For VV2, we strictly only need this if using pressure
2042 * control, but we really would like to have accurate pressures
2043 * printed out.
2044 * Think about ways around this in the future?
2045 * For now, keep this choice in comments.
2047 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
2048 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
2049 bPres = TRUE;
2050 bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK));
2051 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2052 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2053 constr,NULL,FALSE,state->box,
2054 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2055 cglo_flags
2056 | CGLO_ENERGY
2057 | (bTemp ? CGLO_TEMPERATURE:0)
2058 | (bPres ? CGLO_PRESSURE : 0)
2059 | (bPres ? CGLO_CONSTRAINT : 0)
2060 | ((bIterations && iterate.bIterate) ? CGLO_ITERATE : 0)
2061 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
2062 | CGLO_SCALEEKIN
2064 /* explanation of above:
2065 a) We compute Ekin at the full time step
2066 if 1) we are using the AveVel Ekin, and it's not the
2067 initial step, or 2) if we are using AveEkin, but need the full
2068 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
2069 b) If we are using EkinAveEkin for the kinetic energy for the temperture control, we still feed in
2070 EkinAveVel because it's needed for the pressure */
2072 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
2073 if (!bInitStep)
2075 if (bTrotter)
2077 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ2);
2079 else
2081 update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
2085 if (bIterations &&
2086 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
2087 state->veta,&vetanew))
2089 break;
2091 bFirstIterate = FALSE;
2094 if (bTrotter && !bInitStep) {
2095 copy_mat(shake_vir,state->svir_prev);
2096 copy_mat(force_vir,state->fvir_prev);
2097 if (IR_NVT_TROTTER(ir) && ir->eI==eiVV) {
2098 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
2099 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,NULL,(ir->eI==eiVV),FALSE,FALSE);
2100 enerd->term[F_EKIN] = trace(ekind->ekin);
2103 /* if it's the initial step, we performed this first step just to get the constraint virial */
2104 if (bInitStep && ir->eI==eiVV) {
2105 copy_rvecn(cbuf,state->v,0,state->natoms);
2108 if (fr->bSepDVDL && fplog && do_log)
2110 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2112 enerd->term[F_DHDL_CON] += dvdl;
2114 GMX_MPE_LOG(ev_timestep1);
2117 /* MRS -- now done iterating -- compute the conserved quantity */
2118 if (bVV) {
2119 saved_conserved_quantity = compute_conserved_from_auxiliary(ir,state,&MassQ);
2120 if (ir->eI==eiVV)
2122 last_ekin = enerd->term[F_EKIN]; /* does this get preserved through checkpointing? */
2124 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
2126 saved_conserved_quantity -= enerd->term[F_DISPCORR];
2130 /* ######## END FIRST UPDATE STEP ############## */
2131 /* ######## If doing VV, we now have v(dt) ###### */
2133 /* ################## START TRAJECTORY OUTPUT ################# */
2135 /* Now we have the energies and forces corresponding to the
2136 * coordinates at time t. We must output all of this before
2137 * the update.
2138 * for RerunMD t is read from input trajectory
2140 GMX_MPE_LOG(ev_output_start);
2142 mdof_flags = 0;
2143 if (do_per_step(step,ir->nstxout)) { mdof_flags |= MDOF_X; }
2144 if (do_per_step(step,ir->nstvout)) { mdof_flags |= MDOF_V; }
2145 if (do_per_step(step,ir->nstfout)) { mdof_flags |= MDOF_F; }
2146 if (do_per_step(step,ir->nstxtcout)) { mdof_flags |= MDOF_XTC; }
2147 if (bCPT) { mdof_flags |= MDOF_CPT; };
2149 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
2150 if (bLastStep)
2152 /* Enforce writing positions and velocities at end of run */
2153 mdof_flags |= (MDOF_X | MDOF_V);
2155 #endif
2156 #ifdef GMX_FAHCORE
2157 if (MASTER(cr))
2158 fcReportProgress( ir->nsteps, step );
2160 /* sync bCPT and fc record-keeping */
2161 if (bCPT && MASTER(cr))
2162 fcRequestCheckPoint();
2163 #endif
2165 if (mdof_flags != 0)
2167 wallcycle_start(wcycle,ewcTRAJ);
2168 if (bCPT)
2170 if (state->flags & (1<<estLD_RNG))
2172 get_stochd_state(upd,state);
2174 if (MASTER(cr))
2176 if (bSumEkinhOld)
2178 state_global->ekinstate.bUpToDate = FALSE;
2180 else
2182 update_ekinstate(&state_global->ekinstate,ekind);
2183 state_global->ekinstate.bUpToDate = TRUE;
2185 update_energyhistory(&state_global->enerhist,mdebin);
2188 write_traj(fplog,cr,outf,mdof_flags,top_global,
2189 step,t,state,state_global,f,f_global,&n_xtc,&x_xtc);
2190 if (bCPT)
2192 nchkpt++;
2193 bCPT = FALSE;
2195 debug_gmx();
2196 if (bLastStep && step_rel == ir->nsteps &&
2197 (Flags & MD_CONFOUT) && MASTER(cr) &&
2198 !bRerunMD && !bFFscan)
2200 /* x and v have been collected in write_traj,
2201 * because a checkpoint file will always be written
2202 * at the last step.
2204 fprintf(stderr,"\nWriting final coordinates.\n");
2205 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols &&
2206 DOMAINDECOMP(cr))
2208 /* Make molecules whole only for confout writing */
2209 do_pbc_mtop(fplog,ir->ePBC,state->box,top_global,state_global->x);
2211 write_sto_conf_mtop(ftp2fn(efSTO,nfile,fnm),
2212 *top_global->name,top_global,
2213 state_global->x,state_global->v,
2214 ir->ePBC,state->box);
2215 debug_gmx();
2217 wallcycle_stop(wcycle,ewcTRAJ);
2219 GMX_MPE_LOG(ev_output_finish);
2221 /* kludge -- virial is lost with restart for NPT control. Must restart */
2222 if (bStartingFromCpt && bVV)
2224 copy_mat(state->svir_prev,shake_vir);
2225 copy_mat(state->fvir_prev,force_vir);
2227 /* ################## END TRAJECTORY OUTPUT ################ */
2229 /* Determine the pressure:
2230 * always when we want exact averages in the energy file,
2231 * at ns steps when we have pressure coupling,
2232 * otherwise only at energy output steps (set below).
2235 bNstEner = (bGStatEveryStep || do_per_step(step,ir->nstcalcenergy));
2236 bCalcEnerPres = bNstEner;
2238 /* Do we need global communication ? */
2239 bGStat = (bGStatEveryStep || bStopCM || bNS ||
2240 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
2242 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
2244 if (do_ene || do_log)
2246 bCalcEnerPres = TRUE;
2247 bGStat = TRUE;
2250 /* Determine the wallclock run time up till now */
2251 run_time = gmx_gettime() - (double)runtime->real;
2253 /* Check whether everything is still allright */
2254 if (((int)gmx_get_stop_condition() > handled_stop_condition)
2255 #ifdef GMX_THREADS
2256 && MASTER(cr)
2257 #endif
2260 /* this is just make gs.sig compatible with the hack
2261 of sending signals around by MPI_Reduce with together with
2262 other floats */
2263 if ( gmx_get_stop_condition() == gmx_stop_cond_next_ns )
2264 gs.sig[eglsSTOPCOND]=1;
2265 if ( gmx_get_stop_condition() == gmx_stop_cond_next )
2266 gs.sig[eglsSTOPCOND]=-1;
2267 /* < 0 means stop at next step, > 0 means stop at next NS step */
2268 if (fplog)
2270 fprintf(fplog,
2271 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2272 gmx_get_signal_name(),
2273 gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
2274 fflush(fplog);
2276 fprintf(stderr,
2277 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2278 gmx_get_signal_name(),
2279 gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
2280 fflush(stderr);
2281 handled_stop_condition=(int)gmx_get_stop_condition();
2283 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
2284 (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
2285 gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
2287 /* Signal to terminate the run */
2288 gs.sig[eglsSTOPCOND] = 1;
2289 if (fplog)
2291 fprintf(fplog,"\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2293 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2296 if (bResetCountersHalfMaxH && MASTER(cr) &&
2297 run_time > max_hours*60.0*60.0*0.495)
2299 gs.sig[eglsRESETCOUNTERS] = 1;
2302 if (ir->nstlist == -1 && !bRerunMD)
2304 /* When bGStatEveryStep=FALSE, global_stat is only called
2305 * when we check the atom displacements, not at NS steps.
2306 * This means that also the bonded interaction count check is not
2307 * performed immediately after NS. Therefore a few MD steps could
2308 * be performed with missing interactions.
2309 * But wrong energies are never written to file,
2310 * since energies are only written after global_stat
2311 * has been called.
2313 if (step >= nlh.step_nscheck)
2315 nlh.nabnsb = natoms_beyond_ns_buffer(ir,fr,&top->cgs,
2316 nlh.scale_tot,state->x);
2318 else
2320 /* This is not necessarily true,
2321 * but step_nscheck is determined quite conservatively.
2323 nlh.nabnsb = 0;
2327 /* In parallel we only have to check for checkpointing in steps
2328 * where we do global communication,
2329 * otherwise the other nodes don't know.
2331 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
2332 cpt_period >= 0 &&
2333 (cpt_period == 0 ||
2334 run_time >= nchkpt*cpt_period*60.0)) &&
2335 gs.set[eglsCHKPT] == 0)
2337 gs.sig[eglsCHKPT] = 1;
2340 if (bIterations)
2342 gmx_iterate_init(&iterate,bIterations);
2345 /* for iterations, we save these vectors, as we will be redoing the calculations */
2346 if (bIterations && iterate.bIterate)
2348 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
2350 bFirstIterate = TRUE;
2351 while (bFirstIterate || (bIterations && iterate.bIterate))
2353 /* We now restore these vectors to redo the calculation with improved extended variables */
2354 if (bIterations)
2356 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
2359 /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
2360 so scroll down for that logic */
2362 /* ######### START SECOND UPDATE STEP ################# */
2363 GMX_MPE_LOG(ev_update_start);
2364 /* Box is changed in update() when we do pressure coupling,
2365 * but we should still use the old box for energy corrections and when
2366 * writing it to the energy file, so it matches the trajectory files for
2367 * the same timestep above. Make a copy in a separate array.
2369 copy_mat(state->box,lastbox);
2371 bOK = TRUE;
2372 if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
2374 wallcycle_start(wcycle,ewcUPDATE);
2375 dvdl = 0;
2376 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
2377 if (bTrotter)
2379 if (bIterations && iterate.bIterate)
2381 if (bFirstIterate)
2383 scalevir = 1;
2385 else
2387 /* we use a new value of scalevir to converge the iterations faster */
2388 scalevir = tracevir/trace(shake_vir);
2390 msmul(shake_vir,scalevir,shake_vir);
2391 m_add(force_vir,shake_vir,total_vir);
2392 clear_mat(shake_vir);
2394 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ3);
2395 /* We can only do Berendsen coupling after we have summed
2396 * the kinetic energy or virial. Since the happens
2397 * in global_state after update, we should only do it at
2398 * step % nstlist = 1 with bGStatEveryStep=FALSE.
2401 else
2403 update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
2404 update_pcouple(fplog,step,ir,state,pcoupl_mu,M,wcycle,
2405 upd,bInitStep);
2408 if (bVV)
2410 /* velocity half-step update */
2411 update_coords(fplog,step,ir,mdatoms,state,f,
2412 fr->bTwinRange && bNStList,fr->f_twin,fcd,
2413 ekind,M,wcycle,upd,FALSE,etrtVELOCITY2,
2414 cr,nrnb,constr,&top->idef);
2417 /* Above, initialize just copies ekinh into ekin,
2418 * it doesn't copy position (for VV),
2419 * and entire integrator for MD.
2422 if (ir->eI==eiVVAK)
2424 copy_rvecn(state->x,cbuf,0,state->natoms);
2427 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2428 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2429 wallcycle_stop(wcycle,ewcUPDATE);
2431 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2432 &top->idef,shake_vir,force_vir,
2433 cr,nrnb,wcycle,upd,constr,
2434 bInitStep,FALSE,bCalcEnerPres,state->veta);
2436 if (ir->eI==eiVVAK)
2438 /* erase F_EKIN and F_TEMP here? */
2439 /* just compute the kinetic energy at the half step to perform a trotter step */
2440 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2441 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2442 constr,NULL,FALSE,lastbox,
2443 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2444 cglo_flags | CGLO_TEMPERATURE
2446 wallcycle_start(wcycle,ewcUPDATE);
2447 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ4);
2448 /* now we know the scaling, we can compute the positions again again */
2449 copy_rvecn(cbuf,state->x,0,state->natoms);
2451 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2452 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2453 wallcycle_stop(wcycle,ewcUPDATE);
2455 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
2456 /* are the small terms in the shake_vir here due
2457 * to numerical errors, or are they important
2458 * physically? I'm thinking they are just errors, but not completely sure.
2459 * For now, will call without actually constraining, constr=NULL*/
2460 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2461 &top->idef,tmp_vir,force_vir,
2462 cr,nrnb,wcycle,upd,NULL,
2463 bInitStep,FALSE,bCalcEnerPres,
2464 state->veta);
2466 if (!bOK && !bFFscan)
2468 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2471 if (fr->bSepDVDL && fplog && do_log)
2473 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2475 enerd->term[F_DHDL_CON] += dvdl;
2477 else if (graph)
2479 /* Need to unshift here */
2480 unshift_self(graph,state->box,state->x);
2483 GMX_BARRIER(cr->mpi_comm_mygroup);
2484 GMX_MPE_LOG(ev_update_finish);
2486 if (vsite != NULL)
2488 wallcycle_start(wcycle,ewcVSITECONSTR);
2489 if (graph != NULL)
2491 shift_self(graph,state->box,state->x);
2493 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
2494 top->idef.iparams,top->idef.il,
2495 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
2497 if (graph != NULL)
2499 unshift_self(graph,state->box,state->x);
2501 wallcycle_stop(wcycle,ewcVSITECONSTR);
2504 /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
2505 if (ir->nstlist == -1 && bFirstIterate)
2507 gs.sig[eglsNABNSB] = nlh.nabnsb;
2509 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2510 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2511 constr,
2512 bFirstIterate ? &gs : NULL,(step % gs.nstms == 0),
2513 lastbox,
2514 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2515 cglo_flags
2516 | (!EI_VV(ir->eI) ? CGLO_ENERGY : 0)
2517 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
2518 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
2519 | (bIterations && iterate.bIterate ? CGLO_ITERATE : 0)
2520 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
2521 | CGLO_CONSTRAINT
2523 if (ir->nstlist == -1 && bFirstIterate)
2525 nlh.nabnsb = gs.set[eglsNABNSB];
2526 gs.set[eglsNABNSB] = 0;
2528 /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
2529 /* ############# END CALC EKIN AND PRESSURE ################# */
2531 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
2532 the virial that should probably be addressed eventually. state->veta has better properies,
2533 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
2534 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
2536 if (bIterations &&
2537 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
2538 trace(shake_vir),&tracevir))
2540 break;
2542 bFirstIterate = FALSE;
2545 update_box(fplog,step,ir,mdatoms,state,graph,f,
2546 ir->nstlist==-1 ? &nlh.scale_tot : NULL,pcoupl_mu,nrnb,wcycle,upd,bInitStep,FALSE);
2548 /* ################# END UPDATE STEP 2 ################# */
2549 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
2551 /* The coordinates (x) were unshifted in update */
2552 if (bFFscan && (shellfc==NULL || bConverged))
2554 if (print_forcefield(fplog,enerd->term,mdatoms->homenr,
2555 f,NULL,xcopy,
2556 &(top_global->mols),mdatoms->massT,pres))
2558 if (gmx_parallel_env_initialized())
2560 gmx_finalize();
2562 fprintf(stderr,"\n");
2563 exit(0);
2566 if (!bGStat)
2568 /* We will not sum ekinh_old,
2569 * so signal that we still have to do it.
2571 bSumEkinhOld = TRUE;
2574 if (bTCR)
2576 /* Only do GCT when the relaxation of shells (minimization) has converged,
2577 * otherwise we might be coupling to bogus energies.
2578 * In parallel we must always do this, because the other sims might
2579 * update the FF.
2582 /* Since this is called with the new coordinates state->x, I assume
2583 * we want the new box state->box too. / EL 20040121
2585 do_coupling(fplog,oenv,nfile,fnm,tcr,t,step,enerd->term,fr,
2586 ir,MASTER(cr),
2587 mdatoms,&(top->idef),mu_aver,
2588 top_global->mols.nr,cr,
2589 state->box,total_vir,pres,
2590 mu_tot,state->x,f,bConverged);
2591 debug_gmx();
2594 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
2596 /* sum up the foreign energy and dhdl terms */
2597 sum_dhdl(enerd,state->lambda,ir);
2599 /* use the directly determined last velocity, not actually the averaged half steps */
2600 if (bTrotter && ir->eI==eiVV)
2602 enerd->term[F_EKIN] = last_ekin;
2604 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
2606 if (bVV)
2608 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
2610 else
2612 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir,state,&MassQ);
2614 /* Check for excessively large energies */
2615 if (bIonize)
2617 #ifdef GMX_DOUBLE
2618 real etot_max = 1e200;
2619 #else
2620 real etot_max = 1e30;
2621 #endif
2622 if (fabs(enerd->term[F_ETOT]) > etot_max)
2624 fprintf(stderr,"Energy too large (%g), giving up\n",
2625 enerd->term[F_ETOT]);
2628 /* ######### END PREPARING EDR OUTPUT ########### */
2630 /* Time for performance */
2631 if (((step % stepout) == 0) || bLastStep)
2633 runtime_upd_proc(runtime);
2636 /* Output stuff */
2637 if (MASTER(cr))
2639 gmx_bool do_dr,do_or;
2641 if (!(bStartingFromCpt && (EI_VV(ir->eI))))
2643 if (bNstEner)
2645 upd_mdebin(mdebin,bDoDHDL, TRUE,
2646 t,mdatoms->tmass,enerd,state,lastbox,
2647 shake_vir,force_vir,total_vir,pres,
2648 ekind,mu_tot,constr);
2650 else
2652 upd_mdebin_step(mdebin);
2655 do_dr = do_per_step(step,ir->nstdisreout);
2656 do_or = do_per_step(step,ir->nstorireout);
2658 print_ebin(outf->fp_ene,do_ene,do_dr,do_or,do_log?fplog:NULL,
2659 step,t,
2660 eprNORMAL,bCompact,mdebin,fcd,groups,&(ir->opts));
2662 if (ir->ePull != epullNO)
2664 pull_print_output(ir->pull,step,t);
2667 if (do_per_step(step,ir->nstlog))
2669 if(fflush(fplog) != 0)
2671 gmx_fatal(FARGS,"Cannot flush logfile - maybe you are out of quota?");
2677 /* Remaining runtime */
2678 if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal() ))
2680 if (shellfc)
2682 fprintf(stderr,"\n");
2684 print_time(stderr,runtime,step,ir,cr);
2687 /* Replica exchange */
2688 bExchanged = FALSE;
2689 if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
2690 do_per_step(step,repl_ex_nst))
2692 bExchanged = replica_exchange(fplog,cr,repl_ex,
2693 state_global,enerd->term,
2694 state,step,t);
2696 if (bExchanged && DOMAINDECOMP(cr))
2698 dd_partition_system(fplog,step,cr,TRUE,1,
2699 state_global,top_global,ir,
2700 state,&f,mdatoms,top,fr,
2701 vsite,shellfc,constr,
2702 nrnb,wcycle,FALSE);
2706 bFirstStep = FALSE;
2707 bInitStep = FALSE;
2708 bStartingFromCpt = FALSE;
2710 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
2711 /* With all integrators, except VV, we need to retain the pressure
2712 * at the current step for coupling at the next step.
2714 if ((state->flags & (1<<estPRES_PREV)) &&
2715 (bGStatEveryStep ||
2716 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
2718 /* Store the pressure in t_state for pressure coupling
2719 * at the next MD step.
2721 copy_mat(pres,state->pres_prev);
2724 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
2726 if (bRerunMD)
2728 if (MASTER(cr))
2730 /* read next frame from input trajectory */
2731 bNotLastFrame = read_next_frame(oenv,status,&rerun_fr);
2734 if (PAR(cr))
2736 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
2740 if (!bRerunMD || !rerun_fr.bStep)
2742 /* increase the MD step number */
2743 step++;
2744 step_rel++;
2747 cycles = wallcycle_stop(wcycle,ewcSTEP);
2748 if (DOMAINDECOMP(cr) && wcycle)
2750 dd_cycles_add(cr->dd,cycles,ddCyclStep);
2753 if (step_rel == wcycle_get_reset_counters(wcycle) ||
2754 gs.set[eglsRESETCOUNTERS] != 0)
2756 /* Reset all the counters related to performance over the run */
2757 reset_all_counters(fplog,cr,step,&step_rel,ir,wcycle,nrnb,runtime);
2758 wcycle_set_reset_counters(wcycle,-1);
2759 /* Correct max_hours for the elapsed time */
2760 max_hours -= run_time/(60.0*60.0);
2761 bResetCountersHalfMaxH = FALSE;
2762 gs.set[eglsRESETCOUNTERS] = 0;
2765 /* End of main MD loop */
2766 debug_gmx();
2768 /* Stop the time */
2769 runtime_end(runtime);
2771 if (bRerunMD && MASTER(cr))
2773 close_trj(status);
2776 if (!(cr->duty & DUTY_PME))
2778 /* Tell the PME only node to finish */
2779 gmx_pme_finish(cr);
2782 if (MASTER(cr))
2784 if (ir->nstcalcenergy > 0 && !bRerunMD)
2786 print_ebin(outf->fp_ene,FALSE,FALSE,FALSE,fplog,step,t,
2787 eprAVER,FALSE,mdebin,fcd,groups,&(ir->opts));
2791 done_mdoutf(outf);
2793 debug_gmx();
2795 if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
2797 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)));
2798 fprintf(fplog,"Average number of atoms that crossed the half buffer length: %.1f\n\n",nlh.ab/nlh.nns);
2801 if (shellfc && fplog)
2803 fprintf(fplog,"Fraction of iterations that converged: %.2f %%\n",
2804 (nconverged*100.0)/step_rel);
2805 fprintf(fplog,"Average number of force evaluations per MD step: %.2f\n\n",
2806 tcount/step_rel);
2809 if (repl_ex_nst > 0 && MASTER(cr))
2811 print_replica_exchange_statistics(fplog,repl_ex);
2814 runtime->nsteps_done = step_rel;
2816 return 0;