Committing another fix!
[gromacs/rigid-bodies.git] / src / kernel / md.c
blob874938a6679c72047bf9345a464a3d639ebedea0
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
3 *
4 * This source code is part of
5 *
6 * G R O M A C S
7 *
8 * GROningen MAchine for Chemical Simulations
9 *
10 * VERSION 3.2.0
11 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13 * Copyright (c) 2001-2004, The GROMACS development team,
14 * check out http://www.gromacs.org for more information.
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * as published by the Free Software Foundation; either version 2
19 * of the License, or (at your option) any later version.
21 * If you want to redistribute modifications, please consider that
22 * scientific software is very special. Version control is crucial -
23 * bugs must be traceable. We will be happy to consider code for
24 * inclusion in the official distribution, but derived work must not
25 * be called official GROMACS. Details are found in the README & COPYING
26 * files - if they are missing, get the official version at www.gromacs.org.
28 * To help us fund GROMACS development, we humbly ask that you cite
29 * the papers on the package - you can find them in the top README file.
31 * For more info, check our website at http://www.gromacs.org
33 * And Hey:
34 * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
40 #include <signal.h>
41 #include <stdlib.h>
42 #include "typedefs.h"
43 #include "smalloc.h"
44 #include "sysstuff.h"
45 #include "vec.h"
46 #include "statutil.h"
47 #include "vcm.h"
48 #include "mdebin.h"
49 #include "nrnb.h"
50 #include "calcmu.h"
51 #include "index.h"
52 #include "vsite.h"
53 #include "update.h"
54 #include "ns.h"
55 #include "trnio.h"
56 #include "xtcio.h"
57 #include "mdrun.h"
58 #include "confio.h"
59 #include "network.h"
60 #include "pull.h"
61 #include "xvgr.h"
62 #include "physics.h"
63 #include "names.h"
64 #include "xmdrun.h"
65 #include "ionize.h"
66 #include "disre.h"
67 #include "orires.h"
68 #include "dihre.h"
69 #include "pppm.h"
70 #include "pme.h"
71 #include "mdatoms.h"
72 #include "repl_ex.h"
73 #include "qmmm.h"
74 #include "mpelogging.h"
75 #include "domdec.h"
76 #include "partdec.h"
77 #include "topsort.h"
78 #include "coulomb.h"
79 #include "constr.h"
80 #include "shellfc.h"
81 #include "compute_io.h"
82 #include "mvdata.h"
83 #include "checkpoint.h"
84 #include "mtop_util.h"
85 #include "genborn.h"
87 #ifdef GMX_LIB_MPI
88 #include <mpi.h>
89 #endif
90 #ifdef GMX_THREADS
91 #include "tmpi.h"
92 #endif
94 #ifdef GMX_FAHCORE
95 #include "corewrap.h"
96 #endif
98 /* The following two variables and the signal_handler function
99 * is used from pme.c as well
101 extern bool bGotTermSignal, bGotUsr1Signal;
103 static RETSIGTYPE signal_handler(int n)
105 switch (n) {
106 case SIGTERM:
107 bGotTermSignal = TRUE;
108 break;
109 #ifdef HAVE_SIGUSR1
110 case SIGUSR1:
111 bGotUsr1Signal = TRUE;
112 break;
113 #endif
117 typedef struct {
118 gmx_integrator_t *func;
119 } gmx_intp_t;
121 /* The array should match the eI array in include/types/enums.h */
122 const gmx_intp_t integrator[eiNR] = { {do_md}, {do_steep}, {do_cg}, {do_md}, {do_md}, {do_nm}, {do_lbfgs}, {do_tpi}, {do_tpi}, {do_md}, {do_md}};
124 /* Static variables for temporary use with the deform option */
125 static int init_step_tpx;
126 static matrix box_tpx;
127 #ifdef GMX_THREADS
128 static tMPI_Thread_mutex_t box_mutex=TMPI_THREAD_MUTEX_INITIALIZER;
129 #endif
132 static void copy_coupling_state(t_state *statea,t_state *stateb,
133 gmx_ekindata_t *ekinda,gmx_ekindata_t *ekindb)
136 /* MRS note -- might be able to get rid of some of the arguments. Look over it when it's all debugged */
138 int i,j,ngtc_eff;
140 stateb->natoms = statea->natoms;
141 stateb->ngtc = statea->ngtc;
142 stateb->veta = statea->veta;
143 if (ekinda)
145 copy_mat(ekinda->ekin,ekindb->ekin);
146 for (i=0; i<stateb->ngtc; i++)
148 ekindb->tcstat[i].T = ekinda->tcstat[i].T;
149 ekindb->tcstat[i].Th = ekinda->tcstat[i].Th;
150 copy_mat(ekinda->tcstat[i].ekinh,ekindb->tcstat[i].ekinh);
151 copy_mat(ekinda->tcstat[i].ekinf,ekindb->tcstat[i].ekinf);
152 ekindb->tcstat[i].ekinscalef_nhc = ekinda->tcstat[i].ekinscalef_nhc;
153 ekindb->tcstat[i].ekinscaleh_nhc = ekinda->tcstat[i].ekinscaleh_nhc;
154 ekindb->tcstat[i].vscale_nhc = ekinda->tcstat[i].vscale_nhc;
157 copy_rvecn(statea->x,stateb->x,0,stateb->natoms);
158 copy_rvecn(statea->v,stateb->v,0,stateb->natoms);
159 copy_mat(statea->box,stateb->box);
160 copy_mat(statea->box_rel,stateb->box_rel);
161 copy_mat(statea->boxv,stateb->boxv);
162 /* need extra term for the barostat */
163 ngtc_eff = stateb->ngtc+1;
165 for (i = 0; i < ngtc_eff; i++)
167 for (j=0; j < NNHCHAIN; j++)
169 stateb->nosehoover_xi[i*NNHCHAIN + j] = statea->nosehoover_xi[i*NNHCHAIN + j];
170 stateb->nosehoover_vxi[i*NNHCHAIN + j] = statea->nosehoover_vxi[i*NNHCHAIN + j];
175 static void compute_globals(FILE *fplog, gmx_global_stat_t gstat, t_commrec *cr, t_inputrec *ir,
176 t_forcerec *fr, gmx_ekindata_t *ekind,
177 t_state *state, t_state *state_global, t_mdatoms *mdatoms,
178 t_nrnb *nrnb, t_vcm *vcm, gmx_wallcycle_t wcycle,
179 gmx_enerdata_t *enerd,tensor force_vir, tensor shake_vir, tensor total_vir,
180 tensor pres, rvec mu_tot, gmx_constr_t constr,
181 real *chkpt,real *terminate, real *terminate_now,
182 int *nabnsb, matrix box, gmx_mtop_t *top_global, real *pcurr,
183 int natoms, bool *bSumEkinhOld, int flags)
186 int i;
187 tensor corr_vir,corr_pres,shakeall_vir;
188 bool bEner,bPres,bTemp, bVV;
189 bool bRerunMD, bEkinAveVel, bStopCM, bGStat, bNEMD, bIterate,
190 bFirstIterate,bReadEkin,bScaleEkin, bConstrain;
191 real ekin,temp,prescorr,enercorr,dvdlcorr;
193 /* translate CGLO flags to booleans */
194 bRerunMD = flags & CGLO_RERUNMD;
195 bEkinAveVel = flags & CGLO_EKINAVEVEL;
196 bStopCM = flags & CGLO_STOPCM;
197 bGStat = flags & CGLO_GSTAT;
198 bNEMD = flags & CGLO_NEMD;
199 bReadEkin = flags & CGLO_READEKIN;
200 bScaleEkin = flags & CGLO_SCALEEKIN;
201 bEner = flags & CGLO_ENERGY;
202 bTemp = flags & CGLO_TEMPERATURE;
203 bPres = flags & CGLO_PRESSURE;
204 bConstrain = flags & CGLO_CONSTRAINT;
205 bIterate = flags & CGLO_ITERATE;
206 bFirstIterate = flags & CGLO_FIRSTITERATE;
208 /* in initalization, it sums the shake virial in vv, and to
209 sums ekinh_old in leapfrog (or if we are calculating ekinh_old for other reasons */
211 bVV = (ir->eI == eiVV);
213 /* ########## Kinetic energy ############## */
215 if (bTemp)
217 /* Non-equilibrium MD: this is parallellized, but only does communication
218 * when there really is NEMD.
221 if (PAR(cr) && (bNEMD))
223 accumulate_u(cr,&(ir->opts),ekind);
225 debug_gmx();
226 if (bReadEkin)
228 restore_ekinstate_from_state(cr,ekind,&state_global->ekinstate);
230 else
232 calc_ke_part(state,&(ir->opts),mdatoms,ekind,nrnb,bEkinAveVel,bIterate);
235 debug_gmx();
237 /* Calculate center of mass velocity if necessary, also parallellized */
238 if (bStopCM && !bRerunMD && bEner)
240 calc_vcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms,
241 state->x,state->v,vcm);
245 if (bTemp || bPres || bEner || bConstrain)
247 if (!bGStat)
249 /* We will not sum ekinh_old,
250 * so signal that we still have to do it.
252 *bSumEkinhOld = TRUE;
254 else
256 if (PAR(cr))
258 GMX_MPE_LOG(ev_global_stat_start);
259 global_stat(fplog,gstat,cr,enerd,force_vir,shake_vir,mu_tot,
260 ir,ekind,constr,vcm,NULL,NULL,terminate,top_global,state,
261 *bSumEkinhOld,flags);
262 GMX_MPE_LOG(ev_global_stat_finish);
265 if (terminate != 0)
267 terminate_now = terminate;
268 terminate = 0;
270 wallcycle_stop(wcycle,ewcMoveE);
271 *bSumEkinhOld = FALSE;
275 if (!bNEMD && debug && bTemp && (vcm->nr > 0))
277 correct_ekin(debug,
278 mdatoms->start,mdatoms->start+mdatoms->homenr,
279 state->v,vcm->group_p[0],
280 mdatoms->massT,mdatoms->tmass,ekind->ekin);
283 if (bEner) {
284 /* Do center of mass motion removal */
285 if (bStopCM && !bRerunMD) /* is this correct? Does it get called too often with this logic? */
287 check_cm_grp(fplog,vcm,ir,1);
288 do_stopcm_grp(fplog,mdatoms->start,mdatoms->homenr,mdatoms->cVCM,
289 state->x,state->v,vcm);
290 inc_nrnb(nrnb,eNR_STOPCM,mdatoms->homenr);
294 if (bTemp)
296 /* Sum the kinetic energies of the groups & calc temp */
297 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,&(enerd->term[F_DKDL]),
298 bEkinAveVel||bReadEkin,bIterate,bScaleEkin);
299 /* three main: VV with AveVel, vv with AveEkin, leap with AveEkin. Leap with AveVel is also
300 an option, but not supported now. Additionally, if we are doing iterations.
301 bCopyHalf: if TRUE, we simply copy the ekinh directly to ekin, multiplying be ekinscale_nhc.
302 bEkinAveVel: If TRUE, we simply multiply ekin by ekinscale.
303 If FALSE, we average ekinh_old and ekinh*ekinscale_nhc.
304 bSaveEkinOld: If TRUE (in the case of iteration = bIterate is TRUE), we don't reset the ekinscale_nhc.
305 If FALSE, we go ahead and erase.
307 enerd->term[F_EKIN] = trace(ekind->ekin);
310 /* ########## Long range energy information ###### */
312 if (bEner || bPres || bConstrain)
314 calc_dispcorr(fplog,ir,fr,0,top_global,box,state->lambda,
315 corr_pres,corr_vir,&prescorr,&enercorr,&dvdlcorr);
318 if (bEner && bFirstIterate)
320 enerd->term[F_DISPCORR] = enercorr;
321 enerd->term[F_EPOT] += enercorr;
322 enerd->term[F_DVDL] += dvdlcorr;
323 if (fr->efep != efepNO) {
324 enerd->dvdl_lin += dvdlcorr;
328 /* ########## Now pressure ############## */
329 if (bPres || bConstrain)
332 m_add(force_vir,shake_vir,total_vir);
334 /* Calculate pressure and apply LR correction if PPPM is used.
335 * Use the box from last timestep since we already called update().
338 enerd->term[F_PRES] = calc_pres(fr->ePBC,ir->nwall,box,ekind->ekin,total_vir,pres,
339 (fr->eeltype==eelPPPM)?enerd->term[F_COUL_RECIP]:0.0);
341 /* Calculate long range corrections to pressure and energy */
342 /* this adds to enerd->term[F_PRES] and enerd->term[F_ETOT],
343 and computes enerd->term[F_DISPCORR]. Also modifies the
344 total_vir and pres tesors */
346 m_add(total_vir,corr_vir,total_vir);
347 m_add(pres,corr_pres,pres);
348 enerd->term[F_PDISPCORR] = prescorr;
349 enerd->term[F_PRES] += prescorr;
350 *pcurr = enerd->term[F_PRES];
351 /* calculate temperature using virial */
352 enerd->term[F_VTEMP] = calc_temp(trace(total_vir),ir->opts.nrdf[0]);
357 #ifdef GMX_THREADS
358 struct mdrunner_arglist
360 FILE *fplog;
361 t_commrec *cr;
362 int nfile;
363 const t_filenm *fnm;
364 output_env_t oenv;
365 bool bVerbose;
366 bool bCompact;
367 int nstglobalcomm;
368 ivec ddxyz;
369 int dd_node_order;
370 real rdd;
371 real rconstr;
372 const char *dddlb_opt;
373 real dlb_scale;
374 const char *ddcsx;
375 const char *ddcsy;
376 const char *ddcsz;
377 int nstepout;
378 int nmultisim;
379 int repl_ex_nst;
380 int repl_ex_seed;
381 real pforce;
382 real cpt_period;
383 real max_hours;
384 unsigned long Flags;
385 int ret; /* return value */
389 static void mdrunner_start_fn(void *arg)
391 struct mdrunner_arglist *mda=(struct mdrunner_arglist*)arg;
392 struct mdrunner_arglist mc=*mda; /* copy the arg list to make sure
393 that it's thread-local. This doesn't
394 copy pointed-to items, of course,
395 but those are all const. */
396 t_commrec *cr; /* we need a local version of this */
397 FILE *fplog=NULL;
398 t_filenm *fnm=dup_tfn(mc.nfile, mc.fnm);
400 cr=init_par_threads(mc.cr);
401 if (MASTER(cr))
403 fplog=mc.fplog;
407 mda->ret=mdrunner(fplog, cr, mc.nfile, mc.fnm, mc.oenv, mc.bVerbose,
408 mc.bCompact, mc.nstglobalcomm,
409 mc.ddxyz, mc.dd_node_order, mc.rdd,
410 mc.rconstr, mc.dddlb_opt, mc.dlb_scale,
411 mc.ddcsx, mc.ddcsy, mc.ddcsz, mc.nstepout, mc.nmultisim,
412 mc.repl_ex_nst, mc.repl_ex_seed, mc.pforce,
413 mc.cpt_period, mc.max_hours, mc.Flags);
416 #endif
418 int mdrunner_threads(int nthreads,
419 FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
420 const output_env_t oenv, bool bVerbose,bool bCompact,
421 int nstglobalcomm,
422 ivec ddxyz,int dd_node_order,real rdd,real rconstr,
423 const char *dddlb_opt,real dlb_scale,
424 const char *ddcsx,const char *ddcsy,const char *ddcsz,
425 int nstepout,int nmultisim,int repl_ex_nst,
426 int repl_ex_seed, real pforce,real cpt_period,
427 real max_hours, unsigned long Flags)
429 int ret;
430 /* first check whether we even need to start tMPI */
431 if (nthreads < 2)
433 ret=mdrunner(fplog, cr, nfile, fnm, oenv, bVerbose, bCompact,
434 nstglobalcomm,
435 ddxyz, dd_node_order, rdd, rconstr, dddlb_opt, dlb_scale,
436 ddcsx, ddcsy, ddcsz, nstepout, nmultisim, repl_ex_nst,
437 repl_ex_seed, pforce, cpt_period, max_hours, Flags);
439 else
441 #ifdef GMX_THREADS
442 struct mdrunner_arglist mda;
443 /* fill the data structure to pass as void pointer to thread start fn */
444 mda.fplog=fplog;
445 mda.cr=cr;
446 mda.nfile=nfile;
447 mda.fnm=fnm;
448 mda.oenv=oenv;
449 mda.bVerbose=bVerbose;
450 mda.bCompact=bCompact;
451 mda.nstglobalcomm=nstglobalcomm;
452 mda.ddxyz[XX]=ddxyz[XX];
453 mda.ddxyz[YY]=ddxyz[YY];
454 mda.ddxyz[ZZ]=ddxyz[ZZ];
455 mda.dd_node_order=dd_node_order;
456 mda.rdd=rdd;
457 mda.rconstr=rconstr;
458 mda.dddlb_opt=dddlb_opt;
459 mda.dlb_scale=dlb_scale;
460 mda.ddcsx=ddcsx;
461 mda.ddcsy=ddcsy;
462 mda.ddcsz=ddcsz;
463 mda.nstepout=nstepout;
464 mda.nmultisim=nmultisim;
465 mda.repl_ex_nst=repl_ex_nst;
466 mda.repl_ex_seed=repl_ex_seed;
467 mda.pforce=pforce;
468 mda.cpt_period=cpt_period;
469 mda.max_hours=max_hours;
470 mda.Flags=Flags;
472 fprintf(stderr, "Starting %d threads\n",nthreads);
473 fflush(stderr);
474 tMPI_Init_fn(nthreads, mdrunner_start_fn, (void*)(&mda) );
475 ret=mda.ret;
476 #else
477 ret=-1;
478 gmx_comm("Multiple threads requested but not compiled with threads");
479 #endif
481 return ret;
485 int mdrunner(FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
486 const output_env_t oenv, bool bVerbose,bool bCompact,
487 int nstglobalcomm,
488 ivec ddxyz,int dd_node_order,real rdd,real rconstr,
489 const char *dddlb_opt,real dlb_scale,
490 const char *ddcsx,const char *ddcsy,const char *ddcsz,
491 int nstepout,int nmultisim,int repl_ex_nst,int repl_ex_seed,
492 real pforce,real cpt_period,real max_hours,
493 unsigned long Flags)
495 double nodetime=0,realtime;
496 t_inputrec *inputrec;
497 t_state *state=NULL;
498 matrix box;
499 gmx_ddbox_t ddbox;
500 int npme_major;
501 real tmpr1,tmpr2;
502 t_nrnb *nrnb;
503 gmx_mtop_t *mtop=NULL;
504 t_mdatoms *mdatoms=NULL;
505 t_forcerec *fr=NULL;
506 t_fcdata *fcd=NULL;
507 real ewaldcoeff=0;
508 gmx_pme_t *pmedata=NULL;
509 gmx_vsite_t *vsite=NULL;
510 gmx_constr_t constr;
511 int i,m,nChargePerturbed=-1,status,nalloc;
512 char *gro;
513 gmx_wallcycle_t wcycle;
514 bool bReadRNG,bReadEkin;
515 int list;
516 gmx_runtime_t runtime;
517 int rc;
518 gmx_large_int_t reset_counters;
519 gmx_edsam_t ed;
521 /* Essential dynamics */
522 if (opt2bSet("-ei",nfile,fnm))
524 /* Open input and output files, allocate space for ED data structure */
525 ed = ed_open(nfile,fnm,cr);
527 else
528 ed=NULL;
530 snew(inputrec,1);
531 snew(mtop,1);
533 if (bVerbose && SIMMASTER(cr))
535 fprintf(stderr,"Getting Loaded...\n");
538 if (Flags & MD_APPENDFILES)
540 fplog = NULL;
543 if (PAR(cr))
545 /* The master thread on the master node reads from disk,
546 * then distributes everything to the other processors.
549 list = (SIMMASTER(cr) && !(Flags & MD_APPENDFILES)) ? (LIST_SCALARS | LIST_INPUTREC) : 0;
551 snew(state,1);
552 init_parallel(fplog, opt2fn_master("-s",nfile,fnm,cr),cr,
553 inputrec,mtop,state,list);
556 else
558 /* Read a file for a single processor */
559 snew(state,1);
560 init_single(fplog,inputrec,ftp2fn(efTPX,nfile,fnm),mtop,state);
562 if (!EEL_PME(inputrec->coulombtype) || (Flags & MD_PARTDEC))
564 cr->npmenodes = 0;
567 #ifdef GMX_FAHCORE
568 fcRegisterSteps(inputrec->nsteps,inputrec->init_step);
569 #endif
571 /* NMR restraints must be initialized before load_checkpoint,
572 * since with time averaging the history is added to t_state.
573 * For proper consistency check we therefore need to extend
574 * t_state here.
575 * So the PME-only nodes (if present) will also initialize
576 * the distance restraints.
578 snew(fcd,1);
580 /* This needs to be called before read_checkpoint to extend the state */
581 init_disres(fplog,mtop,inputrec,cr,Flags & MD_PARTDEC,fcd,state);
583 if (gmx_mtop_ftype_count(mtop,F_ORIRES) > 0)
585 if (PAR(cr) && !(Flags & MD_PARTDEC))
587 gmx_fatal(FARGS,"Orientation restraints do not work (yet) with domain decomposition, use particle decomposition (mdrun option -pd)");
589 /* Orientation restraints */
590 if (MASTER(cr))
592 init_orires(fplog,mtop,state->x,inputrec,cr->ms,&(fcd->orires),
593 state);
597 if (DEFORM(*inputrec))
599 /* Store the deform reference box before reading the checkpoint */
600 if (SIMMASTER(cr))
602 copy_mat(state->box,box);
604 if (PAR(cr))
606 gmx_bcast(sizeof(box),box,cr);
608 /* Because we do not have the update struct available yet
609 * in which the reference values should be stored,
610 * we store them temporarily in static variables.
611 * This should be thread safe, since they are only written once
612 * and with identical values.
614 #ifdef GMX_THREADS
615 tMPI_Thread_mutex_lock(&box_mutex);
616 #endif
617 init_step_tpx = inputrec->init_step;
618 copy_mat(box,box_tpx);
619 #ifdef GMX_THREADS
620 tMPI_Thread_mutex_unlock(&box_mutex);
621 #endif
624 if (opt2bSet("-cpi",nfile,fnm))
626 /* Check if checkpoint file exists before doing continuation.
627 * This way we can use identical input options for the first and subsequent runs...
629 if( gmx_fexist_master(opt2fn_master("-cpi",nfile,fnm,cr),cr) )
631 load_checkpoint(opt2fn_master("-cpi",nfile,fnm,cr),fplog,
632 cr,Flags & MD_PARTDEC,ddxyz,
633 inputrec,state,&bReadRNG,&bReadEkin,
634 (Flags & MD_APPENDFILES));
636 if (bReadRNG)
638 Flags |= MD_READ_RNG;
640 if (bReadEkin)
642 Flags |= MD_READ_EKIN;
647 if (MASTER(cr) && (Flags & MD_APPENDFILES))
649 fplog = gmx_log_open(ftp2fn(efLOG,nfile,fnm),cr,!(Flags & MD_SEPPOT),
650 Flags);
653 if (SIMMASTER(cr))
655 copy_mat(state->box,box);
658 if (PAR(cr))
660 gmx_bcast(sizeof(box),box,cr);
663 if (bVerbose && SIMMASTER(cr))
665 fprintf(stderr,"Loaded with Money\n\n");
668 if (PAR(cr) && !((Flags & MD_PARTDEC) || EI_TPI(inputrec->eI)))
670 cr->dd = init_domain_decomposition(fplog,cr,Flags,ddxyz,rdd,rconstr,
671 dddlb_opt,dlb_scale,
672 ddcsx,ddcsy,ddcsz,
673 mtop,inputrec,
674 box,state->x,
675 &ddbox,&npme_major);
677 make_dd_communicators(fplog,cr,dd_node_order);
679 /* Set overallocation to avoid frequent reallocation of arrays */
680 set_over_alloc_dd(TRUE);
682 else
684 cr->duty = (DUTY_PP | DUTY_PME);
685 npme_major = cr->nnodes;
687 if (inputrec->ePBC == epbcSCREW)
689 gmx_fatal(FARGS,
690 "pbc=%s is only implemented with domain decomposition",
691 epbc_names[inputrec->ePBC]);
695 if (PAR(cr))
697 /* After possible communicator splitting in make_dd_communicators.
698 * we can set up the intra/inter node communication.
700 gmx_setup_nodecomm(fplog,cr);
703 wcycle = wallcycle_init(fplog,cr);
704 if (PAR(cr))
706 /* Master synchronizes its value of reset_counters with all nodes
707 * including PME only nodes */
708 reset_counters = wcycle_get_reset_counters(wcycle);
709 gmx_bcast_sim(sizeof(reset_counters),&reset_counters,cr);
710 wcycle_set_reset_counters(wcycle, reset_counters);
714 snew(nrnb,1);
715 if (cr->duty & DUTY_PP)
717 /* For domain decomposition we allocate dynamically
718 * in dd_partition_system.
720 if (DOMAINDECOMP(cr))
722 bcast_state_setup(cr,state);
724 else
726 if (PAR(cr))
728 if (!MASTER(cr))
730 snew(state,1);
732 bcast_state(cr,state,TRUE);
736 /* Dihedral Restraints */
737 if (gmx_mtop_ftype_count(mtop,F_DIHRES) > 0)
739 init_dihres(fplog,mtop,inputrec,fcd);
742 /* Initiate forcerecord */
743 fr = mk_forcerec();
744 init_forcerec(fplog,oenv,fr,fcd,inputrec,mtop,cr,box,FALSE,
745 opt2fn("-table",nfile,fnm),
746 opt2fn("-tablep",nfile,fnm),
747 opt2fn("-tableb",nfile,fnm),FALSE,pforce);
749 /* version for PCA_NOT_READ_NODE (see md.c) */
750 /*init_forcerec(fplog,fr,fcd,inputrec,mtop,cr,box,FALSE,
751 "nofile","nofile","nofile",FALSE,pforce);
753 fr->bSepDVDL = ((Flags & MD_SEPPOT) == MD_SEPPOT);
755 /* Initialize QM-MM */
756 if(fr->bQMMM)
758 init_QMMMrec(cr,box,mtop,inputrec,fr);
761 /* Initialize the mdatoms structure.
762 * mdatoms is not filled with atom data,
763 * as this can not be done now with domain decomposition.
765 mdatoms = init_mdatoms(fplog,mtop,inputrec->efep!=efepNO);
767 /* Initialize the virtual site communication */
768 vsite = init_vsite(mtop,cr);
770 calc_shifts(box,fr->shift_vec);
772 /* With periodic molecules the charge groups should be whole at start up
773 * and the virtual sites should not be far from their proper positions.
775 if (!inputrec->bContinuation && MASTER(cr) &&
776 !(inputrec->ePBC != epbcNONE && inputrec->bPeriodicMols))
778 /* Make molecules whole at start of run */
779 if (fr->ePBC != epbcNONE)
781 do_pbc_first_mtop(fplog,inputrec->ePBC,box,mtop,state->x);
783 if (vsite)
785 /* Correct initial vsite positions are required
786 * for the initial distribution in the domain decomposition
787 * and for the initial shell prediction.
789 construct_vsites_mtop(fplog,vsite,mtop,state->x);
793 /* Initiate PPPM if necessary */
794 if (fr->eeltype == eelPPPM)
796 if (mdatoms->nChargePerturbed)
798 gmx_fatal(FARGS,"Free energy with %s is not implemented",
799 eel_names[fr->eeltype]);
801 status = gmx_pppm_init(fplog,cr,oenv,FALSE,TRUE,box,
802 getenv("GMXGHAT"),inputrec, (Flags & MD_REPRODUCIBLE));
803 if (status != 0)
805 gmx_fatal(FARGS,"Error %d initializing PPPM",status);
809 if (EEL_PME(fr->eeltype))
811 ewaldcoeff = fr->ewaldcoeff;
812 pmedata = &fr->pmedata;
814 else
816 pmedata = NULL;
819 else
821 /* This is a PME only node */
823 /* We don't need the state */
824 done_state(state);
826 ewaldcoeff = calc_ewaldcoeff(inputrec->rcoulomb, inputrec->ewald_rtol);
827 snew(pmedata,1);
830 /* Initiate PME if necessary,
831 * either on all nodes or on dedicated PME nodes only. */
832 if (EEL_PME(inputrec->coulombtype))
834 if (mdatoms)
836 nChargePerturbed = mdatoms->nChargePerturbed;
838 if (cr->npmenodes > 0)
840 /* The PME only nodes need to know nChargePerturbed */
841 gmx_bcast_sim(sizeof(nChargePerturbed),&nChargePerturbed,cr);
843 if (cr->duty & DUTY_PME)
845 status = gmx_pme_init(pmedata,cr,npme_major,inputrec,
846 mtop ? mtop->natoms : 0,nChargePerturbed,
847 (Flags & MD_REPRODUCIBLE));
848 if (status != 0)
850 gmx_fatal(FARGS,"Error %d initializing PME",status);
856 if (integrator[inputrec->eI].func == do_md)
858 /* Turn on signal handling on all nodes */
860 * (A user signal from the PME nodes (if any)
861 * is communicated to the PP nodes.
863 if (getenv("GMX_NO_TERM") == NULL)
865 if (debug)
867 fprintf(debug,"Installing signal handler for SIGTERM\n");
869 signal(SIGTERM,signal_handler);
871 #ifdef HAVE_SIGUSR1
872 if (getenv("GMX_NO_USR1") == NULL)
874 if (debug)
876 fprintf(debug,"Installing signal handler for SIGUSR1\n");
878 signal(SIGUSR1,signal_handler);
880 #endif
883 if (cr->duty & DUTY_PP)
885 if (inputrec->ePull != epullNO)
887 /* Initialize pull code */
888 init_pull(fplog,inputrec,nfile,fnm,mtop,cr,oenv,
889 EI_DYNAMICS(inputrec->eI) && MASTER(cr),Flags);
892 constr = init_constraints(fplog,mtop,inputrec,ed,state,cr);
894 if (DOMAINDECOMP(cr))
896 dd_init_bondeds(fplog,cr->dd,mtop,vsite,constr,inputrec,
897 Flags & MD_DDBONDCHECK,fr->cginfo_mb);
899 set_dd_parameters(fplog,cr->dd,dlb_scale,inputrec,fr,&ddbox);
901 setup_dd_grid(fplog,cr->dd);
904 /* Now do whatever the user wants us to do (how flexible...) */
905 integrator[inputrec->eI].func(fplog,cr,nfile,fnm,
906 oenv,bVerbose,bCompact,
907 nstglobalcomm,
908 vsite,constr,
909 nstepout,inputrec,mtop,
910 fcd,state,
911 mdatoms,nrnb,wcycle,ed,fr,
912 repl_ex_nst,repl_ex_seed,
913 cpt_period,max_hours,
914 Flags,
915 &runtime);
917 if (inputrec->ePull != epullNO)
919 finish_pull(fplog,inputrec->pull);
922 else
924 /* do PME only */
925 gmx_pmeonly(*pmedata,cr,nrnb,wcycle,ewaldcoeff,FALSE,inputrec);
928 if (EI_DYNAMICS(inputrec->eI) || EI_TPI(inputrec->eI))
930 /* Some timing stats */
931 if (MASTER(cr))
933 if (runtime.proc == 0)
935 runtime.proc = runtime.real;
938 else
940 runtime.real = 0;
944 wallcycle_stop(wcycle,ewcRUN);
946 /* Finish up, write some stuff
947 * if rerunMD, don't write last frame again
949 finish_run(fplog,cr,ftp2fn(efSTO,nfile,fnm),
950 inputrec,nrnb,wcycle,&runtime,
951 EI_DYNAMICS(inputrec->eI) && !MULTISIM(cr));
953 /* Does what it says */
954 print_date_and_time(fplog,cr->nodeid,"Finished mdrun",&runtime);
956 /* Close logfile already here if we were appending to it */
957 if (MASTER(cr) && (Flags & MD_APPENDFILES))
959 gmx_log_close(fplog);
962 if(bGotTermSignal)
964 rc = 1;
966 else if(bGotUsr1Signal)
968 rc = 2;
970 else
972 rc = 0;
975 return rc;
978 static void md_print_warning(const t_commrec *cr,FILE *fplog,const char *buf)
980 if (MASTER(cr))
982 fprintf(stderr,"\n%s\n",buf);
984 if (fplog)
986 fprintf(fplog,"\n%s\n",buf);
990 static bool done_iterating(const t_commrec *cr,FILE *fplog, bool *bFirstIterate, bool *bIterate, real fom, real *newf, int n)
995 /* monitor convergence, and use a secant search to propose new
996 values.
997 x_{i} - x_{i-1}
998 The secant method computes x_{i+1} = x_{i} - f(x_{i}) * ---------------------
999 f(x_{i}) - f(x_{i-1})
1001 The function we are trying to zero is fom-x, where fom is the
1002 "figure of merit" which is the pressure (or the veta value) we
1003 would get by putting in an old value of the pressure or veta into
1004 the incrementor function for the step or half step. I have
1005 verified that this gives the same answer as self consistent
1006 iteration, usually in many fewer steps, especially for small tau_p.
1008 We could possibly eliminate an iteration with proper use
1009 of the value from the previous step, but that would take a bit
1010 more bookkeeping, especially for veta, since tests indicate the
1011 function of veta on the last step is not sufficiently close to
1012 guarantee convergence this step. This is
1013 good enough for now. On my tests, I could use tau_p down to
1014 0.02, which is smaller that would ever be necessary in
1015 practice. Generally, 3-5 iterations will be sufficient */
1017 /* Definitions for convergence. Could be optimized . . . */
1018 #ifdef GMX_DOUBLE
1019 #define CONVERGEITER 0.000000001
1020 #else
1021 #define CONVERGEITER 0.0001
1022 #endif
1023 #define MAXITERCONST 200
1025 /* used to escape out of cyclic traps because of limited numberical precision */
1026 #define CYCLEMAX 20
1027 #define FALLBACK 1000
1029 static real f,fprev,x,xprev;
1030 static int iter_i;
1031 static real allrelerr[MAXITERCONST+2];
1032 double relerr,xmin;
1033 char buf[256];
1034 int i;
1035 bool incycle;
1037 if (*bFirstIterate)
1039 *bFirstIterate = FALSE;
1040 iter_i = 0;
1041 x = fom;
1042 f = fom-x;
1043 *newf = fom;
1045 else
1047 f = fom-x; /* we want to zero this difference */
1048 if ((iter_i > 1) && (iter_i < MAXITERCONST))
1050 if (f==fprev)
1052 *newf = f;
1054 else
1056 *newf = x - (x-xprev)*(f)/(f-fprev);
1059 else
1061 /* just use self-consistent iteration the first step to initialize, or
1062 if it's not converging (which happens occasionally -- need to investigate why) */
1063 *newf = fom;
1066 /* Consider a slight shortcut allowing us to exit one sooner -- we check the
1067 difference between the closest of x and xprev to the new
1068 value. To be 100% certain, we should check the difference between
1069 the last result, and the previous result, or
1071 relerr = (fabs((x-xprev)/fom));
1073 but this is pretty much never necessary under typical conditions.
1074 Checking numerically, it seems to lead to almost exactly the same
1075 trajectories, but there are small differences out a few decimal
1076 places in the pressure, and eventually in the v_eta, but it could
1077 save an interation.
1079 if (fabs(*newf-x) < fabs(*newf - xprev)) { xmin = x;} else { xmin = xprev;}
1080 relerr = (fabs((*newf-xmin) / *newf));
1083 relerr = (fabs((f-fprev)/fom));
1085 allrelerr[iter_i] = relerr;
1087 if (iter_i > 0)
1089 if (debug)
1091 fprintf(debug,"Iterating NPT constraints #%i: %6i %20.12f%14.6g%20.12f\n",n,iter_i,fom,relerr,*newf);
1094 if ((relerr < CONVERGEITER) || (fom==0))
1096 *bIterate = FALSE;
1097 if (debug)
1099 fprintf(debug,"Iterating NPT constraints #%i: CONVERGED\n",n);
1101 return TRUE;
1103 if (iter_i > MAXITERCONST)
1105 incycle = FALSE;
1106 for (i=0;i<CYCLEMAX;i++) {
1107 if (allrelerr[(MAXITERCONST-2*CYCLEMAX)-i] == allrelerr[iter_i-1]) {
1108 incycle = TRUE;
1109 if (relerr > CONVERGEITER*FALLBACK) {incycle = FALSE; break;}
1113 if (incycle) {
1114 /* we are trapped in a numerical attractor, and can't converge any more, and are close to the final result.
1115 Better to give up here and proceed with a warning than have the simulation die.
1117 sprintf(buf,"numerical convergence issues with NPT, relative error only %10.5g, continuing\n",relerr);
1118 md_print_warning(cr,fplog,buf);
1119 return TRUE;
1120 } else {
1121 gmx_fatal(FARGS,"Could not converge NPT constraints\n");
1126 xprev = x;
1127 x = *newf;
1128 fprev = f;
1129 iter_i++;
1131 return FALSE;
1134 static void check_nst_param(FILE *fplog,t_commrec *cr,
1135 const char *desc_nst,int nst,
1136 const char *desc_p,int *p)
1138 char buf[STRLEN];
1140 if (*p > 0 && *p % nst != 0)
1142 /* Round up to the next multiple of nst */
1143 *p = ((*p)/nst + 1)*nst;
1144 sprintf(buf,"NOTE: %s changes %s to %d\n",desc_nst,desc_p,*p);
1145 md_print_warning(cr,fplog,buf);
1149 static void reset_all_counters(FILE *fplog,t_commrec *cr,
1150 gmx_large_int_t step,
1151 gmx_large_int_t *step_rel,t_inputrec *ir,
1152 gmx_wallcycle_t wcycle,t_nrnb *nrnb,
1153 gmx_runtime_t *runtime)
1155 char buf[STRLEN],sbuf[22];
1157 /* Reset all the counters related to performance over the run */
1158 sprintf(buf,"Step %s: resetting all time and cycle counters\n",
1159 gmx_step_str(step,sbuf));
1160 md_print_warning(cr,fplog,buf);
1162 wallcycle_stop(wcycle,ewcRUN);
1163 wallcycle_reset_all(wcycle);
1164 if (DOMAINDECOMP(cr))
1166 reset_dd_statistics_counters(cr->dd);
1168 init_nrnb(nrnb);
1169 ir->init_step += *step_rel;
1170 ir->nsteps -= *step_rel;
1171 *step_rel = 0;
1172 wallcycle_start(wcycle,ewcRUN);
1173 runtime_start(runtime);
1174 print_date_and_time(fplog,cr->nodeid,"Restarted time",runtime);
1177 static int check_nstglobalcomm(FILE *fplog,t_commrec *cr,
1178 int nstglobalcomm,t_inputrec *ir)
1180 char buf[STRLEN];
1182 if (!EI_DYNAMICS(ir->eI))
1184 nstglobalcomm = 1;
1187 if (nstglobalcomm == -1)
1189 if (ir->nstcalcenergy == 0 && ir->nstlist == 0)
1191 nstglobalcomm = 10;
1192 if (ir->nstenergy > 0 && ir->nstenergy < nstglobalcomm)
1194 nstglobalcomm = ir->nstenergy;
1197 else
1199 /* We assume that if nstcalcenergy > nstlist,
1200 * nstcalcenergy is a multiple of nstlist.
1202 if (ir->nstcalcenergy == 0 ||
1203 (ir->nstlist > 0 && ir->nstlist < ir->nstcalcenergy))
1205 nstglobalcomm = ir->nstlist;
1207 else
1209 nstglobalcomm = ir->nstcalcenergy;
1213 else
1215 if (ir->nstlist > 0 &&
1216 nstglobalcomm > ir->nstlist && nstglobalcomm % ir->nstlist != 0)
1218 nstglobalcomm = (nstglobalcomm / ir->nstlist)*ir->nstlist;
1219 sprintf(buf,"WARNING: nstglobalcomm is larger than nstlist, but not a multiple, setting it to %d\n",nstglobalcomm);
1220 md_print_warning(cr,fplog,buf);
1222 if (nstglobalcomm > ir->nstcalcenergy)
1224 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
1225 "nstcalcenergy",&ir->nstcalcenergy);
1228 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
1229 "nstenergy",&ir->nstenergy);
1231 check_nst_param(fplog,cr,"-gcom",nstglobalcomm,
1232 "nstlog",&ir->nstlog);
1235 if (ir->comm_mode != ecmNO && ir->nstcomm < nstglobalcomm)
1237 sprintf(buf,"WARNING: Changing nstcomm from %d to %d\n",
1238 ir->nstcomm,nstglobalcomm);
1239 md_print_warning(cr,fplog,buf);
1240 ir->nstcomm = nstglobalcomm;
1243 return nstglobalcomm;
1246 static void check_ir_old_tpx_versions(t_commrec *cr,FILE *fplog,
1247 t_inputrec *ir,gmx_mtop_t *mtop)
1249 /* Check required for old tpx files */
1250 if (IR_TWINRANGE(*ir) && ir->nstlist > 1 &&
1251 ir->nstcalcenergy % ir->nstlist != 0)
1253 md_print_warning(cr,fplog,"Old tpr file with twin-range settings: modifiying energy calculation and/or T/P-coupling frequencies");
1255 if (gmx_mtop_ftype_count(mtop,F_CONSTR) +
1256 gmx_mtop_ftype_count(mtop,F_CONSTRNC) > 0 &&
1257 ir->eConstrAlg == econtSHAKE)
1259 md_print_warning(cr,fplog,"With twin-range cut-off's and SHAKE the virial and pressure are incorrect");
1260 if (ir->epc != epcNO)
1262 gmx_fatal(FARGS,"Can not do pressure coupling with twin-range cut-off's and SHAKE");
1265 check_nst_param(fplog,cr,"nstlist",ir->nstlist,
1266 "nstcalcenergy",&ir->nstcalcenergy);
1268 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
1269 "nstenergy",&ir->nstenergy);
1270 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
1271 "nstlog",&ir->nstlog);
1272 if (ir->efep != efepNO)
1274 check_nst_param(fplog,cr,"nstdhdl",ir->nstdhdl,
1275 "nstenergy",&ir->nstenergy);
1279 typedef struct {
1280 bool bGStatEveryStep;
1281 gmx_large_int_t step_ns;
1282 gmx_large_int_t step_nscheck;
1283 gmx_large_int_t nns;
1284 matrix scale_tot;
1285 int nabnsb;
1286 double s1;
1287 double s2;
1288 double ab;
1289 double lt_runav;
1290 double lt_runav2;
1291 } gmx_nlheur_t;
1293 static void reset_nlistheuristics(gmx_nlheur_t *nlh,gmx_large_int_t step)
1295 nlh->lt_runav = 0;
1296 nlh->lt_runav2 = 0;
1297 nlh->step_nscheck = step;
1300 static void init_nlistheuristics(gmx_nlheur_t *nlh,
1301 bool bGStatEveryStep,gmx_large_int_t step)
1303 nlh->bGStatEveryStep = bGStatEveryStep;
1304 nlh->nns = 0;
1305 nlh->nabnsb = 0;
1306 nlh->s1 = 0;
1307 nlh->s2 = 0;
1308 nlh->ab = 0;
1310 reset_nlistheuristics(nlh,step);
1313 static void update_nliststatistics(gmx_nlheur_t *nlh,gmx_large_int_t step)
1315 gmx_large_int_t nl_lt;
1316 char sbuf[22],sbuf2[22];
1318 /* Determine the neighbor list life time */
1319 nl_lt = step - nlh->step_ns;
1320 if (debug)
1322 fprintf(debug,"%d atoms beyond ns buffer, updating neighbor list after %s steps\n",nlh->nabnsb,gmx_step_str(nl_lt,sbuf));
1324 nlh->nns++;
1325 nlh->s1 += nl_lt;
1326 nlh->s2 += nl_lt*nl_lt;
1327 nlh->ab += nlh->nabnsb;
1328 if (nlh->lt_runav == 0)
1330 nlh->lt_runav = nl_lt;
1331 /* Initialize the fluctuation average
1332 * such that at startup we check after 0 steps.
1334 nlh->lt_runav2 = sqr(nl_lt/2.0);
1336 /* Running average with 0.9 gives an exp. history of 9.5 */
1337 nlh->lt_runav2 = 0.9*nlh->lt_runav2 + 0.1*sqr(nlh->lt_runav - nl_lt);
1338 nlh->lt_runav = 0.9*nlh->lt_runav + 0.1*nl_lt;
1339 if (nlh->bGStatEveryStep)
1341 /* Always check the nlist validity */
1342 nlh->step_nscheck = step;
1344 else
1346 /* We check after: <life time> - 2*sigma
1347 * The factor 2 is quite conservative,
1348 * but we assume that with nstlist=-1 the user
1349 * prefers exact integration over performance.
1351 nlh->step_nscheck = step
1352 + (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)) - 1;
1354 if (debug)
1356 fprintf(debug,"nlist life time %s run av. %4.1f sig %3.1f check %s check with -gcom %d\n",
1357 gmx_step_str(nl_lt,sbuf),nlh->lt_runav,sqrt(nlh->lt_runav2),
1358 gmx_step_str(nlh->step_nscheck-step+1,sbuf2),
1359 (int)(nlh->lt_runav - 2.0*sqrt(nlh->lt_runav2)));
1363 static void set_nlistheuristics(gmx_nlheur_t *nlh,bool bReset,gmx_large_int_t step)
1365 int d;
1367 if (bReset)
1369 reset_nlistheuristics(nlh,step);
1371 else
1373 update_nliststatistics(nlh,step);
1376 nlh->step_ns = step;
1377 /* Initialize the cumulative coordinate scaling matrix */
1378 clear_mat(nlh->scale_tot);
1379 for(d=0; d<DIM; d++)
1381 nlh->scale_tot[d][d] = 1.0;
1385 double do_md(FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
1386 const output_env_t oenv, bool bVerbose,bool bCompact,
1387 int nstglobalcomm,
1388 gmx_vsite_t *vsite,gmx_constr_t constr,
1389 int stepout,t_inputrec *ir,
1390 gmx_mtop_t *top_global,
1391 t_fcdata *fcd,
1392 t_state *state_global,
1393 t_mdatoms *mdatoms,
1394 t_nrnb *nrnb,gmx_wallcycle_t wcycle,
1395 gmx_edsam_t ed,t_forcerec *fr,
1396 int repl_ex_nst,int repl_ex_seed,
1397 real cpt_period,real max_hours,
1398 unsigned long Flags,
1399 gmx_runtime_t *runtime)
1401 int fp_trn=0,fp_xtc=0;
1402 ener_file_t fp_ene=NULL;
1403 gmx_large_int_t step,step_rel;
1404 const char *fn_cpt;
1405 FILE *fp_dhdl=NULL,*fp_field=NULL;
1406 double run_time;
1407 double t,t0,lam0;
1408 bool bGStatEveryStep,bGStat,bNstEner,bCalcPres,bCalcEner;
1409 bool bNS,bNStList,bSimAnn,bStopCM,bRerunMD,bNotLastFrame=FALSE,
1410 bFirstStep,bStateFromTPX,bInitStep,bLastStep,bEkinAveVel,
1411 bBornRadii,bStartingFromCpt,bVVAveVel,bVVAveEkin;
1412 bool bDoDHDL=FALSE;
1413 bool bNEMD,do_ene,do_log,do_verbose,bRerunWarnNoV=TRUE,
1414 bForceUpdate=FALSE,bX,bV,bF,bXTC,bCPT;
1415 bool bMasterState;
1416 int force_flags,cglo_flags;
1417 tensor force_vir,shake_vir,total_vir,tmp_vir,pres;
1418 int i,m,status;
1419 rvec mu_tot;
1420 t_vcm *vcm;
1421 t_state *bufstate;
1422 matrix *scale_tot,pcoupl_mu,M,ebox;
1423 gmx_nlheur_t nlh;
1424 t_trxframe rerun_fr;
1425 gmx_repl_ex_t repl_ex=NULL;
1426 int nchkpt=1;
1427 /* Booleans (disguised as a reals) to checkpoint and terminate mdrun */
1428 real chkpt=0,terminate=0,terminate_now=0;
1430 gmx_localtop_t *top;
1431 t_mdebin *mdebin=NULL;
1432 t_state *state=NULL;
1433 rvec *f_global=NULL;
1434 int n_xtc=-1;
1435 rvec *x_xtc=NULL;
1436 gmx_enerdata_t *enerd;
1437 rvec *f=NULL;
1438 gmx_global_stat_t gstat;
1439 gmx_update_t upd=NULL;
1440 t_graph *graph=NULL;
1442 bool bFFscan;
1443 gmx_groups_t *groups;
1444 gmx_ekindata_t *ekind, *ekind_save;
1445 gmx_shellfc_t shellfc;
1446 int count,nconverged=0;
1447 real timestep=0;
1448 double tcount=0;
1449 bool bIonize=FALSE;
1450 bool bTCR=FALSE,bConverged=TRUE,bOK,bSumEkinhOld,bExchanged;
1451 bool bAppend;
1452 bool bVV,bIterations,bIterate,bFirstIterate,bTemp,bPres,bTrotter;
1453 real temp0,mu_aver=0,dvdl;
1454 int a0,a1,gnx=0,ii;
1455 atom_id *grpindex=NULL;
1456 char *grpname;
1457 t_coupl_rec *tcr=NULL;
1458 rvec *xcopy=NULL,*vcopy=NULL,*cbuf=NULL;
1459 matrix boxcopy,lastbox;
1460 tensor tmpvir;
1461 real fom,oldfom,veta_save,pcurr,scalevir,tracevir;
1462 real vetanew = 0;
1463 double cycles;
1464 int reset_counters=-1;
1465 real last_conserved = 0;
1466 real last_ekin = 0;
1467 int iter_i;
1468 t_extmass MassQ;
1469 int **trotter_seq;
1470 char sbuf[22],sbuf2[22];
1471 bool bHandledSignal=FALSE;
1472 #ifdef GMX_FAHCORE
1473 /* Temporary addition for FAHCORE checkpointing */
1474 int chkpt_ret;
1475 #endif
1477 /* Check for special mdrun options */
1478 bRerunMD = (Flags & MD_RERUN);
1479 bIonize = (Flags & MD_IONIZE);
1480 bFFscan = (Flags & MD_FFSCAN);
1481 bAppend = (Flags & MD_APPENDFILES);
1482 /* md-vv uses averaged half step velocities to determine temperature unless defined otherwise by GMX_EKIN_AVE_EKIN;
1483 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
1484 bVV = (ir->eI==eiVV);
1485 if (bVV) {
1486 bEkinAveVel = (getenv("GMX_EKIN_AVE_EKIN")==NULL);
1487 } else {
1488 bEkinAveVel = (getenv("GMX_EKIN_AVE_VEL")!=NULL);
1490 bVVAveVel = bVV && bEkinAveVel;
1491 bVVAveEkin = bVV && !bEkinAveVel;
1493 if (bVV) /* to store the initial velocities while computing virial */
1495 snew(cbuf,top_global->natoms);
1497 /* all the iteratative cases - only if there are constraints */
1498 bIterations = ((IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
1499 bTrotter = (bVV && (IR_NPT_TROTTER(ir) || (IR_NVT_TROTTER(ir))));
1501 if (bRerunMD)
1503 /* Since we don't know if the frames read are related in any way,
1504 * rebuild the neighborlist at every step.
1506 ir->nstlist = 1;
1507 ir->nstcalcenergy = 1;
1508 nstglobalcomm = 1;
1511 check_ir_old_tpx_versions(cr,fplog,ir,top_global);
1513 nstglobalcomm = check_nstglobalcomm(fplog,cr,nstglobalcomm,ir);
1514 bGStatEveryStep = (nstglobalcomm == 1);
1516 if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
1518 fprintf(fplog,
1519 "To reduce the energy communication with nstlist = -1\n"
1520 "the neighbor list validity should not be checked at every step,\n"
1521 "this means that exact integration is not guaranteed.\n"
1522 "The neighbor list validity is checked after:\n"
1523 " <n.list life time> - 2*std.dev.(n.list life time) steps.\n"
1524 "In most cases this will result in exact integration.\n"
1525 "This reduces the energy communication by a factor of 2 to 3.\n"
1526 "If you want less energy communication, set nstlist > 3.\n\n");
1529 if (bRerunMD || bFFscan)
1531 ir->nstxtcout = 0;
1533 groups = &top_global->groups;
1535 /* Initial values */
1536 init_md(fplog,cr,ir,oenv,&t,&t0,&state_global->lambda,&lam0,
1537 nrnb,top_global,&upd,
1538 nfile,fnm,&fp_trn,&fp_xtc,&fp_ene,&fn_cpt,
1539 &fp_dhdl,&fp_field,&mdebin,
1540 force_vir,shake_vir,mu_tot,&bNEMD,&bSimAnn,&vcm,Flags);
1542 clear_mat(total_vir);
1543 clear_mat(pres);
1544 /* Energy terms and groups */
1545 snew(enerd,1);
1546 init_enerdata(top_global->groups.grps[egcENER].nr,ir->n_flambda,enerd);
1547 if (DOMAINDECOMP(cr))
1549 f = NULL;
1551 else
1553 snew(f,top_global->natoms);
1556 /* Kinetic energy data */
1557 snew(ekind,1);
1558 init_ekindata(fplog,top_global,&(ir->opts),ekind);
1559 /* needed for iteration of constraints */
1560 snew(ekind_save,1);
1561 init_ekindata(fplog,top_global,&(ir->opts),ekind_save);
1562 /* Copy the cos acceleration to the groups struct */
1563 ekind->cosacc.cos_accel = ir->cos_accel;
1565 gstat = global_stat_init(ir);
1566 debug_gmx();
1568 /* Check for polarizable models and flexible constraints */
1569 shellfc = init_shell_flexcon(fplog,
1570 top_global,n_flexible_constraints(constr),
1571 (ir->bContinuation ||
1572 (DOMAINDECOMP(cr) && !MASTER(cr))) ?
1573 NULL : state_global->x);
1575 if (DEFORM(*ir))
1577 #ifdef GMX_THREADS
1578 tMPI_Thread_mutex_lock(&box_mutex);
1579 #endif
1580 set_deform_reference_box(upd,init_step_tpx,box_tpx);
1581 #ifdef GMX_THREADS
1582 tMPI_Thread_mutex_unlock(&box_mutex);
1583 #endif
1587 double io = compute_io(ir,top_global->natoms,groups,mdebin->ebin->nener,1);
1588 if ((io > 2000) && MASTER(cr))
1589 fprintf(stderr,
1590 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
1591 io);
1594 if (DOMAINDECOMP(cr)) {
1595 top = dd_init_local_top(top_global);
1597 snew(state,1);
1598 dd_init_local_state(cr->dd,state_global,state);
1600 if (DDMASTER(cr->dd) && ir->nstfout) {
1601 snew(f_global,state_global->natoms);
1603 } else {
1604 if (PAR(cr)) {
1605 /* Initialize the particle decomposition and split the topology */
1606 top = split_system(fplog,top_global,ir,cr);
1608 pd_cg_range(cr,&fr->cg0,&fr->hcg);
1609 pd_at_range(cr,&a0,&a1);
1610 } else {
1611 top = gmx_mtop_generate_local_top(top_global,ir);
1613 a0 = 0;
1614 a1 = top_global->natoms;
1617 state = partdec_init_local_state(cr,state_global);
1618 f_global = f;
1620 atoms2md(top_global,ir,0,NULL,a0,a1-a0,mdatoms);
1622 if (vsite) {
1623 set_vsite_top(vsite,top,mdatoms,cr);
1626 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols) {
1627 graph = mk_graph(fplog,&(top->idef),0,top_global->natoms,FALSE,FALSE);
1630 if (shellfc) {
1631 make_local_shells(cr,mdatoms,shellfc);
1634 if (ir->pull && PAR(cr)) {
1635 dd_make_local_pull_groups(NULL,ir->pull,mdatoms);
1639 if (DOMAINDECOMP(cr))
1641 /* Distribute the charge groups over the nodes from the master node */
1642 dd_partition_system(fplog,ir->init_step,cr,TRUE,1,
1643 state_global,top_global,ir,
1644 state,&f,mdatoms,top,fr,
1645 vsite,shellfc,constr,
1646 nrnb,wcycle,FALSE);
1649 /* If not DD, copy gb data */
1650 if(ir->implicit_solvent && !DOMAINDECOMP(cr))
1652 make_local_gb(cr,fr->born,ir->gb_algorithm);
1655 update_mdatoms(mdatoms,state->lambda);
1657 if (MASTER(cr))
1659 /* Update mdebin with energy history if appending to output files */
1660 if ( Flags & MD_APPENDFILES )
1662 restore_energyhistory_from_state(mdebin,&state_global->enerhist);
1664 /* Set the initial energy history in state to zero by updating once */
1665 update_energyhistory(&state_global->enerhist,mdebin);
1668 if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG)) {
1669 /* Set the random state if we read a checkpoint file */
1670 set_stochd_state(upd,state);
1673 /* Initialize constraints */
1674 if (constr) {
1675 if (!DOMAINDECOMP(cr))
1676 set_constraints(constr,top,ir,mdatoms,cr);
1679 /* Check whether we have to GCT stuff */
1680 bTCR = ftp2bSet(efGCT,nfile,fnm);
1681 if (bTCR) {
1682 if (MASTER(cr)) {
1683 fprintf(stderr,"Will do General Coupling Theory!\n");
1685 gnx = top_global->mols.nr;
1686 snew(grpindex,gnx);
1687 for(i=0; (i<gnx); i++) {
1688 grpindex[i] = i;
1692 if (repl_ex_nst > 0 && MASTER(cr))
1693 repl_ex = init_replica_exchange(fplog,cr->ms,state_global,ir,
1694 repl_ex_nst,repl_ex_seed);
1696 if (!ir->bContinuation && !bRerunMD)
1698 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
1700 /* Set the velocities of frozen particles to zero */
1701 for(i=mdatoms->start; i<mdatoms->start+mdatoms->homenr; i++)
1703 for(m=0; m<DIM; m++)
1705 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
1707 state->v[i][m] = 0;
1713 if (constr)
1715 /* Constrain the initial coordinates and velocities */
1716 do_constrain_first(fplog,constr,ir,mdatoms,state,f,
1717 graph,cr,nrnb,fr,top,shake_vir);
1719 if (vsite)
1721 /* Construct the virtual sites for the initial configuration */
1722 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,NULL,
1723 top->idef.iparams,top->idef.il,
1724 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1728 debug_gmx();
1730 /* would need to modify if vv starts with full time step */
1731 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1732 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1733 constr,&chkpt,&terminate,&terminate_now,&(nlh.nabnsb),state->box,
1734 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1735 (CGLO_FIRSTCALL |
1736 (bVV ? CGLO_PRESSURE:0) |
1737 (CGLO_TEMPERATURE) |
1738 (bRerunMD ? CGLO_RERUNMD:0) |
1739 (bEkinAveVel ? CGLO_EKINAVEVEL:0) |
1740 (CGLO_GSTAT) |
1741 ((Flags & MD_READ_EKIN) ? CGLO_READEKIN:0)));
1742 /* I'm assuming we need global communication the first time */
1743 /* Calculate the initial half step temperature, and save the ekinh_old */
1744 if (!(Flags & MD_STARTFROMCPT))
1746 for(i=0; (i<ir->opts.ngtc); i++)
1748 copy_mat(ekind->tcstat[i].ekinh,ekind->tcstat[i].ekinh_old);
1751 temp0 = enerd->term[F_TEMP];
1753 /* Initiate data for the special cases */
1754 if (bIterations)
1756 bufstate = init_bufstate(state->natoms,(ir->opts.ngtc+1)*NNHCHAIN); /* extra state for barostat */
1759 if (bFFscan)
1761 snew(xcopy,state->natoms);
1762 snew(vcopy,state->natoms);
1763 copy_rvecn(state->x,xcopy,0,state->natoms);
1764 copy_rvecn(state->v,vcopy,0,state->natoms);
1765 copy_mat(state->box,boxcopy);
1768 /* need to make an initial call to get the Trotter variables set. */
1769 trotter_seq = init_trotter(ir,state,&MassQ,bTrotter);
1771 if (MASTER(cr))
1773 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
1775 fprintf(fplog,
1776 "RMS relative constraint deviation after constraining: %.2e\n",
1777 constr_rmsd(constr,FALSE));
1779 fprintf(fplog,"Initial temperature: %g K\n",enerd->term[F_TEMP]);
1780 if (bRerunMD)
1782 fprintf(stderr,"starting md rerun '%s', reading coordinates from"
1783 " input trajectory '%s'\n\n",
1784 *(top_global->name),opt2fn("-rerun",nfile,fnm));
1785 if (bVerbose)
1787 fprintf(stderr,"Calculated time to finish depends on nsteps from "
1788 "run input file,\nwhich may not correspond to the time "
1789 "needed to process input trajectory.\n\n");
1792 else
1794 fprintf(stderr,"starting mdrun '%s'\n",
1795 *(top_global->name));
1796 if (ir->init_step > 0)
1798 fprintf(stderr,"%s steps, %8.1f ps (continuing from step %s, %8.1f ps).\n",
1799 gmx_step_str(ir->init_step+ir->nsteps,sbuf),
1800 (ir->init_step+ir->nsteps)*ir->delta_t,
1801 gmx_step_str(ir->init_step,sbuf2),
1802 ir->init_step*ir->delta_t);
1804 else
1806 fprintf(stderr,"%s steps, %8.1f ps.\n",
1807 gmx_step_str(ir->nsteps,sbuf),ir->nsteps*ir->delta_t);
1810 fprintf(fplog,"\n");
1813 /* Set and write start time */
1814 runtime_start(runtime);
1815 print_date_and_time(fplog,cr->nodeid,"Started mdrun",runtime);
1816 wallcycle_start(wcycle,ewcRUN);
1817 if (fplog)
1818 fprintf(fplog,"\n");
1820 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
1821 #ifdef GMX_FAHCORE
1822 chkpt_ret=fcCheckPointParallel( cr->nodeid,
1823 NULL,0);
1824 if ( chkpt_ret == 0 )
1825 gmx_fatal( 3,__FILE__,__LINE__, "Checkpoint error on step %d\n", 0 );
1826 #endif
1828 debug_gmx();
1829 /***********************************************************
1831 * Loop over MD steps
1833 ************************************************************/
1835 /* if rerunMD then read coordinates and velocities from input trajectory */
1836 if (bRerunMD)
1838 if (getenv("GMX_FORCE_UPDATE"))
1840 bForceUpdate = TRUE;
1843 bNotLastFrame = read_first_frame(oenv,&status,
1844 opt2fn("-rerun",nfile,fnm),
1845 &rerun_fr,TRX_NEED_X | TRX_READ_V);
1846 if (rerun_fr.natoms != top_global->natoms)
1848 gmx_fatal(FARGS,
1849 "Number of atoms in trajectory (%d) does not match the "
1850 "run input file (%d)\n",
1851 rerun_fr.natoms,top_global->natoms);
1853 if (ir->ePBC != epbcNONE)
1855 if (!rerun_fr.bBox)
1857 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);
1859 if (max_cutoff2(ir->ePBC,rerun_fr.box) < sqr(fr->rlistlong))
1861 gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f has too small box dimensions",rerun_fr.step,rerun_fr.time);
1864 /* Set the shift vectors.
1865 * Necessary here when have a static box different from the tpr box.
1867 calc_shifts(rerun_fr.box,fr->shift_vec);
1871 /* loop over MD steps or if rerunMD to end of input trajectory */
1872 bFirstStep = TRUE;
1873 /* Skip the first Nose-Hoover integration when we get the state from tpx */
1874 bStateFromTPX = !opt2bSet("-cpi",nfile,fnm);
1875 bInitStep = bFirstStep && (bStateFromTPX || bVV);
1876 bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
1877 bLastStep = FALSE;
1878 bSumEkinhOld = FALSE;
1879 bExchanged = FALSE;
1881 step = ir->init_step;
1882 step_rel = 0;
1884 if (ir->nstlist == -1)
1886 init_nlistheuristics(&nlh,bGStatEveryStep,step);
1889 bLastStep = (bRerunMD || step_rel > ir->nsteps);
1890 while (!bLastStep || (bRerunMD && bNotLastFrame)) {
1892 wallcycle_start(wcycle,ewcSTEP);
1894 GMX_MPE_LOG(ev_timestep1);
1896 if (bRerunMD) {
1897 if (rerun_fr.bStep) {
1898 step = rerun_fr.step;
1899 step_rel = step - ir->init_step;
1901 if (rerun_fr.bTime) {
1902 t = rerun_fr.time;
1904 else
1906 t = step;
1909 else
1911 bLastStep = (step_rel == ir->nsteps);
1912 t = t0 + step*ir->delta_t;
1915 if (ir->efep != efepNO)
1917 if (bRerunMD && rerun_fr.bLambda && (ir->delta_lambda!=0))
1919 state_global->lambda = rerun_fr.lambda;
1921 else
1923 state_global->lambda = lam0 + step*ir->delta_lambda;
1925 state->lambda = state_global->lambda;
1926 bDoDHDL = do_per_step(step,ir->nstdhdl);
1929 if (bSimAnn)
1931 update_annealing_target_temp(&(ir->opts),t);
1934 if (bRerunMD)
1936 if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
1938 for(i=0; i<state_global->natoms; i++)
1940 copy_rvec(rerun_fr.x[i],state_global->x[i]);
1942 if (rerun_fr.bV)
1944 for(i=0; i<state_global->natoms; i++)
1946 copy_rvec(rerun_fr.v[i],state_global->v[i]);
1949 else
1951 for(i=0; i<state_global->natoms; i++)
1953 clear_rvec(state_global->v[i]);
1955 if (bRerunWarnNoV)
1957 fprintf(stderr,"\nWARNING: Some frames do not contain velocities.\n"
1958 " Ekin, temperature and pressure are incorrect,\n"
1959 " the virial will be incorrect when constraints are present.\n"
1960 "\n");
1961 bRerunWarnNoV = FALSE;
1965 copy_mat(rerun_fr.box,state_global->box);
1966 copy_mat(state_global->box,state->box);
1968 if (vsite && (Flags & MD_RERUN_VSITE))
1970 if (DOMAINDECOMP(cr))
1972 gmx_fatal(FARGS,"Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
1974 if (graph)
1976 /* Following is necessary because the graph may get out of sync
1977 * with the coordinates if we only have every N'th coordinate set
1979 mk_mshift(fplog,graph,fr->ePBC,state->box,state->x);
1980 shift_self(graph,state->box,state->x);
1982 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
1983 top->idef.iparams,top->idef.il,
1984 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1985 if (graph)
1987 unshift_self(graph,state->box,state->x);
1992 /* Stop Center of Mass motion */
1993 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step,ir->nstcomm));
1995 /* Copy back starting coordinates in case we're doing a forcefield scan */
1996 if (bFFscan)
1998 for(ii=0; (ii<state->natoms); ii++)
2000 copy_rvec(xcopy[ii],state->x[ii]);
2001 copy_rvec(vcopy[ii],state->v[ii]);
2003 copy_mat(boxcopy,state->box);
2006 if (bRerunMD)
2008 /* for rerun MD always do Neighbour Searching */
2009 bNS = (bFirstStep || ir->nstlist != 0);
2010 bNStList = bNS;
2012 else
2014 /* Determine whether or not to do Neighbour Searching and LR */
2015 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
2017 bNS = (bFirstStep || bExchanged || bNStList ||
2018 (ir->nstlist == -1 && nlh.nabnsb > 0));
2020 if (bNS && ir->nstlist == -1)
2022 set_nlistheuristics(&nlh,bFirstStep || bExchanged,step);
2026 if (terminate_now > 0 || (terminate_now < 0 && bNS))
2028 bLastStep = TRUE;
2031 /* Determine whether or not to update the Born radii if doing GB */
2032 bBornRadii=bFirstStep;
2033 if (ir->implicit_solvent && (step % ir->nstgbradii==0))
2035 bBornRadii=TRUE;
2038 do_log = do_per_step(step,ir->nstlog) || bFirstStep || bLastStep;
2039 do_verbose = bVerbose &&
2040 (step % stepout == 0 || bFirstStep || bLastStep);
2042 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
2044 if (bRerunMD)
2046 bMasterState = TRUE;
2048 else
2050 bMasterState = FALSE;
2051 /* Correct the new box if it is too skewed */
2052 if (DYNAMIC_BOX(*ir))
2054 if (correct_box(fplog,step,state->box,graph))
2056 bMasterState = TRUE;
2059 if (DOMAINDECOMP(cr) && bMasterState)
2061 dd_collect_state(cr->dd,state,state_global);
2065 if (DOMAINDECOMP(cr))
2067 /* Repartition the domain decomposition */
2068 wallcycle_start(wcycle,ewcDOMDEC);
2069 dd_partition_system(fplog,step,cr,
2070 bMasterState,nstglobalcomm,
2071 state_global,top_global,ir,
2072 state,&f,mdatoms,top,fr,
2073 vsite,shellfc,constr,
2074 nrnb,wcycle,do_verbose);
2075 wallcycle_stop(wcycle,ewcDOMDEC);
2079 if (MASTER(cr) && do_log && !bFFscan)
2081 print_ebin_header(fplog,step,t,state->lambda);
2084 if (ir->efep != efepNO)
2086 update_mdatoms(mdatoms,state->lambda);
2089 if (bRerunMD && rerun_fr.bV)
2092 /* We need the kinetic energy at minus the half step for determining
2093 * the full step kinetic energy and possibly for T-coupling.*/
2094 /* This may not be quite working correctly yet . . . . */
2095 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2096 wcycle,enerd,NULL,NULL,NULL,NULL,mu_tot,
2097 constr,&chkpt,&terminate,&terminate_now,&(nlh.nabnsb),state->box,
2098 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2099 (CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE) |
2100 (bEkinAveVel?CGLO_EKINAVEVEL:0));
2102 clear_mat(force_vir);
2104 /* Ionize the atoms if necessary */
2105 if (bIonize)
2107 ionize(fplog,oenv,mdatoms,top_global,t,ir,state->x,state->v,
2108 mdatoms->start,mdatoms->start+mdatoms->homenr,state->box,cr);
2111 /* Update force field in ffscan program */
2112 if (bFFscan)
2114 if (update_forcefield(fplog,
2115 nfile,fnm,fr,
2116 mdatoms->nr,state->x,state->box)) {
2117 if (gmx_parallel_env())
2119 gmx_finalize();
2121 exit(0);
2125 GMX_MPE_LOG(ev_timestep2);
2127 if ((bNS || bLastStep) && (step > ir->init_step) && !bRerunMD)
2129 bCPT = (chkpt > 0 || (bLastStep && (Flags & MD_CONFOUT)));
2130 if (bCPT)
2132 chkpt = 0;
2135 else
2137 bCPT = FALSE;
2140 /* Determine the pressure:
2141 * always when we want exact averages in the energy file,
2142 * at ns steps when we have pressure coupling,
2143 * otherwise only at energy output steps (set below).
2145 bNstEner = (bGStatEveryStep || do_per_step(step,ir->nstcalcenergy));
2146 bCalcEner = bNstEner;
2147 bCalcPres = (bGStatEveryStep || (ir->epc != epcNO && bNS));
2149 /* Do we need global communication ? */
2150 bGStat = (bCalcEner || bStopCM ||
2151 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
2153 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
2155 if (do_ene || do_log)
2157 bCalcPres = TRUE;
2158 bCalcEner = TRUE;
2159 bGStat = TRUE;
2162 /* these CGLO_ options remain the same throughout the iteration */
2163 cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
2164 (bEkinAveVel ? CGLO_EKINAVEVEL : 0) |
2165 (bStopCM ? CGLO_STOPCM : 0) |
2166 (bGStat ? CGLO_GSTAT : 0) |
2167 (bNEMD ? CGLO_NEMD : 0) |
2168 (constr ? CGLO_CONSTRAINT : 0)
2171 force_flags = (GMX_FORCE_STATECHANGED |
2172 ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
2173 GMX_FORCE_ALLFORCES |
2174 (bNStList ? GMX_FORCE_DOLR : 0) |
2175 GMX_FORCE_SEPLRF |
2176 (bCalcEner ? GMX_FORCE_VIRIAL : 0) |
2177 (bDoDHDL ? GMX_FORCE_DHDL : 0));
2179 if (shellfc)
2181 /* Now is the time to relax the shells */
2182 count=relax_shell_flexcon(fplog,cr,bVerbose,bFFscan ? step+1 : step,
2183 ir,bNS,force_flags,
2184 bStopCM,top,top_global,
2185 constr,enerd,fcd,
2186 state,f,force_vir,mdatoms,
2187 nrnb,wcycle,graph,groups,
2188 shellfc,fr,bBornRadii,t,mu_tot,
2189 state->natoms,&bConverged,vsite,
2190 fp_field);
2191 tcount+=count;
2193 if (bConverged)
2195 nconverged++;
2198 else
2200 /* The coordinates (x) are shifted (to get whole molecules)
2201 * in do_force.
2202 * This is parallellized as well, and does communication too.
2203 * Check comments in sim_util.c
2206 do_force(fplog,cr,ir,step,nrnb,wcycle,top,top_global,groups,
2207 state->box,state->x,&state->hist,
2208 f,force_vir,mdatoms,enerd,fcd,
2209 state->lambda,graph,
2210 fr,vsite,mu_tot,t,fp_field,ed,bBornRadii,
2211 (bNS ? GMX_FORCE_NS : 0) | force_flags);
2214 GMX_BARRIER(cr->mpi_comm_mygroup);
2216 if (bTCR)
2218 mu_aver = calc_mu_aver(cr,state->x,mdatoms->chargeA,
2219 mu_tot,&top_global->mols,mdatoms,gnx,grpindex);
2222 if (bTCR && bFirstStep)
2224 tcr=init_coupling(fplog,nfile,fnm,cr,fr,mdatoms,&(top->idef));
2225 fprintf(fplog,"Done init_coupling\n");
2226 fflush(fplog);
2229 /* ############### START FIRST UPDATE HALF-STEP ############### */
2231 if (!bStartingFromCpt && !bRerunMD) {
2232 if (bVVAveVel && bInitStep) {
2233 /* if using velocity verlet with full time step Ekin, take the first half step only to compute the
2234 virial for the first step. From there, revert back to the initial coordinates
2235 so that the input is actually the initial step */
2236 copy_rvecn(state->v,cbuf,0,state->natoms); /* should make this better for parallelizing? */
2239 /* this is for NHC in the Ekin(t+dt/2) version of vv */
2240 if (!bInitStep || !bEkinAveVel)
2242 trotter_update(ir,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq[1],bEkinAveVel);
2245 update_coords(fplog,step,ir,mdatoms,state,
2246 f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2247 ekind,M,wcycle,upd,bInitStep,etrtVELOCITY,cr,nrnb,constr,&top->idef);
2249 bIterate = bIterations && (!bInitStep);
2250 bFirstIterate = TRUE;
2251 /* for iterations, we save these vectors, as we will be self-consistently iterating
2252 the calculations */
2253 /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
2255 /* save the state */
2256 if (bIterate) {
2257 copy_coupling_state(state,bufstate,ekind,ekind_save);
2260 while (bIterate || bFirstIterate)
2262 if (bIterate)
2264 copy_coupling_state(bufstate,state,ekind_save,ekind);
2266 if (bIterate)
2268 if (bFirstIterate && bTrotter)
2270 /* The first time, we need a decent first estimate
2271 of veta(t+dt) to compute the constraints. Do
2272 this by computing the box volume part of the
2273 trotter integration at this time. Nothing else
2274 should be changed by this routine here. If
2275 !(first time), we start with the previous value
2276 of veta. */
2278 veta_save = state->veta;
2279 trotter_update(ir,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq[0],FALSE);
2280 vetanew = state->veta;
2281 state->veta = veta_save;
2285 bOK = TRUE;
2286 if ( !bRerunMD || rerun_fr.bV || bForceUpdate) { /* Why is rerun_fr.bV here? Unclear. */
2287 wallcycle_start(wcycle,ewcUPDATE);
2288 dvdl = 0;
2290 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2291 &top->idef,shake_vir,NULL,
2292 cr,nrnb,wcycle,upd,constr,
2293 bInitStep,TRUE,bCalcPres,vetanew);
2295 if (!bOK && !bFFscan)
2297 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2301 else if (graph)
2302 { /* Need to unshift here if a do_force has been
2303 called in the previous step */
2304 unshift_self(graph,state->box,state->x);
2307 /* Note -- we don't want to compute the constraint virial again.
2308 /* first step, we need to compute the virial */
2309 if (bVV) {
2310 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2311 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2312 constr,&chkpt,&terminate,&terminate_now,&(nlh.nabnsb),state->box,
2313 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2314 (cglo_flags | CGLO_ENERGY) |
2315 (bFirstIterate ? (cglo_flags | CGLO_PRESSURE):0) |
2316 (((bEkinAveVel &&(!bInitStep)) || (!bEkinAveVel && IR_NPT_TROTTER(ir)))? (cglo_flags | CGLO_TEMPERATURE):0) |
2317 ((bEkinAveVel || (!bEkinAveVel && IR_NPT_TROTTER(ir))) ? CGLO_EKINAVEVEL : 0) |
2318 (bIterate ? CGLO_ITERATE : 0) |
2319 (bFirstIterate ? CGLO_FIRSTITERATE : 0) |
2320 (cglo_flags | CGLO_SCALEEKIN)
2323 /* explanation of above:
2324 a) We compute Ekin at the full time step
2325 if 1) we are using the AveVel Ekin, and it's not the
2326 initial step, or 2) if we are using AveEkin, but need the full
2327 time step kinetic energy for the pressure.
2328 b) If we are using EkinAveEkin for the kinetic energy for the temperture control, we still feed in
2329 EkinAveVel because it's needed for the pressure */
2331 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
2332 if (!bInitStep)
2334 trotter_update(ir,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq[2],bEkinAveVel);
2337 if (done_iterating(cr,fplog,&bFirstIterate,&bIterate,state->veta,&vetanew,0)) break;
2340 if (bTrotter && !bInitStep) {
2341 copy_mat(shake_vir,state->vir_prev);
2342 if (IR_NVT_TROTTER(ir) && bEkinAveVel) {
2343 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
2344 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,NULL,bEkinAveVel,FALSE,FALSE);
2345 enerd->term[F_EKIN] = trace(ekind->ekin);
2348 /* if it's the initial step, we performed this first step just to get the constraint virial */
2349 if (bInitStep && bVVAveVel) {
2350 copy_rvecn(cbuf,state->v,0,state->natoms);
2353 if (fr->bSepDVDL && fplog && do_log)
2355 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2357 enerd->term[F_DHDL_CON] += dvdl;
2359 wallcycle_stop(wcycle,ewcUPDATE);
2360 GMX_MPE_LOG(ev_timestep1);
2362 /* MRS -- done iterating -- compute the conserved quantity */
2364 if (bVV) {
2365 last_conserved = 0;
2366 if (IR_NVT_TROTTER(ir) || IR_NPT_TROTTER(ir))
2368 last_conserved =
2369 NPT_energy(ir,state->nosehoover_xi,state->nosehoover_vxi,state->veta, state->box, &MassQ);
2370 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
2372 last_conserved -= enerd->term[F_DISPCORR];
2375 if (bEkinAveVel) {
2376 last_ekin = enerd->term[F_EKIN]; /* does this get preserved through checkpointing? */
2380 /* ######## END FIRST UPDATE STEP ############## */
2381 /* ######## If doing VV, we now have v(dt) ###### */
2383 /* ################## START TRAJECTORY OUTPUT ################# */
2385 /* Now we have the energies and forces corresponding to the
2386 * coordinates at time t. We must output all of this before
2387 * the update.
2388 * for RerunMD t is read from input trajectory
2390 GMX_MPE_LOG(ev_output_start);
2392 bX = do_per_step(step,ir->nstxout);
2393 bV = do_per_step(step,ir->nstvout);
2394 bF = do_per_step(step,ir->nstfout);
2395 bXTC = do_per_step(step,ir->nstxtcout);
2397 #ifdef GMX_FAHCORE
2398 if (MASTER(cr))
2399 fcReportProgress( ir->nsteps, step );
2401 bX = bX || bLastStep; /*enforce writing positions and velocities
2402 at end of run */
2403 bV = bV || bLastStep;
2405 int nthreads=(cr->nthreads==0 ? 1 : cr->nthreads);
2406 int nnodes=(cr->nnodes==0 ? 1 : cr->nnodes);
2408 bCPT = bCPT;
2409 /*Gromacs drives checkpointing; no ||
2410 fcCheckPointPendingThreads(cr->nodeid,
2411 nthreads*nnodes);*/
2412 /* sync bCPT and fc record-keeping */
2413 if (bCPT && MASTER(cr))
2414 fcRequestCheckPoint();
2416 #endif
2419 if (bX || bV || bF || bXTC || bCPT)
2421 wallcycle_start(wcycle,ewcTRAJ);
2422 if (bCPT)
2424 if (state->flags & (1<<estLD_RNG))
2426 get_stochd_state(upd,state);
2428 if (MASTER(cr))
2430 if (bSumEkinhOld)
2432 state_global->ekinstate.bUpToDate = FALSE;
2434 else
2436 update_ekinstate(&state_global->ekinstate,ekind);
2437 state_global->ekinstate.bUpToDate = TRUE;
2439 update_energyhistory(&state_global->enerhist,mdebin);
2442 write_traj(fplog,cr,fp_trn,bX,bV,bF,fp_xtc,bXTC,ir->xtcprec,
2443 fn_cpt,bCPT,top_global,ir->eI,ir->simulation_part,
2444 step,t,state,state_global,f,f_global,&n_xtc,&x_xtc);
2445 debug_gmx();
2446 if (bLastStep && step_rel == ir->nsteps &&
2447 (Flags & MD_CONFOUT) && MASTER(cr) &&
2448 !bRerunMD && !bFFscan)
2450 /* x and v have been collected in write_traj */
2451 fprintf(stderr,"\nWriting final coordinates.\n");
2452 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols &&
2453 DOMAINDECOMP(cr))
2455 /* Make molecules whole only for confout writing */
2456 do_pbc_mtop(fplog,ir->ePBC,state->box,top_global,state_global->x);
2458 write_sto_conf_mtop(ftp2fn(efSTO,nfile,fnm),
2459 *top_global->name,top_global,
2460 state_global->x,state_global->v,
2461 ir->ePBC,state->box);
2462 debug_gmx();
2464 wallcycle_stop(wcycle,ewcTRAJ);
2466 GMX_MPE_LOG(ev_output_finish);
2468 /* kludge -- virial is lost with restart for NPT control. Must restart */
2469 if (bStartingFromCpt && bVV)
2471 copy_mat(state->vir_prev,shake_vir);
2473 /* ################## END TRAJECTORY OUTPUT ################ */
2475 /* Determine the pressure:
2476 * always when we want exact averages in the energy file,
2477 * at ns steps when we have pressure coupling,
2478 * otherwise only at energy output steps (set below).
2481 bNstEner = (bGStatEveryStep || do_per_step(step,ir->nstcalcenergy));
2482 bCalcEner = bNstEner;
2483 bCalcPres = (bGStatEveryStep || (ir->epc != epcNO && bNS));
2485 /* Do we need global communication ? */
2486 bGStat = (bGStatEveryStep || bStopCM || bNS ||
2487 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
2489 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
2491 if (do_ene || do_log)
2493 bCalcPres = TRUE;
2494 bGStat = TRUE;
2497 bIterate = bIterations;
2498 bFirstIterate = TRUE;
2500 /* for iterations, we save these vectors, as we will be redoing the calculations */
2501 if (bIterate)
2503 copy_coupling_state(state,bufstate,ekind,ekind_save);
2506 while (bIterate || bFirstIterate)
2508 /* We now restore these vectors to redo the calculation with improved extended variables */
2509 if (bIterate)
2511 copy_coupling_state(bufstate,state,ekind_save,ekind);
2514 /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
2515 so scroll down for that logic */
2517 /* ######### START SECOND UPDATE STEP ################# */
2519 GMX_MPE_LOG(ev_update_start);
2520 bOK = TRUE;
2521 if (!bRerunMD || rerun_fr.bV || bForceUpdate)
2523 wallcycle_start(wcycle,ewcUPDATE);
2524 dvdl = 0;
2527 /* Box is changed in update() when we do pressure coupling,
2528 * but we should still use the old box for energy corrections and when
2529 * writing it to the energy file, so it matches the trajectory files for
2530 * the same timestep above. Make a copy in a separate array.
2533 copy_mat(state->box,lastbox);
2535 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS*/
2536 if (bTrotter)
2538 if (bFirstIterate)
2540 tracevir = trace(shake_vir);
2542 if (bIterate)
2544 /* we use a new value of scalevir to converge the iterations faster */
2545 scalevir = tracevir/trace(shake_vir);
2546 msmul(shake_vir,scalevir,shake_vir);
2547 m_add(force_vir,shake_vir,total_vir);
2548 clear_mat(shake_vir);
2550 trotter_update(ir,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq[3],bEkinAveVel);
2552 /* We can only do Berendsen coupling after we have summed the kinetic
2553 * energy or virial. Since the happens in global_state after update,
2554 * we should only do it at step % nstlist = 1 with bGStatEveryStep=FALSE.
2557 update_extended(fplog,step,ir,mdatoms,state,ekind,pcoupl_mu,M,wcycle,
2558 upd,bInitStep,FALSE,&MassQ);
2560 /* velocity (for VV) */
2561 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2562 ekind,M,wcycle,upd,FALSE,etrtVELOCITY,cr,nrnb,constr,&top->idef);
2564 /* above, initialize just copies ekinh into ekin, it doesn't copy
2565 position (for VV), and entire integrator for MD */
2567 if (bVVAveEkin)
2569 copy_rvecn(state->x,cbuf,0,state->natoms);
2572 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2573 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2575 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2576 &top->idef,shake_vir,force_vir,
2577 cr,nrnb,wcycle,upd,constr,
2578 bInitStep,FALSE,bCalcPres,state->veta);
2580 if (bVVAveEkin)
2582 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2583 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2584 constr,&chkpt,&terminate,&terminate_now,&(nlh.nabnsb),lastbox,
2585 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2586 (cglo_flags | CGLO_TEMPERATURE) |
2587 (cglo_flags & ~CGLO_PRESSURE) |
2588 (cglo_flags & ~CGLO_ENERGY)
2590 trotter_update(ir,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq[4],bEkinAveVel);
2591 copy_rvecn(cbuf,state->x,0,state->natoms);
2592 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
2593 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
2594 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
2595 /* are the small terms in the shake_vir here due
2596 * to numerical errors, or are they important
2597 * physically? I'm thinking they are just errors, but not completely sure. */
2598 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
2599 &top->idef,tmp_vir,force_vir,
2600 cr,nrnb,wcycle,upd,constr,
2601 bInitStep,FALSE,bCalcPres,state->veta);
2602 m_add(shake_vir,tmp_vir,shake_vir);
2605 if (!bOK && !bFFscan)
2607 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
2610 if (fr->bSepDVDL && fplog && do_log)
2612 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
2614 enerd->term[F_DHDL_CON] += dvdl;
2615 wallcycle_stop(wcycle,ewcUPDATE);
2617 else if (graph)
2619 /* Need to unshift here */
2620 unshift_self(graph,state->box,state->x);
2623 GMX_BARRIER(cr->mpi_comm_mygroup);
2624 GMX_MPE_LOG(ev_update_finish);
2626 if (vsite != NULL)
2628 wallcycle_start(wcycle,ewcVSITECONSTR);
2629 if (graph != NULL)
2631 shift_self(graph,state->box,state->x);
2633 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
2634 top->idef.iparams,top->idef.il,
2635 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
2637 if (graph != NULL)
2639 unshift_self(graph,state->box,state->x);
2641 wallcycle_stop(wcycle,ewcVSITECONSTR);
2644 /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
2645 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
2646 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
2647 constr,&chkpt,&terminate,&terminate_now,&(nlh.nabnsb),lastbox,
2648 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
2649 (!bVV ? (cglo_flags | CGLO_ENERGY):0) |
2650 (!bVV ? (cglo_flags | CGLO_PRESSURE):0) |
2651 (!bVV ? (cglo_flags | CGLO_TEMPERATURE):0) |
2652 (bIterate ? (cglo_flags | CGLO_ITERATE) : 0) |
2653 (bFirstIterate ? (cglo_flags | CGLO_FIRSTITERATE) : 0)
2655 /* bIterate is set to keep it from eliminating the old ekinh */
2656 /* ############# END CALC EKIN AND PRESSURE ################# */
2658 if (done_iterating(cr,fplog,&bFirstIterate,&bIterate,trace(shake_vir),&tracevir,1)) break;
2661 update_box(fplog,step,ir,mdatoms,state,graph,f,
2662 ir->nstlist==-1 ? &nlh.scale_tot : NULL,pcoupl_mu,nrnb,wcycle,upd,bInitStep,FALSE);
2664 /* ################# END UPDATE STEP 2 ################# */
2665 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
2667 /* Determine the wallclock run time up till now */
2668 run_time = (double)time(NULL) - (double)runtime->real;
2670 /* Check whether everything is still allright */
2671 if ((bGotTermSignal || bGotUsr1Signal) && !bHandledSignal)
2673 if (bGotTermSignal || ir->nstlist == 0)
2675 terminate = 1;
2677 else
2679 terminate = -1;
2681 if (!PAR(cr))
2683 terminate_now = terminate;
2685 if (fplog)
2687 fprintf(fplog,
2688 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2689 bGotTermSignal ? "TERM" : "USR1",
2690 terminate==-1 ? "NS " : "");
2691 fflush(fplog);
2693 fprintf(stderr,
2694 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
2695 bGotTermSignal ? "TERM" : "USR1",
2696 terminate==-1 ? "NS " : "");
2697 fflush(stderr);
2698 bHandledSignal=TRUE;
2700 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
2701 (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
2702 terminate == 0)
2704 /* Signal to terminate the run */
2705 terminate = (ir->nstlist == 0 ? 1 : -1);
2706 if (!PAR(cr))
2708 terminate_now = terminate;
2710 if (fplog)
2712 fprintf(fplog,"\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2714 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
2717 if (ir->nstlist == -1 && !bRerunMD)
2719 /* When bGStatEveryStep=FALSE, global_stat is only called
2720 * when we check the atom displacements, not at NS steps.
2721 * This means that also the bonded interaction count check is not
2722 * performed immediately after NS. Therefore a few MD steps could
2723 * be performed with missing interactions.
2724 * But wrong energies are never written to file,
2725 * since energies are only written after global_stat
2726 * has been called.
2728 if (step >= nlh.step_nscheck)
2730 nlh.nabnsb = natoms_beyond_ns_buffer(ir,fr,&top->cgs,
2731 nlh.scale_tot,state->x);
2733 else
2735 /* This is not necessarily true,
2736 * but step_nscheck is determined quite conservatively.
2738 nlh.nabnsb = 0;
2742 /* In parallel we only have to check for checkpointing in steps
2743 * where we do global communication,
2744 * otherwise the other nodes don't know.
2746 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
2747 cpt_period >= 0 &&
2748 (cpt_period == 0 ||
2749 run_time >= nchkpt*cpt_period*60.0)))
2751 if (chkpt == 0)
2753 nchkpt++;
2755 chkpt = 1;
2758 /* The coordinates (x) were unshifted in update */
2759 if (bFFscan && (shellfc==NULL || bConverged))
2761 if (print_forcefield(fplog,enerd->term,mdatoms->homenr,
2762 f,NULL,xcopy,
2763 &(top_global->mols),mdatoms->massT,pres))
2765 if (gmx_parallel_env()) {
2766 gmx_finalize();
2768 fprintf(stderr,"\n");
2769 exit(0);
2772 if (!bGStat)
2774 /* We will not sum ekinh_old,
2775 * so signal that we still have to do it.
2777 bSumEkinhOld = TRUE;
2780 if (bTCR)
2782 /* Only do GCT when the relaxation of shells (minimization) has converged,
2783 * otherwise we might be coupling to bogus energies.
2784 * In parallel we must always do this, because the other sims might
2785 * update the FF.
2788 /* Since this is called with the new coordinates state->x, I assume
2789 * we want the new box state->box too. / EL 20040121
2791 do_coupling(fplog,oenv,nfile,fnm,tcr,t,step,enerd->term,fr,
2792 ir,MASTER(cr),
2793 mdatoms,&(top->idef),mu_aver,
2794 top_global->mols.nr,cr,
2795 state->box,total_vir,pres,
2796 mu_tot,state->x,f,bConverged);
2797 debug_gmx();
2800 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
2802 sum_dhdl(enerd,state->lambda,ir);
2803 /* use the directly determined last velocity, not actually the averaged half steps */
2804 if (bTrotter && bEkinAveVel) {
2805 enerd->term[F_EKIN] = last_ekin;
2807 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
2809 switch (ir->etc)
2811 case etcNO:
2812 break;
2813 case etcBERENDSEN:
2814 break;
2815 case etcNOSEHOOVER:
2816 if (IR_NVT_TROTTER(ir)) {
2817 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + last_conserved;
2818 } else {
2819 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] +
2820 NPT_energy(ir,state->nosehoover_xi,
2821 state->nosehoover_vxi,state->veta,state->box,&MassQ);
2823 break;
2824 case etcVRESCALE:
2825 enerd->term[F_ECONSERVED] =
2826 enerd->term[F_ETOT] + vrescale_energy(&(ir->opts),
2827 state->therm_integral);
2828 break;
2829 default:
2830 break;
2833 /* Check for excessively large energies */
2834 if (bIonize)
2836 #ifdef GMX_DOUBLE
2837 real etot_max = 1e200;
2838 #else
2839 real etot_max = 1e30;
2840 #endif
2841 if (fabs(enerd->term[F_ETOT]) > etot_max)
2843 fprintf(stderr,"Energy too large (%g), giving up\n",
2844 enerd->term[F_ETOT]);
2847 /* ######### END PREPARING EDR OUTPUT ########### */
2849 /* Time for performance */
2850 if (((step % stepout) == 0) || bLastStep)
2852 runtime_upd_proc(runtime);
2855 /* Output stuff */
2856 if (MASTER(cr))
2858 bool do_dr,do_or;
2860 if (bNstEner)
2862 upd_mdebin(mdebin,bDoDHDL ? fp_dhdl : NULL,TRUE,
2863 t,mdatoms->tmass,enerd,state,lastbox,
2864 shake_vir,force_vir,total_vir,pres,
2865 ekind,mu_tot,constr);
2867 else
2869 upd_mdebin_step(mdebin);
2872 do_dr = do_per_step(step,ir->nstdisreout);
2873 do_or = do_per_step(step,ir->nstorireout);
2875 print_ebin(fp_ene,do_ene,do_dr,do_or,do_log?fplog:NULL,step,t,
2876 eprNORMAL,bCompact,mdebin,fcd,groups,&(ir->opts));
2878 if (ir->ePull != epullNO)
2880 pull_print_output(ir->pull,step,t);
2883 if (do_per_step(step,ir->nstlog))
2885 if(fflush(fplog) != 0)
2887 gmx_fatal(FARGS,"Cannot flush logfile - maybe you are out of quota?");
2893 /* Remaining runtime */
2894 if (MULTIMASTER(cr) && do_verbose)
2896 if (shellfc)
2898 fprintf(stderr,"\n");
2900 print_time(stderr,runtime,step,ir);
2903 /* Replica exchange */
2904 bExchanged = FALSE;
2905 if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
2906 do_per_step(step,repl_ex_nst))
2908 bExchanged = replica_exchange(fplog,cr,repl_ex,
2909 state_global,enerd->term,
2910 state,step,t);
2912 if (bExchanged && PAR(cr))
2914 if (DOMAINDECOMP(cr))
2916 dd_partition_system(fplog,step,cr,TRUE,1,
2917 state_global,top_global,ir,
2918 state,&f,mdatoms,top,fr,
2919 vsite,shellfc,constr,
2920 nrnb,wcycle,FALSE);
2922 else
2924 bcast_state(cr,state,FALSE);
2928 bFirstStep = FALSE;
2929 bInitStep = FALSE;
2930 bStartingFromCpt = FALSE;
2932 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
2933 /* Complicated conditional when bGStatEveryStep=FALSE.
2934 * We can not just use bGStat, since then the simulation results
2935 * would depend on nstenergy and nstlog or step_nscheck.
2937 if (((state->flags & (1<<estPRES_PREV)) || (state->flags & (1<<estVIR_PREV))) &&
2938 (bGStatEveryStep ||
2939 (ir->nstlist > 0 && step % ir->nstlist == 0) ||
2940 (ir->nstlist < 0 && nlh.nabnsb > 0) ||
2941 (ir->nstlist == 0 && bGStat)))
2943 /* Store the pressure in t_state for pressure coupling
2944 * at the next MD step.
2946 if (state->flags & (1<<estPRES_PREV))
2948 copy_mat(pres,state->pres_prev);
2952 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
2954 if (bRerunMD)
2956 /* read next frame from input trajectory */
2957 bNotLastFrame = read_next_frame(oenv,status,&rerun_fr);
2960 if (!bRerunMD || !rerun_fr.bStep)
2962 /* increase the MD step number */
2963 step++;
2964 step_rel++;
2967 cycles = wallcycle_stop(wcycle,ewcSTEP);
2968 if (DOMAINDECOMP(cr) && wcycle)
2970 dd_cycles_add(cr->dd,cycles,ddCyclStep);
2973 if (step_rel == wcycle_get_reset_counters(wcycle))
2975 /* Reset all the counters related to performance over the run */
2976 reset_all_counters(fplog,cr,step,&step_rel,ir,wcycle,nrnb,runtime);
2977 wcycle_set_reset_counters(wcycle, 0);
2980 /* End of main MD loop */
2981 debug_gmx();
2983 /* Stop the time */
2984 runtime_end(runtime);
2986 if (bRerunMD)
2988 close_trj(status);
2991 if (!(cr->duty & DUTY_PME))
2993 /* Tell the PME only node to finish */
2994 gmx_pme_finish(cr);
2997 if (MASTER(cr))
2999 if (bGStatEveryStep && !bRerunMD)
3001 print_ebin(fp_ene,FALSE,FALSE,FALSE,fplog,step,t,
3002 eprAVER,FALSE,mdebin,fcd,groups,&(ir->opts));
3004 close_enx(fp_ene);
3005 if (ir->nstxtcout)
3007 close_xtc(fp_xtc);
3009 close_trn(fp_trn);
3010 if (fp_dhdl)
3012 gmx_fio_fclose(fp_dhdl);
3014 if (fp_field)
3016 gmx_fio_fclose(fp_field);
3019 debug_gmx();
3021 if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
3023 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)));
3024 fprintf(fplog,"Average number of atoms that crossed the half buffer length: %.1f\n\n",nlh.ab/nlh.nns);
3027 if (shellfc && fplog)
3029 fprintf(fplog,"Fraction of iterations that converged: %.2f %%\n",
3030 (nconverged*100.0)/step_rel);
3031 fprintf(fplog,"Average number of force evaluations per MD step: %.2f\n\n",
3032 tcount/step_rel);
3035 if (repl_ex_nst > 0 && MASTER(cr))
3037 print_replica_exchange_statistics(fplog,repl_ex);
3040 runtime->nsteps_done = step_rel;
3042 return 0;