Redefine the default boolean type to gmx_bool.
[alexxy/gromacs.git] / src / kernel / md.c
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  *
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.
15
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.
20  * 
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.
27  * 
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.
30  * 
31  * For more info, check our website at http://www.gromacs.org
32  * 
33  * And Hey:
34  * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
35  */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include <signal.h>
41 #include <stdlib.h>
42
43 #if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
44 /* _isnan() */
45 #include <float.h>
46 #endif
47
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
93 #ifdef GMX_LIB_MPI
94 #include <mpi.h>
95 #endif
96 #ifdef GMX_THREADS
97 #include "tmpi.h"
98 #endif
99
100 #ifdef GMX_FAHCORE
101 #include "corewrap.h"
102 #endif
103
104
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 };
113
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;
119
120
121 static int multisim_min(const gmx_multisim_t *ms,int nmin,int n)
122 {
123     int  *buf;
124     gmx_bool bPos,bEqual;
125     int  s,d;
126
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++)
133     {
134         bPos   = bPos   && (buf[s] > 0);
135         bEqual = bEqual && (buf[s] == buf[0]);
136     }
137     if (bPos)
138     {
139         if (bEqual)
140         {
141             nmin = min(nmin,buf[0]);
142         }
143         else
144         {
145             /* Find the least common multiple */
146             for(d=2; d<nmin; d++)
147             {
148                 s = 0;
149                 while (s < ms->nsim && d % buf[s] == 0)
150                 {
151                     s++;
152                 }
153                 if (s == ms->nsim)
154                 {
155                     /* We found the LCM and it is less than nmin */
156                     nmin = d;
157                     break;
158                 }
159             }
160         }
161     }
162     sfree(buf);
163
164     return nmin;
165 }
166
167 static int multisim_nstsimsync(const t_commrec *cr,
168                                const t_inputrec *ir,int repl_ex_nst)
169 {
170     int nmin;
171
172     if (MASTER(cr))
173     {
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)
179         {
180             gmx_fatal(FARGS,"Can not find an appropriate interval for inter-simulation communication, since nstlist, nstcalcenergy and -replex are all <= 0");
181         }
182         /* Avoid inter-simulation communication at every (second) step */
183         if (nmin <= 2)
184         {
185             nmin = 10;
186         }
187     }
188
189     gmx_bcast(sizeof(int),&nmin,cr);
190
191     return nmin;
192 }
193
194 static void init_global_signals(globsig_t *gs,const t_commrec *cr,
195                                 const t_inputrec *ir,int repl_ex_nst)
196 {
197     int i;
198
199     if (MULTISIM(cr))
200     {
201         gs->nstms = multisim_nstsimsync(cr,ir,repl_ex_nst);
202         if (debug)
203         {
204             fprintf(debug,"Syncing simulations for checkpointing and termination every %d steps\n",gs->nstms);
205         }
206     }
207     else
208     {
209         gs->nstms = 1;
210     }
211
212     for(i=0; i<eglsNR; i++)
213     {
214         gs->sig[i] = 0;
215         gs->set[i] = 0;
216     }
217 }
218
219 static void copy_coupling_state(t_state *statea,t_state *stateb, 
220                                 gmx_ekindata_t *ekinda,gmx_ekindata_t *ekindb, t_grpopts* opts) 
221 {
222     
223     /* MRS note -- might be able to get rid of some of the arguments.  Look over it when it's all debugged */
224     
225     int i,j,nc;
226
227     /* Make sure we have enough space for x and v */
228     if (statea->nalloc > stateb->nalloc)
229     {
230         stateb->nalloc = statea->nalloc;
231         srenew(stateb->x,stateb->nalloc);
232         srenew(stateb->v,stateb->nalloc);
233     }
234
235     stateb->natoms     = statea->natoms;
236     stateb->ngtc       = statea->ngtc;
237     stateb->nnhpres    = statea->nnhpres;
238     stateb->veta       = statea->veta;
239     if (ekinda) 
240     {
241         copy_mat(ekinda->ekin,ekindb->ekin);
242         for (i=0; i<stateb->ngtc; i++) 
243         {
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;
251         }
252     }
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);
258
259     for (i = 0; i<stateb->ngtc; i++) 
260     { 
261         nc = i*opts->nhchainlength;
262         for (j=0; j<opts->nhchainlength; j++) 
263         {
264             stateb->nosehoover_xi[nc+j]  = statea->nosehoover_xi[nc+j];
265             stateb->nosehoover_vxi[nc+j] = statea->nosehoover_vxi[nc+j];
266         }
267     }
268     if (stateb->nhpres_xi != NULL)
269     {
270         for (i = 0; i<stateb->nnhpres; i++) 
271         {
272             nc = i*opts->nhchainlength;
273             for (j=0; j<opts->nhchainlength; j++) 
274             {
275                 stateb->nhpres_xi[nc+j]  = statea->nhpres_xi[nc+j];
276                 stateb->nhpres_vxi[nc+j] = statea->nhpres_vxi[nc+j];
277             }
278         }
279     }
280 }
281
282 static real compute_conserved_from_auxiliary(t_inputrec *ir, t_state *state, t_extmass *MassQ)
283 {
284     real quantity = 0;
285     switch (ir->etc) 
286     {
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;
299     }
300     return quantity;
301 }
302
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)
312 {
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;
320     
321     /* translate CGLO flags to gmx_booleans */
322     bRerunMD = flags & CGLO_RERUNMD;
323     bStopCM = flags & CGLO_STOPCM;
324     bGStat = flags & CGLO_GSTAT;
325
326 /* FIX ME after 4.5 */
327 /* temporary hack because we are using gmx_bool (unsigned char) */
328
329     bReadEkin = (flags & CGLO_READEKIN) != 0;
330     bScaleEkin = (flags & CGLO_SCALEEKIN) != 0;
331     bEner = flags & CGLO_ENERGY;
332     bTemp = flags & CGLO_TEMPERATURE;
333     bPres  = (flags & CGLO_PRESSURE) != 0;
334     bConstrain = (flags & CGLO_CONSTRAINT) != 0;
335     bIterate = (flags & CGLO_ITERATE) != 0;
336     bFirstIterate = (flags & CGLO_FIRSTITERATE) != 0;
337
338     /* we calculate a full state kinetic energy either with full-step velocity verlet
339        or half step where we need the pressure */
340     
341     bEkinAveVel = (ir->eI==eiVV || (ir->eI==eiVVAK && bPres) || bReadEkin);
342     
343     /* in initalization, it sums the shake virial in vv, and to 
344        sums ekinh_old in leapfrog (or if we are calculating ekinh_old) for other reasons */
345
346     /* ########## Kinetic energy  ############## */
347     
348     if (bTemp) 
349     {
350         /* Non-equilibrium MD: this is parallellized, but only does communication
351          * when there really is NEMD.
352          */
353         
354         if (PAR(cr) && (ekind->bNEMD)) 
355         {
356             accumulate_u(cr,&(ir->opts),ekind);
357         }
358         debug_gmx();
359         if (bReadEkin)
360         {
361             restore_ekinstate_from_state(cr,ekind,&state_global->ekinstate);
362         }
363         else 
364         {
365
366             calc_ke_part(state,&(ir->opts),mdatoms,ekind,nrnb,bEkinAveVel,bIterate);
367         }
368         
369         debug_gmx();
370         
371         /* Calculate center of mass velocity if necessary, also parallellized */
372         if (bStopCM && !bRerunMD && bEner) 
373         {
374             calc_vcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms,
375                          state->x,state->v,vcm);
376         }
377     }
378
379     if (bTemp || bPres || bEner || bConstrain) 
380     {
381         if (!bGStat)
382         {
383             /* We will not sum ekinh_old,                                                            
384              * so signal that we still have to do it.                                                
385              */
386             *bSumEkinhOld = TRUE;
387
388         }
389         else
390         {
391             if (gs != NULL)
392             {
393                 for(i=0; i<eglsNR; i++)
394                 {
395                     gs_buf[i] = gs->sig[i];
396                 }
397             }
398             if (PAR(cr)) 
399             {
400                 wallcycle_start(wcycle,ewcMoveE);
401                 GMX_MPE_LOG(ev_global_stat_start);
402                 global_stat(fplog,gstat,cr,enerd,force_vir,shake_vir,mu_tot,
403                             ir,ekind,constr,vcm,
404                             gs != NULL ? eglsNR : 0,gs_buf,
405                             top_global,state,
406                             *bSumEkinhOld,flags);
407                 GMX_MPE_LOG(ev_global_stat_finish);
408                 wallcycle_stop(wcycle,ewcMoveE);
409             }
410             if (gs != NULL)
411             {
412                 if (MULTISIM(cr) && bInterSimGS)
413                 {
414                     if (MASTER(cr))
415                     {
416                         /* Communicate the signals between the simulations */
417                         gmx_sum_sim(eglsNR,gs_buf,cr->ms);
418                     }
419                     /* Communicate the signals form the master to the others */
420                     gmx_bcast(eglsNR*sizeof(gs_buf[0]),gs_buf,cr);
421                 }
422                 for(i=0; i<eglsNR; i++)
423                 {
424                     if (bInterSimGS || gs_simlocal[i])
425                     {
426                         /* Set the communicated signal only when it is non-zero,
427                          * since signals might not be processed at each MD step.
428                          */
429                         gsi = (gs_buf[i] >= 0 ?
430                                (int)(gs_buf[i] + 0.5) :
431                                (int)(gs_buf[i] - 0.5));
432                         if (gsi != 0)
433                         {
434                             gs->set[i] = gsi;
435                         }
436                         /* Turn off the local signal */
437                         gs->sig[i] = 0;
438                     }
439                 }
440             }
441             *bSumEkinhOld = FALSE;
442         }
443     }
444     
445     if (!ekind->bNEMD && debug && bTemp && (vcm->nr > 0))
446     {
447         correct_ekin(debug,
448                      mdatoms->start,mdatoms->start+mdatoms->homenr,
449                      state->v,vcm->group_p[0],
450                      mdatoms->massT,mdatoms->tmass,ekind->ekin);
451     }
452     
453     if (bEner) {
454         /* Do center of mass motion removal */
455         if (bStopCM && !bRerunMD) /* is this correct?  Does it get called too often with this logic? */
456         {
457             check_cm_grp(fplog,vcm,ir,1);
458             do_stopcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms->cVCM,
459                           state->x,state->v,vcm);
460             inc_nrnb(nrnb,eNR_STOPCM,mdatoms->homenr);
461         }
462     }
463
464     if (bTemp) 
465     {
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.
474         */ 
475         enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,&(enerd->term[F_DKDL]),
476                                        bEkinAveVel,bIterate,bScaleEkin);
477  
478         enerd->term[F_EKIN] = trace(ekind->ekin);
479     }
480     
481     /* ##########  Long range energy information ###### */
482     
483     if (bEner || bPres || bConstrain) 
484     {
485         calc_dispcorr(fplog,ir,fr,0,top_global->natoms,box,state->lambda,
486                       corr_pres,corr_vir,&prescorr,&enercorr,&dvdlcorr);
487     }
488     
489     if (bEner && bFirstIterate) 
490     {
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;
496         }
497     }
498     
499     /* ########## Now pressure ############## */
500     if (bPres || bConstrain) 
501     {
502         
503         m_add(force_vir,shake_vir,total_vir);
504         
505         /* Calculate pressure and apply LR correction if PPPM is used.
506          * Use the box from last timestep since we already called update().
507          */
508         
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);
511         
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 */
516         
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]);
524         
525     }    
526 }
527
528
529 /* Definitions for convergence of iterated constraints */
530
531 /* iterate constraints up to 50 times  */
532 #define MAXITERCONST       50
533
534 /* data type */
535 typedef struct
536 {
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;
543   
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
551
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
557   
558 /* maximum length of cyclic traps to check, emerging from limited numerical precision  */
559 #define CYCLEMAX            20
560
561 static void gmx_iterate_init(gmx_iterate_t *iterate,gmx_bool bIterate)
562 {
563     int i;
564
565     iterate->iter_i = 0;
566     iterate->bIterate = bIterate;
567     iterate->num_close = 0;
568     for (i=0;i<MAXITERCONST+2;i++) 
569     {
570         iterate->allrelerr[i] = 0;
571     }
572 }
573
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) 
575 {    
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})
581        
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.
588        
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 */
597
598     real relerr,err,xmin;
599     char buf[256];
600     int i;
601     gmx_bool incycle;
602     
603     if (bFirstIterate) 
604     {
605         iterate->x = fom;
606         iterate->f = fom-iterate->x;
607         iterate->xprev = 0;
608         iterate->fprev = 0;
609         *newf = fom;
610     } 
611     else 
612     {
613         iterate->f = fom-iterate->x; /* we want to zero this difference */
614         if ((iterate->iter_i > 1) && (iterate->iter_i < MAXITERCONST)) 
615         {
616             if (iterate->f==iterate->fprev) 
617             {
618                 *newf = iterate->f;
619             } 
620             else 
621             {
622                 *newf = iterate->x - (iterate->x-iterate->xprev)*(iterate->f)/(iterate->f-iterate->fprev); 
623             }
624         } 
625         else 
626         {
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; 
630         }
631     }
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
636        
637        relerr = (fabs((x-xprev)/fom));
638        
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.
644        
645        if (fabs(*newf-x) < fabs(*newf - xprev)) { xmin = x;} else { xmin = xprev;}
646        relerr = (fabs((*newf-xmin) / *newf));
647     */
648     
649     err = fabs((iterate->f-iterate->fprev));
650     relerr = fabs(err/fom);
651
652     iterate->allrelerr[iterate->iter_i] = relerr;
653     
654     if (iterate->iter_i > 0) 
655     {
656         if (debug) 
657         {
658             fprintf(debug,"Iterating NPT constraints: %6i %20.12f%14.6g%20.12f\n",
659                     iterate->iter_i,fom,relerr,*newf);
660         }
661         
662         if ((relerr < CONVERGEITER) || (err < CONVERGEITER) || (fom==0) || ((iterate->x == iterate->xprev) && iterate->iter_i > 1))
663         {
664             iterate->bIterate = FALSE;
665             if (debug) 
666             {
667                 fprintf(debug,"Iterating NPT constraints: CONVERGED\n");
668             }
669             return TRUE;
670         }
671         if (iterate->iter_i > MAXITERCONST)
672         {
673             if (relerr < CLOSE_ENOUGH)
674             {
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) 
681                         {
682                             fprintf(debug,"Exiting from an NPT iterating cycle of length %d\n",i);
683                         }
684                         break;
685                     }
686                 }
687                 
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.
692                     */
693                     iterate->num_close++;
694                     return TRUE;
695                 } 
696                 else 
697                 {
698                     /* Step #2: test if we are reasonably close for other reasons, then monitor the number.  If not, die */
699                     
700                     /* how many close calls have we had?  If less than a few, we're OK */
701                     if (iterate->num_close < MAX_NUMBER_CLOSE) 
702                     {
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);
710                     } 
711                 }
712             }
713             else 
714             {
715                 gmx_fatal(FARGS,"Could not converge NPT constraints\n");
716             }
717         }
718     }
719     
720     iterate->xprev = iterate->x;
721     iterate->x = *newf;
722     iterate->fprev = iterate->f;
723     iterate->iter_i++;
724     
725     return FALSE;
726 }
727
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)
731 {
732     char buf[STRLEN];
733
734     if (*p > 0 && *p % nst != 0)
735     {
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);
740     }
741 }
742
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)
748 {
749     char buf[STRLEN],sbuf[STEPSTRSIZE];
750
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);
755
756     wallcycle_stop(wcycle,ewcRUN);
757     wallcycle_reset_all(wcycle);
758     if (DOMAINDECOMP(cr))
759     {
760         reset_dd_statistics_counters(cr->dd);
761     }
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);
769 }
770
771 static void min_zero(int *n,int i)
772 {
773     if (i > 0 && (*n == 0 || i < *n))
774     {
775         *n = i;
776     }
777 }
778
779 static int lcd4(int i1,int i2,int i3,int i4)
780 {
781     int nst;
782
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)
789     {
790         gmx_incons("All 4 inputs for determininig nstglobalcomm are <= 0");
791     }
792     
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)))
797     {
798         nst--;
799     }
800
801     return nst;
802 }
803
804 static int check_nstglobalcomm(FILE *fplog,t_commrec *cr,
805                                int nstglobalcomm,t_inputrec *ir)
806 {
807     char buf[STRLEN];
808
809     if (!EI_DYNAMICS(ir->eI))
810     {
811         nstglobalcomm = 1;
812     }
813
814     if (nstglobalcomm == -1)
815     {
816         if (!(ir->nstcalcenergy > 0 ||
817               ir->nstlist > 0 ||
818               ir->etc != etcNO ||
819               ir->epc != epcNO))
820         {
821             nstglobalcomm = 10;
822             if (ir->nstenergy > 0 && ir->nstenergy < nstglobalcomm)
823             {
824                 nstglobalcomm = ir->nstenergy;
825             }
826         }
827         else
828         {
829             /* Ensure that we do timely global communication for
830              * (possibly) each of the four following options.
831              */
832             nstglobalcomm = lcd4(ir->nstcalcenergy,
833                                  ir->nstlist,
834                                  ir->etc != etcNO ? ir->nsttcouple : 0,
835                                  ir->epc != epcNO ? ir->nstpcouple : 0);
836         }
837     }
838     else
839     {
840         if (ir->nstlist > 0 &&
841             nstglobalcomm > ir->nstlist && nstglobalcomm % ir->nstlist != 0)
842         {
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);
846         }
847         if (ir->nstcalcenergy > 0)
848         {
849             check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
850                             "nstcalcenergy",&ir->nstcalcenergy);
851         }
852         if (ir->etc != etcNO && ir->nsttcouple > 0)
853         {
854             check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
855                             "nsttcouple",&ir->nsttcouple);
856         }
857         if (ir->epc != epcNO && ir->nstpcouple > 0)
858         {
859             check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
860                             "nstpcouple",&ir->nstpcouple);
861         }
862
863         check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
864                         "nstenergy",&ir->nstenergy);
865
866         check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
867                         "nstlog",&ir->nstlog);
868     }
869
870     if (ir->comm_mode != ecmNO && ir->nstcomm < nstglobalcomm)
871     {
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;
876     }
877
878     return nstglobalcomm;
879 }
880
881 void check_ir_old_tpx_versions(t_commrec *cr,FILE *fplog,
882                                t_inputrec *ir,gmx_mtop_t *mtop)
883 {
884     /* Check required for old tpx files */
885     if (IR_TWINRANGE(*ir) && ir->nstlist > 1 &&
886         ir->nstcalcenergy % ir->nstlist != 0)
887     {
888         md_print_warning(cr,fplog,"Old tpr file with twin-range settings: modifying energy calculation and/or T/P-coupling frequencies");
889
890         if (gmx_mtop_ftype_count(mtop,F_CONSTR) +
891             gmx_mtop_ftype_count(mtop,F_CONSTRNC) > 0 &&
892             ir->eConstrAlg == econtSHAKE)
893         {
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)
896             {
897                 gmx_fatal(FARGS,"Can not do pressure coupling with twin-range cut-off's and SHAKE");
898             }
899         }
900         check_nst_param(fplog,cr,"nstlist",ir->nstlist,
901                         "nstcalcenergy",&ir->nstcalcenergy);
902         if (ir->epc != epcNO)
903         {
904             check_nst_param(fplog,cr,"nstlist",ir->nstlist,
905                             "nstpcouple",&ir->nstpcouple);
906         }
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)
912         {
913             check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
914                             "nstdhdl",&ir->nstdhdl);
915         }
916     }
917 }
918
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;
932
933 static void reset_nlistheuristics(gmx_nlheur_t *nlh,gmx_large_int_t step)
934 {
935     nlh->lt_runav  = 0;
936     nlh->lt_runav2 = 0;
937     nlh->step_nscheck = step;
938 }
939
940 static void init_nlistheuristics(gmx_nlheur_t *nlh,
941                                  gmx_bool bGStatEveryStep,gmx_large_int_t step)
942 {
943     nlh->bGStatEveryStep = bGStatEveryStep;
944     nlh->nns       = 0;
945     nlh->nabnsb    = 0;
946     nlh->s1        = 0;
947     nlh->s2        = 0;
948     nlh->ab        = 0;
949
950     reset_nlistheuristics(nlh,step);
951 }
952
953 static void update_nliststatistics(gmx_nlheur_t *nlh,gmx_large_int_t step)
954 {
955     gmx_large_int_t nl_lt;
956     char sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
957
958     /* Determine the neighbor list life time */
959     nl_lt = step - nlh->step_ns;
960     if (debug)
961     {
962         fprintf(debug,"%d atoms beyond ns buffer, updating neighbor list after %s steps\n",nlh->nabnsb,gmx_step_str(nl_lt,sbuf));
963     }
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)
969     {
970         nlh->lt_runav  = nl_lt;
971         /* Initialize the fluctuation average
972          * such that at startup we check after 0 steps.
973          */
974         nlh->lt_runav2 = sqr(nl_lt/2.0);
975     }
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)
980     {
981         /* Always check the nlist validity */
982         nlh->step_nscheck = step;
983     }
984     else
985     {
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.
990          */
991         nlh->step_nscheck = step
992                   + (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)) - 1;
993     }
994     if (debug)
995     {
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)));
1000     }
1001 }
1002
1003 static void set_nlistheuristics(gmx_nlheur_t *nlh,gmx_bool bReset,gmx_large_int_t step)
1004 {
1005     int d;
1006
1007     if (bReset)
1008     {
1009         reset_nlistheuristics(nlh,step);
1010     }
1011     else
1012     {
1013         update_nliststatistics(nlh,step);
1014     }
1015
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++)
1020     {
1021         nlh->scale_tot[d][d] = 1.0;
1022     }
1023 }
1024
1025 static void rerun_parallel_comm(t_commrec *cr,t_trxframe *fr,
1026                                 gmx_bool *bNotLastFrame)
1027 {
1028     gmx_bool bAlloc;
1029     rvec *xp,*vp;
1030
1031     bAlloc = (fr->natoms == 0);
1032
1033     if (MASTER(cr) && !*bNotLastFrame)
1034     {
1035         fr->natoms = -1;
1036     }
1037     xp = fr->x;
1038     vp = fr->v;
1039     gmx_bcast(sizeof(*fr),fr,cr);
1040     fr->x = xp;
1041     fr->v = vp;
1042
1043     *bNotLastFrame = (fr->natoms >= 0);
1044
1045     if (*bNotLastFrame && PARTDECOMP(cr))
1046     {
1047         /* x and v are the only variable size quantities stored in trr
1048          * that are required for rerun (f is not needed).
1049          */
1050         if (bAlloc)
1051         {
1052             snew(fr->x,fr->natoms);
1053             snew(fr->v,fr->natoms);
1054         }
1055         if (fr->bX)
1056         {
1057             gmx_bcast(fr->natoms*sizeof(fr->x[0]),fr->x[0],cr);
1058         }
1059         if (fr->bV)
1060         {
1061             gmx_bcast(fr->natoms*sizeof(fr->v[0]),fr->v[0],cr);
1062         }
1063     }
1064 }
1065
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)
1082 {
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;
1108
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;
1121
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
1157
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)
1164     {
1165         if (ir->nsteps > 0)
1166         {
1167             /* Signal to reset the counters half the simulation steps. */
1168             wcycle_set_reset_counters(wcycle,ir->nsteps/2);
1169         }
1170         /* Signal to reset the counters halfway the simulation time. */
1171         bResetCountersHalfMaxH = (max_hours > 0);
1172     }
1173
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 */
1179     {
1180         snew(cbuf,top_global->natoms);
1181     }
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))));        
1185     
1186     if (bRerunMD)
1187     {
1188         /* Since we don't know if the frames read are related in any way,
1189          * rebuild the neighborlist at every step.
1190          */
1191         ir->nstlist       = 1;
1192         ir->nstcalcenergy = 1;
1193         nstglobalcomm     = 1;
1194     }
1195
1196     check_ir_old_tpx_versions(cr,fplog,ir,top_global);
1197
1198     nstglobalcomm = check_nstglobalcomm(fplog,cr,nstglobalcomm,ir);
1199     bGStatEveryStep = (nstglobalcomm == 1);
1200
1201     if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
1202     {
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");
1212     }
1213
1214     if (bRerunMD || bFFscan)
1215     {
1216         ir->nstxtcout = 0;
1217     }
1218     groups = &top_global->groups;
1219
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);
1225
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))
1232     {
1233         f = NULL;
1234     }
1235     else
1236     {
1237         snew(f,top_global->natoms);
1238     }
1239
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;
1248
1249     gstat = global_stat_init(ir);
1250     debug_gmx();
1251
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);
1258
1259     if (DEFORM(*ir))
1260     {
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
1270     }
1271
1272     {
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);
1278     }
1279
1280     if (DOMAINDECOMP(cr)) {
1281         top = dd_init_local_top(top_global);
1282
1283         snew(state,1);
1284         dd_init_local_state(cr->dd,state_global,state);
1285
1286         if (DDMASTER(cr->dd) && ir->nstfout) {
1287             snew(f_global,state_global->natoms);
1288         }
1289     } else {
1290         if (PAR(cr)) {
1291             /* Initialize the particle decomposition and split the topology */
1292             top = split_system(fplog,top_global,ir,cr);
1293
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);
1298
1299             a0 = 0;
1300             a1 = top_global->natoms;
1301         }
1302
1303         state = partdec_init_local_state(cr,state_global);
1304         f_global = f;
1305
1306         atoms2md(top_global,ir,0,NULL,a0,a1-a0,mdatoms);
1307
1308         if (vsite) {
1309             set_vsite_top(vsite,top,mdatoms,cr);
1310         }
1311
1312         if (ir->ePBC != epbcNONE && !ir->bPeriodicMols) {
1313             graph = mk_graph(fplog,&(top->idef),0,top_global->natoms,FALSE,FALSE);
1314         }
1315
1316         if (shellfc) {
1317             make_local_shells(cr,mdatoms,shellfc);
1318         }
1319
1320         if (ir->pull && PAR(cr)) {
1321             dd_make_local_pull_groups(NULL,ir->pull,mdatoms);
1322         }
1323     }
1324
1325     if (DOMAINDECOMP(cr))
1326     {
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);
1333     }
1334
1335     update_mdatoms(mdatoms,state->lambda);
1336
1337     if (MASTER(cr))
1338     {
1339         /* Update mdebin with energy history if appending to output files */
1340         if ( Flags & MD_APPENDFILES )
1341         {
1342             restore_energyhistory_from_state(mdebin,&state_global->enerhist);
1343         }
1344         /* Set the initial energy history in state to zero by updating once */
1345         update_energyhistory(&state_global->enerhist,mdebin);
1346     }   
1347
1348     if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG)) {
1349         /* Set the random state if we read a checkpoint file */
1350         set_stochd_state(upd,state);
1351     }
1352
1353     /* Initialize constraints */
1354     if (constr) {
1355         if (!DOMAINDECOMP(cr))
1356             set_constraints(constr,top,ir,mdatoms,cr);
1357     }
1358
1359     /* Check whether we have to GCT stuff */
1360     bTCR = ftp2bSet(efGCT,nfile,fnm);
1361     if (bTCR) {
1362         if (MASTER(cr)) {
1363             fprintf(stderr,"Will do General Coupling Theory!\n");
1364         }
1365         gnx = top_global->mols.nr;
1366         snew(grpindex,gnx);
1367         for(i=0; (i<gnx); i++) {
1368             grpindex[i] = i;
1369         }
1370     }
1371
1372     if (repl_ex_nst > 0 && MASTER(cr))
1373         repl_ex = init_replica_exchange(fplog,cr->ms,state_global,ir,
1374                                         repl_ex_nst,repl_ex_seed);
1375
1376     if (!ir->bContinuation && !bRerunMD)
1377     {
1378         if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
1379         {
1380             /* Set the velocities of frozen particles to zero */
1381             for(i=mdatoms->start; i<mdatoms->start+mdatoms->homenr; i++)
1382             {
1383                 for(m=0; m<DIM; m++)
1384                 {
1385                     if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
1386                     {
1387                         state->v[i][m] = 0;
1388                     }
1389                 }
1390             }
1391         }
1392
1393         if (constr)
1394         {
1395             /* Constrain the initial coordinates and velocities */
1396             do_constrain_first(fplog,constr,ir,mdatoms,state,f,
1397                                graph,cr,nrnb,fr,top,shake_vir);
1398         }
1399         if (vsite)
1400         {
1401             /* Construct the virtual sites for the initial configuration */
1402             construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,NULL,
1403                              top->idef.iparams,top->idef.il,
1404                              fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1405         }
1406     }
1407
1408     debug_gmx();
1409   
1410     /* I'm assuming we need global communication the first time! MRS */
1411     cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
1412                   | (bVV ? CGLO_PRESSURE:0)
1413                   | (bVV ? CGLO_CONSTRAINT:0)
1414                   | (bRerunMD ? CGLO_RERUNMD:0)
1415                   | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN:0));
1416     
1417     bSumEkinhOld = FALSE;
1418     compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1419                     wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1420                     constr,NULL,FALSE,state->box,
1421                     top_global,&pcurr,top_global->natoms,&bSumEkinhOld,cglo_flags);
1422     if (ir->eI == eiVVAK) {
1423         /* a second call to get the half step temperature initialized as well */ 
1424         /* we do the same call as above, but turn the pressure off -- internally to 
1425            compute_globals, this is recognized as a velocity verlet half-step 
1426            kinetic energy calculation.  This minimized excess variables, but 
1427            perhaps loses some logic?*/
1428         
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,
1433                         cglo_flags &~ CGLO_PRESSURE);
1434     }
1435     
1436     /* Calculate the initial half step temperature, and save the ekinh_old */
1437     if (!(Flags & MD_STARTFROMCPT)) 
1438     {
1439         for(i=0; (i<ir->opts.ngtc); i++) 
1440         {
1441             copy_mat(ekind->tcstat[i].ekinh,ekind->tcstat[i].ekinh_old);
1442         } 
1443     }
1444     if (ir->eI != eiVV) 
1445     {
1446         enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
1447                                      and there is no previous step */
1448     }
1449     temp0 = enerd->term[F_TEMP];
1450     
1451     /* if using an iterative algorithm, we need to create a working directory for the state. */
1452     if (bIterations) 
1453     {
1454             bufstate = init_bufstate(state);
1455     }
1456     if (bFFscan) 
1457     {
1458         snew(xcopy,state->natoms);
1459         snew(vcopy,state->natoms);
1460         copy_rvecn(state->x,xcopy,0,state->natoms);
1461         copy_rvecn(state->v,vcopy,0,state->natoms);
1462         copy_mat(state->box,boxcopy);
1463     } 
1464     
1465     /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
1466        temperature control */
1467     trotter_seq = init_npt_vars(ir,state,&MassQ,bTrotter);
1468     
1469     if (MASTER(cr))
1470     {
1471         if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
1472         {
1473             fprintf(fplog,
1474                     "RMS relative constraint deviation after constraining: %.2e\n",
1475                     constr_rmsd(constr,FALSE));
1476         }
1477         fprintf(fplog,"Initial temperature: %g K\n",enerd->term[F_TEMP]);
1478         if (bRerunMD)
1479         {
1480             fprintf(stderr,"starting md rerun '%s', reading coordinates from"
1481                     " input trajectory '%s'\n\n",
1482                     *(top_global->name),opt2fn("-rerun",nfile,fnm));
1483             if (bVerbose)
1484             {
1485                 fprintf(stderr,"Calculated time to finish depends on nsteps from "
1486                         "run input file,\nwhich may not correspond to the time "
1487                         "needed to process input trajectory.\n\n");
1488             }
1489         }
1490         else
1491         {
1492             char tbuf[20];
1493             fprintf(stderr,"starting mdrun '%s'\n",
1494                     *(top_global->name));
1495             if (ir->nsteps >= 0)
1496             {
1497                 sprintf(tbuf,"%8.1f",(ir->init_step+ir->nsteps)*ir->delta_t);
1498             }
1499             else
1500             {
1501                 sprintf(tbuf,"%s","infinite");
1502             }
1503             if (ir->init_step > 0)
1504             {
1505                 fprintf(stderr,"%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
1506                         gmx_step_str(ir->init_step+ir->nsteps,sbuf),tbuf,
1507                         gmx_step_str(ir->init_step,sbuf2),
1508                         ir->init_step*ir->delta_t);
1509             }
1510             else
1511             {
1512                 fprintf(stderr,"%s steps, %s ps.\n",
1513                         gmx_step_str(ir->nsteps,sbuf),tbuf);
1514             }
1515         }
1516         fprintf(fplog,"\n");
1517     }
1518
1519     /* Set and write start time */
1520     runtime_start(runtime);
1521     print_date_and_time(fplog,cr->nodeid,"Started mdrun",runtime);
1522     wallcycle_start(wcycle,ewcRUN);
1523     if (fplog)
1524         fprintf(fplog,"\n");
1525
1526     /* safest point to do file checkpointing is here.  More general point would be immediately before integrator call */
1527 #ifdef GMX_FAHCORE
1528     chkpt_ret=fcCheckPointParallel( cr->nodeid,
1529                                     NULL,0);
1530     if ( chkpt_ret == 0 ) 
1531         gmx_fatal( 3,__FILE__,__LINE__, "Checkpoint error on step %d\n", 0 );
1532 #endif
1533
1534     debug_gmx();
1535     /***********************************************************
1536      *
1537      *             Loop over MD steps 
1538      *
1539      ************************************************************/
1540
1541     /* if rerunMD then read coordinates and velocities from input trajectory */
1542     if (bRerunMD)
1543     {
1544         if (getenv("GMX_FORCE_UPDATE"))
1545         {
1546             bForceUpdate = TRUE;
1547         }
1548
1549         rerun_fr.natoms = 0;
1550         if (MASTER(cr))
1551         {
1552             bNotLastFrame = read_first_frame(oenv,&status,
1553                                              opt2fn("-rerun",nfile,fnm),
1554                                              &rerun_fr,TRX_NEED_X | TRX_READ_V);
1555             if (rerun_fr.natoms != top_global->natoms)
1556             {
1557                 gmx_fatal(FARGS,
1558                           "Number of atoms in trajectory (%d) does not match the "
1559                           "run input file (%d)\n",
1560                           rerun_fr.natoms,top_global->natoms);
1561             }
1562             if (ir->ePBC != epbcNONE)
1563             {
1564                 if (!rerun_fr.bBox)
1565                 {
1566                     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);
1567                 }
1568                 if (max_cutoff2(ir->ePBC,rerun_fr.box) < sqr(fr->rlistlong))
1569                 {
1570                     gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f has too small box dimensions",rerun_fr.step,rerun_fr.time);
1571                 }
1572             }
1573         }
1574
1575         if (PAR(cr))
1576         {
1577             rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
1578         }
1579
1580         if (ir->ePBC != epbcNONE)
1581         {
1582             /* Set the shift vectors.
1583              * Necessary here when have a static box different from the tpr box.
1584              */
1585             calc_shifts(rerun_fr.box,fr->shift_vec);
1586         }
1587     }
1588
1589     /* loop over MD steps or if rerunMD to end of input trajectory */
1590     bFirstStep = TRUE;
1591     /* Skip the first Nose-Hoover integration when we get the state from tpx */
1592     bStateFromTPX = !opt2bSet("-cpi",nfile,fnm);
1593     bInitStep = bFirstStep && (bStateFromTPX || bVV);
1594     bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
1595     bLastStep    = FALSE;
1596     bSumEkinhOld = FALSE;
1597     bExchanged   = FALSE;
1598
1599     init_global_signals(&gs,cr,ir,repl_ex_nst);
1600
1601     step = ir->init_step;
1602     step_rel = 0;
1603
1604     if (ir->nstlist == -1)
1605     {
1606         init_nlistheuristics(&nlh,bGStatEveryStep,step);
1607     }
1608
1609     bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps));
1610     while (!bLastStep || (bRerunMD && bNotLastFrame)) {
1611
1612         wallcycle_start(wcycle,ewcSTEP);
1613
1614         GMX_MPE_LOG(ev_timestep1);
1615
1616         if (bRerunMD) {
1617             if (rerun_fr.bStep) {
1618                 step = rerun_fr.step;
1619                 step_rel = step - ir->init_step;
1620             }
1621             if (rerun_fr.bTime) {
1622                 t = rerun_fr.time;
1623             }
1624             else
1625             {
1626                 t = step;
1627             }
1628         } 
1629         else 
1630         {
1631             bLastStep = (step_rel == ir->nsteps);
1632             t = t0 + step*ir->delta_t;
1633         }
1634
1635         if (ir->efep != efepNO)
1636         {
1637             if (bRerunMD && rerun_fr.bLambda && (ir->delta_lambda!=0))
1638             {
1639                 state_global->lambda = rerun_fr.lambda;
1640             }
1641             else
1642             {
1643                 state_global->lambda = lam0 + step*ir->delta_lambda;
1644             }
1645             state->lambda = state_global->lambda;
1646             bDoDHDL = do_per_step(step,ir->nstdhdl);
1647         }
1648
1649         if (bSimAnn) 
1650         {
1651             update_annealing_target_temp(&(ir->opts),t);
1652         }
1653
1654         if (bRerunMD)
1655         {
1656             if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
1657             {
1658                 for(i=0; i<state_global->natoms; i++)
1659                 {
1660                     copy_rvec(rerun_fr.x[i],state_global->x[i]);
1661                 }
1662                 if (rerun_fr.bV)
1663                 {
1664                     for(i=0; i<state_global->natoms; i++)
1665                     {
1666                         copy_rvec(rerun_fr.v[i],state_global->v[i]);
1667                     }
1668                 }
1669                 else
1670                 {
1671                     for(i=0; i<state_global->natoms; i++)
1672                     {
1673                         clear_rvec(state_global->v[i]);
1674                     }
1675                     if (bRerunWarnNoV)
1676                     {
1677                         fprintf(stderr,"\nWARNING: Some frames do not contain velocities.\n"
1678                                 "         Ekin, temperature and pressure are incorrect,\n"
1679                                 "         the virial will be incorrect when constraints are present.\n"
1680                                 "\n");
1681                         bRerunWarnNoV = FALSE;
1682                     }
1683                 }
1684             }
1685             copy_mat(rerun_fr.box,state_global->box);
1686             copy_mat(state_global->box,state->box);
1687
1688             if (vsite && (Flags & MD_RERUN_VSITE))
1689             {
1690                 if (DOMAINDECOMP(cr))
1691                 {
1692                     gmx_fatal(FARGS,"Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
1693                 }
1694                 if (graph)
1695                 {
1696                     /* Following is necessary because the graph may get out of sync
1697                      * with the coordinates if we only have every N'th coordinate set
1698                      */
1699                     mk_mshift(fplog,graph,fr->ePBC,state->box,state->x);
1700                     shift_self(graph,state->box,state->x);
1701                 }
1702                 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
1703                                  top->idef.iparams,top->idef.il,
1704                                  fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1705                 if (graph)
1706                 {
1707                     unshift_self(graph,state->box,state->x);
1708                 }
1709             }
1710         }
1711
1712         /* Stop Center of Mass motion */
1713         bStopCM = (ir->comm_mode != ecmNO && do_per_step(step,ir->nstcomm));
1714
1715         /* Copy back starting coordinates in case we're doing a forcefield scan */
1716         if (bFFscan)
1717         {
1718             for(ii=0; (ii<state->natoms); ii++)
1719             {
1720                 copy_rvec(xcopy[ii],state->x[ii]);
1721                 copy_rvec(vcopy[ii],state->v[ii]);
1722             }
1723             copy_mat(boxcopy,state->box);
1724         }
1725
1726         if (bRerunMD)
1727         {
1728             /* for rerun MD always do Neighbour Searching */
1729             bNS = (bFirstStep || ir->nstlist != 0);
1730             bNStList = bNS;
1731         }
1732         else
1733         {
1734             /* Determine whether or not to do Neighbour Searching and LR */
1735             bNStList = (ir->nstlist > 0  && step % ir->nstlist == 0);
1736             
1737             bNS = (bFirstStep || bExchanged || bNStList ||
1738                    (ir->nstlist == -1 && nlh.nabnsb > 0));
1739
1740             if (bNS && ir->nstlist == -1)
1741             {
1742                 set_nlistheuristics(&nlh,bFirstStep || bExchanged,step);
1743             }
1744         } 
1745
1746         /* < 0 means stop at next step, > 0 means stop at next NS step */
1747         if ( (gs.set[eglsSTOPCOND] < 0 ) ||
1748              ( (gs.set[eglsSTOPCOND] > 0 ) && ( bNS || ir->nstlist==0)) )
1749         {
1750             bLastStep = TRUE;
1751         }
1752
1753         /* Determine whether or not to update the Born radii if doing GB */
1754         bBornRadii=bFirstStep;
1755         if (ir->implicit_solvent && (step % ir->nstgbradii==0))
1756         {
1757             bBornRadii=TRUE;
1758         }
1759         
1760         do_log = do_per_step(step,ir->nstlog) || bFirstStep || bLastStep;
1761         do_verbose = bVerbose &&
1762                   (step % stepout == 0 || bFirstStep || bLastStep);
1763
1764         if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
1765         {
1766             if (bRerunMD)
1767             {
1768                 bMasterState = TRUE;
1769             }
1770             else
1771             {
1772                 bMasterState = FALSE;
1773                 /* Correct the new box if it is too skewed */
1774                 if (DYNAMIC_BOX(*ir))
1775                 {
1776                     if (correct_box(fplog,step,state->box,graph))
1777                     {
1778                         bMasterState = TRUE;
1779                     }
1780                 }
1781                 if (DOMAINDECOMP(cr) && bMasterState)
1782                 {
1783                     dd_collect_state(cr->dd,state,state_global);
1784                 }
1785             }
1786
1787             if (DOMAINDECOMP(cr))
1788             {
1789                 /* Repartition the domain decomposition */
1790                 wallcycle_start(wcycle,ewcDOMDEC);
1791                 dd_partition_system(fplog,step,cr,
1792                                     bMasterState,nstglobalcomm,
1793                                     state_global,top_global,ir,
1794                                     state,&f,mdatoms,top,fr,
1795                                     vsite,shellfc,constr,
1796                                     nrnb,wcycle,do_verbose);
1797                 wallcycle_stop(wcycle,ewcDOMDEC);
1798                 /* If using an iterative integrator, reallocate space to match the decomposition */
1799             }
1800         }
1801
1802         if (MASTER(cr) && do_log && !bFFscan)
1803         {
1804             print_ebin_header(fplog,step,t,state->lambda);
1805         }
1806
1807         if (ir->efep != efepNO)
1808         {
1809             update_mdatoms(mdatoms,state->lambda); 
1810         }
1811
1812         if (bRerunMD && rerun_fr.bV)
1813         {
1814             
1815             /* We need the kinetic energy at minus the half step for determining
1816              * the full step kinetic energy and possibly for T-coupling.*/
1817             /* This may not be quite working correctly yet . . . . */
1818             compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1819                             wcycle,enerd,NULL,NULL,NULL,NULL,mu_tot,
1820                             constr,NULL,FALSE,state->box,
1821                             top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1822                             CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1823         }
1824         clear_mat(force_vir);
1825         
1826         /* Ionize the atoms if necessary */
1827         if (bIonize)
1828         {
1829             ionize(fplog,oenv,mdatoms,top_global,t,ir,state->x,state->v,
1830                    mdatoms->start,mdatoms->start+mdatoms->homenr,state->box,cr);
1831         }
1832         
1833         /* Update force field in ffscan program */
1834         if (bFFscan)
1835         {
1836             if (update_forcefield(fplog,
1837                                   nfile,fnm,fr,
1838                                   mdatoms->nr,state->x,state->box)) {
1839                 if (gmx_parallel_env_initialized())
1840                 {
1841                     gmx_finalize();
1842                 }
1843                 exit(0);
1844             }
1845         }
1846
1847         GMX_MPE_LOG(ev_timestep2);
1848
1849         /* We write a checkpoint at this MD step when:
1850          * either at an NS step when we signalled through gs,
1851          * or at the last step (but not when we do not want confout),
1852          * but never at the first step or with rerun.
1853          */
1854         bCPT = (((gs.set[eglsCHKPT] && bNS) ||
1855                  (bLastStep && (Flags & MD_CONFOUT))) &&
1856                 step > ir->init_step && !bRerunMD);
1857         if (bCPT)
1858         {
1859             gs.set[eglsCHKPT] = 0;
1860         }
1861
1862         /* Determine the energy and pressure:
1863          * at nstcalcenergy steps and at energy output steps (set below).
1864          */
1865         bNstEner = do_per_step(step,ir->nstcalcenergy);
1866         bCalcEnerPres =
1867             (bNstEner ||
1868              (ir->epc != epcNO && do_per_step(step,ir->nstpcouple)));
1869
1870         /* Do we need global communication ? */
1871         bGStat = (bCalcEnerPres || bStopCM ||
1872                   do_per_step(step,nstglobalcomm) ||
1873                   (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
1874
1875         do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
1876
1877         if (do_ene || do_log)
1878         {
1879             bCalcEnerPres = TRUE;
1880             bGStat        = TRUE;
1881         }
1882         
1883         /* these CGLO_ options remain the same throughout the iteration */
1884         cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
1885                       (bStopCM ? CGLO_STOPCM : 0) |
1886                       (bGStat ? CGLO_GSTAT : 0)
1887             );
1888         
1889         force_flags = (GMX_FORCE_STATECHANGED |
1890                        ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1891                        GMX_FORCE_ALLFORCES |
1892                        (bNStList ? GMX_FORCE_DOLR : 0) |
1893                        GMX_FORCE_SEPLRF |
1894                        (bCalcEnerPres ? GMX_FORCE_VIRIAL : 0) |
1895                        (bDoDHDL ? GMX_FORCE_DHDL : 0)
1896             );
1897         
1898         if (shellfc)
1899         {
1900             /* Now is the time to relax the shells */
1901             count=relax_shell_flexcon(fplog,cr,bVerbose,bFFscan ? step+1 : step,
1902                                       ir,bNS,force_flags,
1903                                       bStopCM,top,top_global,
1904                                       constr,enerd,fcd,
1905                                       state,f,force_vir,mdatoms,
1906                                       nrnb,wcycle,graph,groups,
1907                                       shellfc,fr,bBornRadii,t,mu_tot,
1908                                       state->natoms,&bConverged,vsite,
1909                                       outf->fp_field);
1910             tcount+=count;
1911
1912             if (bConverged)
1913             {
1914                 nconverged++;
1915             }
1916         }
1917         else
1918         {
1919             /* The coordinates (x) are shifted (to get whole molecules)
1920              * in do_force.
1921              * This is parallellized as well, and does communication too. 
1922              * Check comments in sim_util.c
1923              */
1924         
1925             do_force(fplog,cr,ir,step,nrnb,wcycle,top,top_global,groups,
1926                      state->box,state->x,&state->hist,
1927                      f,force_vir,mdatoms,enerd,fcd,
1928                      state->lambda,graph,
1929                      fr,vsite,mu_tot,t,outf->fp_field,ed,bBornRadii,
1930                      (bNS ? GMX_FORCE_NS : 0) | force_flags);
1931         }
1932     
1933         GMX_BARRIER(cr->mpi_comm_mygroup);
1934         
1935         if (bTCR)
1936         {
1937             mu_aver = calc_mu_aver(cr,state->x,mdatoms->chargeA,
1938                                    mu_tot,&top_global->mols,mdatoms,gnx,grpindex);
1939         }
1940         
1941         if (bTCR && bFirstStep)
1942         {
1943             tcr=init_coupling(fplog,nfile,fnm,cr,fr,mdatoms,&(top->idef));
1944             fprintf(fplog,"Done init_coupling\n"); 
1945             fflush(fplog);
1946         }
1947         
1948         if (bVV && !bStartingFromCpt && !bRerunMD)
1949         /*  ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1950         {
1951             if (ir->eI==eiVV && bInitStep) 
1952             {
1953                 /* if using velocity verlet with full time step Ekin,
1954                  * take the first half step only to compute the 
1955                  * virial for the first step. From there,
1956                  * revert back to the initial coordinates
1957                  * so that the input is actually the initial step.
1958                  */
1959                 copy_rvecn(state->v,cbuf,0,state->natoms); /* should make this better for parallelizing? */
1960             } else {
1961                 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1962                 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ1);            
1963             }
1964
1965             update_coords(fplog,step,ir,mdatoms,state,
1966                           f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1967                           ekind,M,wcycle,upd,bInitStep,etrtVELOCITY1,
1968                           cr,nrnb,constr,&top->idef);
1969             
1970             if (bIterations)
1971             {
1972                 gmx_iterate_init(&iterate,bIterations && !bInitStep);
1973             }
1974             /* for iterations, we save these vectors, as we will be self-consistently iterating
1975                the calculations */
1976
1977             /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1978             
1979             /* save the state */
1980             if (bIterations && iterate.bIterate) { 
1981                 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1982             }
1983             
1984             bFirstIterate = TRUE;
1985             while (bFirstIterate || (bIterations && iterate.bIterate))
1986             {
1987                 if (bIterations && iterate.bIterate) 
1988                 {
1989                     copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
1990                     if (bFirstIterate && bTrotter) 
1991                     {
1992                         /* The first time through, we need a decent first estimate
1993                            of veta(t+dt) to compute the constraints.  Do
1994                            this by computing the box volume part of the
1995                            trotter integration at this time. Nothing else
1996                            should be changed by this routine here.  If
1997                            !(first time), we start with the previous value
1998                            of veta.  */
1999                         
2000                         veta_save = state->veta;
2001                         trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ0);
2002                         vetanew = state->veta;
2003                         state->veta = veta_save;
2004                     } 
2005                 } 
2006                 
2007                 bOK = TRUE;
2008                 if ( !bRerunMD || rerun_fr.bV || bForceUpdate) {  /* Why is rerun_fr.bV here?  Unclear. */
2009                     dvdl = 0;
2010                     
2011                     update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2012                                        &top->idef,shake_vir,NULL,
2013                                        cr,nrnb,wcycle,upd,constr,
2014                                        bInitStep,TRUE,bCalcEnerPres,vetanew);
2015                     
2016                     if (!bOK && !bFFscan)
2017                     {
2018                         gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2019                     }
2020                     
2021                 } 
2022                 else if (graph)
2023                 { /* Need to unshift here if a do_force has been
2024                      called in the previous step */
2025                     unshift_self(graph,state->box,state->x);
2026                 }
2027                 
2028                 
2029                 /* if VV, compute the pressure and constraints */
2030                 /* For VV2, we strictly only need this if using pressure
2031                  * control, but we really would like to have accurate pressures
2032                  * printed out.
2033                  * Think about ways around this in the future?
2034                  * For now, keep this choice in comments.
2035                  */
2036                 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
2037                     /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
2038                 bPres = TRUE;
2039                 bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK));
2040                 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2041                                 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2042                                 constr,NULL,FALSE,state->box,
2043                                 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2044                                 cglo_flags 
2045                                 | CGLO_ENERGY 
2046                                 | (bTemp ? CGLO_TEMPERATURE:0) 
2047                                 | (bPres ? CGLO_PRESSURE : 0) 
2048                                 | (bPres ? CGLO_CONSTRAINT : 0)
2049                                 | ((bIterations && iterate.bIterate) ? CGLO_ITERATE : 0)  
2050                                 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
2051                                 | CGLO_SCALEEKIN 
2052                     );
2053                 /* explanation of above: 
2054                    a) We compute Ekin at the full time step
2055                    if 1) we are using the AveVel Ekin, and it's not the
2056                    initial step, or 2) if we are using AveEkin, but need the full
2057                    time step kinetic energy for the pressure (always true now, since we want accurate statistics).
2058                    b) If we are using EkinAveEkin for the kinetic energy for the temperture control, we still feed in 
2059                    EkinAveVel because it's needed for the pressure */
2060                 
2061                 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
2062                 if (!bInitStep) 
2063                 {
2064                     if (bTrotter)
2065                     {
2066                         trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ2);
2067                     } 
2068                     else 
2069                     {
2070                         update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
2071                     }
2072                 }
2073                 
2074                 if (bIterations &&
2075                     done_iterating(cr,fplog,step,&iterate,bFirstIterate,
2076                                    state->veta,&vetanew)) 
2077                 {
2078                     break;
2079                 }
2080                 bFirstIterate = FALSE;
2081             }
2082
2083             if (bTrotter && !bInitStep) {
2084                 copy_mat(shake_vir,state->svir_prev);
2085                 copy_mat(force_vir,state->fvir_prev);
2086                 if (IR_NVT_TROTTER(ir) && ir->eI==eiVV) {
2087                     /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
2088                     enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,NULL,(ir->eI==eiVV),FALSE,FALSE);
2089                     enerd->term[F_EKIN] = trace(ekind->ekin);
2090                 }
2091             }
2092             /* if it's the initial step, we performed this first step just to get the constraint virial */
2093             if (bInitStep && ir->eI==eiVV) {
2094                 copy_rvecn(cbuf,state->v,0,state->natoms);
2095             }
2096             
2097             if (fr->bSepDVDL && fplog && do_log) 
2098             {
2099                 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2100             }
2101             enerd->term[F_DHDL_CON] += dvdl;
2102             
2103             GMX_MPE_LOG(ev_timestep1);
2104         }
2105     
2106         /* MRS -- now done iterating -- compute the conserved quantity */
2107         if (bVV) {
2108             saved_conserved_quantity = compute_conserved_from_auxiliary(ir,state,&MassQ);
2109             if (ir->eI==eiVV) 
2110             {
2111                 last_ekin = enerd->term[F_EKIN]; /* does this get preserved through checkpointing? */
2112             }
2113             if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres)) 
2114             {
2115                 saved_conserved_quantity -= enerd->term[F_DISPCORR];
2116             }
2117         }
2118         
2119         /* ########  END FIRST UPDATE STEP  ############## */
2120         /* ########  If doing VV, we now have v(dt) ###### */
2121         
2122         /* ################## START TRAJECTORY OUTPUT ################# */
2123         
2124         /* Now we have the energies and forces corresponding to the 
2125          * coordinates at time t. We must output all of this before
2126          * the update.
2127          * for RerunMD t is read from input trajectory
2128          */
2129         GMX_MPE_LOG(ev_output_start);
2130
2131         mdof_flags = 0;
2132         if (do_per_step(step,ir->nstxout)) { mdof_flags |= MDOF_X; }
2133         if (do_per_step(step,ir->nstvout)) { mdof_flags |= MDOF_V; }
2134         if (do_per_step(step,ir->nstfout)) { mdof_flags |= MDOF_F; }
2135         if (do_per_step(step,ir->nstxtcout)) { mdof_flags |= MDOF_XTC; }
2136         if (bCPT) { mdof_flags |= MDOF_CPT; };
2137
2138 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
2139         if (bLastStep)
2140         {
2141             /* Enforce writing positions and velocities at end of run */
2142             mdof_flags |= (MDOF_X | MDOF_V);
2143         }
2144 #endif
2145 #ifdef GMX_FAHCORE
2146         if (MASTER(cr))
2147             fcReportProgress( ir->nsteps, step );
2148
2149         /* sync bCPT and fc record-keeping */
2150         if (bCPT && MASTER(cr))
2151             fcRequestCheckPoint();
2152 #endif
2153         
2154         if (mdof_flags != 0)
2155         {
2156             wallcycle_start(wcycle,ewcTRAJ);
2157             if (bCPT)
2158             {
2159                 if (state->flags & (1<<estLD_RNG))
2160                 {
2161                     get_stochd_state(upd,state);
2162                 }
2163                 if (MASTER(cr))
2164                 {
2165                     if (bSumEkinhOld)
2166                     {
2167                         state_global->ekinstate.bUpToDate = FALSE;
2168                     }
2169                     else
2170                     {
2171                         update_ekinstate(&state_global->ekinstate,ekind);
2172                         state_global->ekinstate.bUpToDate = TRUE;
2173                     }
2174                     update_energyhistory(&state_global->enerhist,mdebin);
2175                 }
2176             }
2177             write_traj(fplog,cr,outf,mdof_flags,top_global,
2178                        step,t,state,state_global,f,f_global,&n_xtc,&x_xtc);
2179             if (bCPT)
2180             {
2181                 nchkpt++;
2182                 bCPT = FALSE;
2183             }
2184             debug_gmx();
2185             if (bLastStep && step_rel == ir->nsteps &&
2186                 (Flags & MD_CONFOUT) && MASTER(cr) &&
2187                 !bRerunMD && !bFFscan)
2188             {
2189                 /* x and v have been collected in write_traj,
2190                  * because a checkpoint file will always be written
2191                  * at the last step.
2192                  */
2193                 fprintf(stderr,"\nWriting final coordinates.\n");
2194                 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols &&
2195                     DOMAINDECOMP(cr))
2196                 {
2197                     /* Make molecules whole only for confout writing */
2198                     do_pbc_mtop(fplog,ir->ePBC,state->box,top_global,state_global->x);
2199                 }
2200                 write_sto_conf_mtop(ftp2fn(efSTO,nfile,fnm),
2201                                     *top_global->name,top_global,
2202                                     state_global->x,state_global->v,
2203                                     ir->ePBC,state->box);
2204                 debug_gmx();
2205             }
2206             wallcycle_stop(wcycle,ewcTRAJ);
2207         }
2208         GMX_MPE_LOG(ev_output_finish);
2209         
2210         /* kludge -- virial is lost with restart for NPT control. Must restart */
2211         if (bStartingFromCpt && bVV) 
2212         {
2213             copy_mat(state->svir_prev,shake_vir);
2214             copy_mat(state->fvir_prev,force_vir);
2215         }
2216         /*  ################## END TRAJECTORY OUTPUT ################ */
2217         
2218         /* Determine the pressure:
2219          * always when we want exact averages in the energy file,
2220          * at ns steps when we have pressure coupling,
2221          * otherwise only at energy output steps (set below).
2222          */
2223     
2224         bNstEner = (bGStatEveryStep || do_per_step(step,ir->nstcalcenergy));
2225         bCalcEnerPres = bNstEner;
2226         
2227         /* Do we need global communication ? */
2228         bGStat = (bGStatEveryStep || bStopCM || bNS ||
2229                   (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
2230         
2231         do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
2232         
2233         if (do_ene || do_log)
2234         {
2235             bCalcEnerPres = TRUE;
2236             bGStat        = TRUE;
2237         }
2238
2239         /* Determine the wallclock run time up till now */
2240         run_time = gmx_gettime() - (double)runtime->real;
2241
2242         /* Check whether everything is still allright */    
2243         if (((int)gmx_get_stop_condition() > handled_stop_condition)
2244 #ifdef GMX_THREADS
2245             && MASTER(cr)
2246 #endif
2247             )
2248         {
2249             /* this is just make gs.sig compatible with the hack 
2250                of sending signals around by MPI_Reduce with together with
2251                other floats */
2252             if ( gmx_get_stop_condition() == gmx_stop_cond_next_ns )
2253                 gs.sig[eglsSTOPCOND]=1;
2254             if ( gmx_get_stop_condition() == gmx_stop_cond_next )
2255                 gs.sig[eglsSTOPCOND]=-1;
2256             /* < 0 means stop at next step, > 0 means stop at next NS step */
2257             if (fplog)
2258             {
2259                 fprintf(fplog,
2260                         "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2261                         gmx_get_signal_name(),
2262                         gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
2263                 fflush(fplog);
2264             }
2265             fprintf(stderr,
2266                     "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2267                     gmx_get_signal_name(),
2268                     gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
2269             fflush(stderr);
2270             handled_stop_condition=(int)gmx_get_stop_condition();
2271         }
2272         else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
2273                  (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
2274                  gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
2275         {
2276             /* Signal to terminate the run */
2277             gs.sig[eglsSTOPCOND] = 1;
2278             if (fplog)
2279             {
2280                 fprintf(fplog,"\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2281             }
2282             fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2283         }
2284         
2285         if (bResetCountersHalfMaxH && MASTER(cr) &&
2286             run_time > max_hours*60.0*60.0*0.495)
2287         {
2288             gs.sig[eglsRESETCOUNTERS] = 1;
2289         }
2290
2291         if (ir->nstlist == -1 && !bRerunMD)
2292         {
2293             /* When bGStatEveryStep=FALSE, global_stat is only called
2294              * when we check the atom displacements, not at NS steps.
2295              * This means that also the bonded interaction count check is not
2296              * performed immediately after NS. Therefore a few MD steps could
2297              * be performed with missing interactions.
2298              * But wrong energies are never written to file,
2299              * since energies are only written after global_stat
2300              * has been called.
2301              */
2302             if (step >= nlh.step_nscheck)
2303             {
2304                 nlh.nabnsb = natoms_beyond_ns_buffer(ir,fr,&top->cgs,
2305                                                      nlh.scale_tot,state->x);
2306             }
2307             else
2308             {
2309                 /* This is not necessarily true,
2310                  * but step_nscheck is determined quite conservatively.
2311                  */
2312                 nlh.nabnsb = 0;
2313             }
2314         }
2315
2316         /* In parallel we only have to check for checkpointing in steps
2317          * where we do global communication,
2318          *  otherwise the other nodes don't know.
2319          */
2320         if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
2321                            cpt_period >= 0 &&
2322                            (cpt_period == 0 || 
2323                             run_time >= nchkpt*cpt_period*60.0)) &&
2324             gs.set[eglsCHKPT] == 0)
2325         {
2326             gs.sig[eglsCHKPT] = 1;
2327         }
2328   
2329         if (bIterations)
2330         {
2331             gmx_iterate_init(&iterate,bIterations);
2332         }
2333     
2334         /* for iterations, we save these vectors, as we will be redoing the calculations */
2335         if (bIterations && iterate.bIterate) 
2336         {
2337             copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
2338         }
2339         bFirstIterate = TRUE;
2340         while (bFirstIterate || (bIterations && iterate.bIterate))
2341         {
2342             /* We now restore these vectors to redo the calculation with improved extended variables */    
2343             if (bIterations) 
2344             { 
2345                 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
2346             }
2347
2348             /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
2349                so scroll down for that logic */
2350             
2351             /* #########   START SECOND UPDATE STEP ################# */
2352             GMX_MPE_LOG(ev_update_start);
2353             /* Box is changed in update() when we do pressure coupling,
2354              * but we should still use the old box for energy corrections and when
2355              * writing it to the energy file, so it matches the trajectory files for
2356              * the same timestep above. Make a copy in a separate array.
2357              */
2358             copy_mat(state->box,lastbox);
2359
2360             bOK = TRUE;
2361             if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
2362             {
2363                 wallcycle_start(wcycle,ewcUPDATE);
2364                 dvdl = 0;
2365                 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
2366                 if (bTrotter) 
2367                 {
2368                     if (bIterations && iterate.bIterate) 
2369                     {
2370                         if (bFirstIterate) 
2371                         {
2372                             scalevir = 1;
2373                         }
2374                         else 
2375                         {
2376                             /* we use a new value of scalevir to converge the iterations faster */
2377                             scalevir = tracevir/trace(shake_vir);
2378                         }
2379                         msmul(shake_vir,scalevir,shake_vir); 
2380                         m_add(force_vir,shake_vir,total_vir);
2381                         clear_mat(shake_vir);
2382                     }
2383                     trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ3);
2384                 /* We can only do Berendsen coupling after we have summed
2385                  * the kinetic energy or virial. Since the happens
2386                  * in global_state after update, we should only do it at
2387                  * step % nstlist = 1 with bGStatEveryStep=FALSE.
2388                  */
2389                 }
2390                 else 
2391                 {
2392                     update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
2393                     update_pcouple(fplog,step,ir,state,pcoupl_mu,M,wcycle,
2394                                    upd,bInitStep);
2395                 }
2396
2397                 if (bVV)
2398                 {
2399                     /* velocity half-step update */
2400                     update_coords(fplog,step,ir,mdatoms,state,f,
2401                                   fr->bTwinRange && bNStList,fr->f_twin,fcd,
2402                                   ekind,M,wcycle,upd,FALSE,etrtVELOCITY2,
2403                                   cr,nrnb,constr,&top->idef);
2404                 }
2405
2406                 /* Above, initialize just copies ekinh into ekin,
2407                  * it doesn't copy position (for VV),
2408                  * and entire integrator for MD.
2409                  */
2410                 
2411                 if (ir->eI==eiVVAK) 
2412                 {
2413                     copy_rvecn(state->x,cbuf,0,state->natoms);
2414                 }
2415                 
2416                 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2417                               ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2418                 wallcycle_stop(wcycle,ewcUPDATE);
2419
2420                 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2421                                    &top->idef,shake_vir,force_vir,
2422                                    cr,nrnb,wcycle,upd,constr,
2423                                    bInitStep,FALSE,bCalcEnerPres,state->veta);  
2424                 
2425                 if (ir->eI==eiVVAK) 
2426                 {
2427                     /* erase F_EKIN and F_TEMP here? */
2428                     /* just compute the kinetic energy at the half step to perform a trotter step */
2429                     compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2430                                     wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2431                                     constr,NULL,FALSE,lastbox,
2432                                     top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2433                                     cglo_flags | CGLO_TEMPERATURE    
2434                         );
2435                     wallcycle_start(wcycle,ewcUPDATE);
2436                     trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ4);            
2437                     /* now we know the scaling, we can compute the positions again again */
2438                     copy_rvecn(cbuf,state->x,0,state->natoms);
2439
2440                     update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2441                                   ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2442                     wallcycle_stop(wcycle,ewcUPDATE);
2443
2444                     /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
2445                     /* are the small terms in the shake_vir here due
2446                      * to numerical errors, or are they important
2447                      * physically? I'm thinking they are just errors, but not completely sure. 
2448                      * For now, will call without actually constraining, constr=NULL*/
2449                     update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2450                                        &top->idef,tmp_vir,force_vir,
2451                                        cr,nrnb,wcycle,upd,NULL,
2452                                        bInitStep,FALSE,bCalcEnerPres,
2453                                        state->veta);  
2454                 }
2455                 if (!bOK && !bFFscan) 
2456                 {
2457                     gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2458                 }
2459                 
2460                 if (fr->bSepDVDL && fplog && do_log) 
2461                 {
2462                     fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2463                 }
2464                 enerd->term[F_DHDL_CON] += dvdl;
2465             } 
2466             else if (graph) 
2467             {
2468                 /* Need to unshift here */
2469                 unshift_self(graph,state->box,state->x);
2470             }
2471             
2472             GMX_BARRIER(cr->mpi_comm_mygroup);
2473             GMX_MPE_LOG(ev_update_finish);
2474
2475             if (vsite != NULL) 
2476             {
2477                 wallcycle_start(wcycle,ewcVSITECONSTR);
2478                 if (graph != NULL) 
2479                 {
2480                     shift_self(graph,state->box,state->x);
2481                 }
2482                 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
2483                                  top->idef.iparams,top->idef.il,
2484                                  fr->ePBC,fr->bMolPBC,graph,cr,state->box);
2485                 
2486                 if (graph != NULL) 
2487                 {
2488                     unshift_self(graph,state->box,state->x);
2489                 }
2490                 wallcycle_stop(wcycle,ewcVSITECONSTR);
2491             }
2492             
2493             /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
2494             if (ir->nstlist == -1 && bFirstIterate)
2495             {
2496                 gs.sig[eglsNABNSB] = nlh.nabnsb;
2497             }
2498             compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2499                             wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2500                             constr,
2501                             bFirstIterate ? &gs : NULL,(step % gs.nstms == 0),
2502                             lastbox,
2503                             top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2504                             cglo_flags 
2505                             | (!EI_VV(ir->eI) ? CGLO_ENERGY : 0) 
2506                             | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0) 
2507                             | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0) 
2508                             | (bIterations && iterate.bIterate ? CGLO_ITERATE : 0) 
2509                             | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
2510                             | CGLO_CONSTRAINT 
2511                 );
2512             if (ir->nstlist == -1 && bFirstIterate)
2513             {
2514                 nlh.nabnsb = gs.set[eglsNABNSB];
2515                 gs.set[eglsNABNSB] = 0;
2516             }
2517             /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
2518             /* #############  END CALC EKIN AND PRESSURE ################# */
2519         
2520             /* Note: this is OK, but there are some numerical precision issues with using the convergence of
2521                the virial that should probably be addressed eventually. state->veta has better properies,
2522                but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
2523                generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
2524
2525             if (bIterations && 
2526                 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
2527                                trace(shake_vir),&tracevir)) 
2528             {
2529                 break;
2530             }
2531             bFirstIterate = FALSE;
2532         }
2533
2534         update_box(fplog,step,ir,mdatoms,state,graph,f,
2535                    ir->nstlist==-1 ? &nlh.scale_tot : NULL,pcoupl_mu,nrnb,wcycle,upd,bInitStep,FALSE);
2536         
2537         /* ################# END UPDATE STEP 2 ################# */
2538         /* #### We now have r(t+dt) and v(t+dt/2)  ############# */
2539     
2540         /* The coordinates (x) were unshifted in update */
2541         if (bFFscan && (shellfc==NULL || bConverged))
2542         {
2543             if (print_forcefield(fplog,enerd->term,mdatoms->homenr,
2544                                  f,NULL,xcopy,
2545                                  &(top_global->mols),mdatoms->massT,pres))
2546             {
2547                 if (gmx_parallel_env_initialized())
2548                 {
2549                     gmx_finalize();
2550                 }
2551                 fprintf(stderr,"\n");
2552                 exit(0);
2553             }
2554         }
2555         if (!bGStat)
2556         {
2557             /* We will not sum ekinh_old,                                                            
2558              * so signal that we still have to do it.                                                
2559              */
2560             bSumEkinhOld = TRUE;
2561         }
2562         
2563         if (bTCR)
2564         {
2565             /* Only do GCT when the relaxation of shells (minimization) has converged,
2566              * otherwise we might be coupling to bogus energies. 
2567              * In parallel we must always do this, because the other sims might
2568              * update the FF.
2569              */
2570
2571             /* Since this is called with the new coordinates state->x, I assume
2572              * we want the new box state->box too. / EL 20040121
2573              */
2574             do_coupling(fplog,oenv,nfile,fnm,tcr,t,step,enerd->term,fr,
2575                         ir,MASTER(cr),
2576                         mdatoms,&(top->idef),mu_aver,
2577                         top_global->mols.nr,cr,
2578                         state->box,total_vir,pres,
2579                         mu_tot,state->x,f,bConverged);
2580             debug_gmx();
2581         }
2582
2583         /* #########  BEGIN PREPARING EDR OUTPUT  ###########  */
2584         
2585         /* sum up the foreign energy and dhdl terms */
2586         sum_dhdl(enerd,state->lambda,ir);
2587
2588         /* use the directly determined last velocity, not actually the averaged half steps */
2589         if (bTrotter && ir->eI==eiVV) 
2590         {
2591             enerd->term[F_EKIN] = last_ekin;
2592         }
2593         enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
2594         
2595         if (bVV)
2596         {
2597             enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
2598         }
2599         else 
2600         {
2601             enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir,state,&MassQ);
2602         }
2603         /* Check for excessively large energies */
2604         if (bIonize) 
2605         {
2606 #ifdef GMX_DOUBLE
2607             real etot_max = 1e200;
2608 #else
2609             real etot_max = 1e30;
2610 #endif
2611             if (fabs(enerd->term[F_ETOT]) > etot_max) 
2612             {
2613                 fprintf(stderr,"Energy too large (%g), giving up\n",
2614                         enerd->term[F_ETOT]);
2615             }
2616         }
2617         /* #########  END PREPARING EDR OUTPUT  ###########  */
2618         
2619         /* Time for performance */
2620         if (((step % stepout) == 0) || bLastStep) 
2621         {
2622             runtime_upd_proc(runtime);
2623         }
2624         
2625         /* Output stuff */
2626         if (MASTER(cr))
2627         {
2628             gmx_bool do_dr,do_or;
2629             
2630             if (!(bStartingFromCpt && (EI_VV(ir->eI)))) 
2631             {
2632                 if (bNstEner)
2633                 {
2634                     upd_mdebin(mdebin,bDoDHDL, TRUE,
2635                                t,mdatoms->tmass,enerd,state,lastbox,
2636                                shake_vir,force_vir,total_vir,pres,
2637                                ekind,mu_tot,constr);
2638                 }
2639                 else
2640                 {
2641                     upd_mdebin_step(mdebin);
2642                 }
2643                 
2644                 do_dr  = do_per_step(step,ir->nstdisreout);
2645                 do_or  = do_per_step(step,ir->nstorireout);
2646                 
2647                 print_ebin(outf->fp_ene,do_ene,do_dr,do_or,do_log?fplog:NULL,
2648                            step,t,
2649                            eprNORMAL,bCompact,mdebin,fcd,groups,&(ir->opts));
2650             }
2651             if (ir->ePull != epullNO)
2652             {
2653                 pull_print_output(ir->pull,step,t);
2654             }
2655             
2656             if (do_per_step(step,ir->nstlog))
2657             {
2658                 if(fflush(fplog) != 0)
2659                 {
2660                     gmx_fatal(FARGS,"Cannot flush logfile - maybe you are out of quota?");
2661                 }
2662             }
2663         }
2664
2665
2666         /* Remaining runtime */
2667         if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal() ))
2668         {
2669             if (shellfc) 
2670             {
2671                 fprintf(stderr,"\n");
2672             }
2673             print_time(stderr,runtime,step,ir,cr);
2674         }
2675
2676         /* Replica exchange */
2677         bExchanged = FALSE;
2678         if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
2679             do_per_step(step,repl_ex_nst)) 
2680         {
2681             bExchanged = replica_exchange(fplog,cr,repl_ex,
2682                                           state_global,enerd->term,
2683                                           state,step,t);
2684
2685             if (bExchanged && DOMAINDECOMP(cr)) 
2686             {
2687                 dd_partition_system(fplog,step,cr,TRUE,1,
2688                                     state_global,top_global,ir,
2689                                     state,&f,mdatoms,top,fr,
2690                                     vsite,shellfc,constr,
2691                                     nrnb,wcycle,FALSE);
2692             }
2693         }
2694         
2695         bFirstStep = FALSE;
2696         bInitStep = FALSE;
2697         bStartingFromCpt = FALSE;
2698
2699         /* #######  SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
2700         /* Complicated conditional when bGStatEveryStep=FALSE.
2701          * We can not just use bGStat, since then the simulation results
2702          * would depend on nstenergy and nstlog or step_nscheck.
2703          */
2704         if (((state->flags & (1<<estPRES_PREV)) || 
2705              (state->flags & (1<<estSVIR_PREV)) ||
2706              (state->flags & (1<<estFVIR_PREV))) &&
2707             (bGStatEveryStep ||
2708              (ir->nstlist > 0 && step % ir->nstlist == 0) ||
2709              (ir->nstlist < 0 && nlh.nabnsb > 0) ||
2710              (ir->nstlist == 0 && bGStat))) 
2711         {
2712             /* Store the pressure in t_state for pressure coupling
2713              * at the next MD step.
2714              */
2715             if (state->flags & (1<<estPRES_PREV))
2716             {
2717                 copy_mat(pres,state->pres_prev);
2718             }
2719         }
2720         
2721         /* #######  END SET VARIABLES FOR NEXT ITERATION ###### */
2722         
2723         if (bRerunMD) 
2724         {
2725             if (MASTER(cr))
2726             {
2727                 /* read next frame from input trajectory */
2728                 bNotLastFrame = read_next_frame(oenv,status,&rerun_fr);
2729             }
2730
2731             if (PAR(cr))
2732             {
2733                 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
2734             }
2735         }
2736         
2737         if (!bRerunMD || !rerun_fr.bStep)
2738         {
2739             /* increase the MD step number */
2740             step++;
2741             step_rel++;
2742         }
2743         
2744         cycles = wallcycle_stop(wcycle,ewcSTEP);
2745         if (DOMAINDECOMP(cr) && wcycle)
2746         {
2747             dd_cycles_add(cr->dd,cycles,ddCyclStep);
2748         }
2749         
2750         if (step_rel == wcycle_get_reset_counters(wcycle) ||
2751             gs.set[eglsRESETCOUNTERS] != 0)
2752         {
2753             /* Reset all the counters related to performance over the run */
2754             reset_all_counters(fplog,cr,step,&step_rel,ir,wcycle,nrnb,runtime);
2755             wcycle_set_reset_counters(wcycle,-1);
2756             /* Correct max_hours for the elapsed time */
2757             max_hours -= run_time/(60.0*60.0);
2758             bResetCountersHalfMaxH = FALSE;
2759             gs.set[eglsRESETCOUNTERS] = 0;
2760         }
2761     }
2762     /* End of main MD loop */
2763     debug_gmx();
2764     
2765     /* Stop the time */
2766     runtime_end(runtime);
2767     
2768     if (bRerunMD && MASTER(cr))
2769     {
2770         close_trj(status);
2771     }
2772     
2773     if (!(cr->duty & DUTY_PME))
2774     {
2775         /* Tell the PME only node to finish */
2776         gmx_pme_finish(cr);
2777     }
2778     
2779     if (MASTER(cr))
2780     {
2781         if (ir->nstcalcenergy > 0 && !bRerunMD) 
2782         {
2783             print_ebin(outf->fp_ene,FALSE,FALSE,FALSE,fplog,step,t,
2784                        eprAVER,FALSE,mdebin,fcd,groups,&(ir->opts));
2785         }
2786     }
2787
2788     done_mdoutf(outf);
2789
2790     debug_gmx();
2791
2792     if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
2793     {
2794         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)));
2795         fprintf(fplog,"Average number of atoms that crossed the half buffer length: %.1f\n\n",nlh.ab/nlh.nns);
2796     }
2797     
2798     if (shellfc && fplog)
2799     {
2800         fprintf(fplog,"Fraction of iterations that converged:           %.2f %%\n",
2801                 (nconverged*100.0)/step_rel);
2802         fprintf(fplog,"Average number of force evaluations per MD step: %.2f\n\n",
2803                 tcount/step_rel);
2804     }
2805     
2806     if (repl_ex_nst > 0 && MASTER(cr))
2807     {
2808         print_replica_exchange_statistics(fplog,repl_ex);
2809     }
2810     
2811     runtime->nsteps_done = step_rel;
2812     
2813     return 0;
2814 }