Fixed timing measurements.
[gromacs.git] / src / kernel / md.c
blob0ca2dc97a077c21174f505830ec60071c83b38e9
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 #if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
41 /* _isnan() */
42 #include <float.h>
43 #endif
45 #include "typedefs.h"
46 #include "smalloc.h"
47 #include "sysstuff.h"
48 #include "vec.h"
49 #include "statutil.h"
50 #include "vcm.h"
51 #include "mdebin.h"
52 #include "nrnb.h"
53 #include "calcmu.h"
54 #include "index.h"
55 #include "vsite.h"
56 #include "update.h"
57 #include "ns.h"
58 #include "trnio.h"
59 #include "xtcio.h"
60 #include "mdrun.h"
61 #include "confio.h"
62 #include "network.h"
63 #include "pull.h"
64 #include "xvgr.h"
65 #include "physics.h"
66 #include "names.h"
67 #include "xmdrun.h"
68 #include "ionize.h"
69 #include "disre.h"
70 #include "orires.h"
71 #include "dihre.h"
72 #include "pppm.h"
73 #include "pme.h"
74 #include "mdatoms.h"
75 #include "repl_ex.h"
76 #include "qmmm.h"
77 #include "mpelogging.h"
78 #include "domdec.h"
79 #include "partdec.h"
80 #include "topsort.h"
81 #include "coulomb.h"
82 #include "constr.h"
83 #include "shellfc.h"
84 #include "compute_io.h"
85 #include "mvdata.h"
86 #include "checkpoint.h"
87 #include "mtop_util.h"
88 #include "sighandler.h"
89 #include "string2.h"
91 #ifdef GMX_LIB_MPI
92 #include <mpi.h>
93 #endif
94 #ifdef GMX_THREADS
95 #include "tmpi.h"
96 #endif
98 #ifdef GMX_FAHCORE
99 #include "corewrap.h"
100 #endif
103 double do_md(FILE *fplog,t_commrec *cr,int nfile,const t_filenm fnm[],
104 const output_env_t oenv, gmx_bool bVerbose,gmx_bool bCompact,
105 int nstglobalcomm,
106 gmx_vsite_t *vsite,gmx_constr_t constr,
107 int stepout,t_inputrec *ir,
108 gmx_mtop_t *top_global,
109 t_fcdata *fcd,
110 t_state *state_global,
111 t_mdatoms *mdatoms,
112 t_nrnb *nrnb,gmx_wallcycle_t wcycle,
113 gmx_edsam_t ed,t_forcerec *fr,
114 int repl_ex_nst,int repl_ex_seed,
115 real cpt_period,real max_hours,
116 const char *deviceOptions,
117 unsigned long Flags,
118 gmx_runtime_t *runtime)
120 gmx_mdoutf_t *outf;
121 gmx_large_int_t step,step_rel;
122 double run_time;
123 double t,t0,lam0;
124 gmx_bool bGStatEveryStep,bGStat,bNstEner,bCalcEnerPres;
125 gmx_bool bNS,bNStList,bSimAnn,bStopCM,bRerunMD,bNotLastFrame=FALSE,
126 bFirstStep,bStateFromTPX,bInitStep,bLastStep,
127 bBornRadii,bStartingFromCpt;
128 gmx_bool bDoDHDL=FALSE;
129 gmx_bool do_ene,do_log,do_verbose,bRerunWarnNoV=TRUE,
130 bForceUpdate=FALSE,bCPT;
131 int mdof_flags;
132 gmx_bool bMasterState;
133 int force_flags,cglo_flags;
134 tensor force_vir,shake_vir,total_vir,tmp_vir,pres;
135 int i,m;
136 t_trxstatus *status;
137 rvec mu_tot;
138 t_vcm *vcm;
139 t_state *bufstate=NULL;
140 matrix *scale_tot,pcoupl_mu,M,ebox;
141 gmx_nlheur_t nlh;
142 t_trxframe rerun_fr;
143 gmx_repl_ex_t repl_ex=NULL;
144 int nchkpt=1;
146 gmx_localtop_t *top;
147 t_mdebin *mdebin=NULL;
148 t_state *state=NULL;
149 rvec *f_global=NULL;
150 int n_xtc=-1;
151 rvec *x_xtc=NULL;
152 gmx_enerdata_t *enerd;
153 rvec *f=NULL;
154 gmx_global_stat_t gstat;
155 gmx_update_t upd=NULL;
156 t_graph *graph=NULL;
157 globsig_t gs;
159 gmx_bool bFFscan;
160 gmx_groups_t *groups;
161 gmx_ekindata_t *ekind, *ekind_save;
162 gmx_shellfc_t shellfc;
163 int count,nconverged=0;
164 real timestep=0;
165 double tcount=0;
166 gmx_bool bIonize=FALSE;
167 gmx_bool bTCR=FALSE,bConverged=TRUE,bOK,bSumEkinhOld,bExchanged;
168 gmx_bool bAppend;
169 gmx_bool bResetCountersHalfMaxH=FALSE;
170 gmx_bool bVV,bIterations,bFirstIterate,bTemp,bPres,bTrotter;
171 real temp0,mu_aver=0,dvdl;
172 int a0,a1,gnx=0,ii;
173 atom_id *grpindex=NULL;
174 char *grpname;
175 t_coupl_rec *tcr=NULL;
176 rvec *xcopy=NULL,*vcopy=NULL,*cbuf=NULL;
177 matrix boxcopy={{0}},lastbox;
178 tensor tmpvir;
179 real fom,oldfom,veta_save,pcurr,scalevir,tracevir;
180 real vetanew = 0;
181 double cycles;
182 real saved_conserved_quantity = 0;
183 real last_ekin = 0;
184 int iter_i;
185 t_extmass MassQ;
186 int **trotter_seq;
187 char sbuf[STEPSTRSIZE],sbuf2[STEPSTRSIZE];
188 int handled_stop_condition=gmx_stop_cond_none; /* compare to get_stop_condition*/
189 gmx_iterate_t iterate;
190 gmx_large_int_t multisim_nsteps=-1; /* number of steps to do before first multisim
191 simulation stops. If equal to zero, don't
192 communicate any more between multisims.*/
193 #ifdef GMX_FAHCORE
194 /* Temporary addition for FAHCORE checkpointing */
195 int chkpt_ret;
196 #endif
198 /* Check for special mdrun options */
199 bRerunMD = (Flags & MD_RERUN);
200 bIonize = (Flags & MD_IONIZE);
201 bFFscan = (Flags & MD_FFSCAN);
202 bAppend = (Flags & MD_APPENDFILES);
203 if (Flags & MD_RESETCOUNTERSHALFWAY)
205 if (ir->nsteps > 0)
207 /* Signal to reset the counters half the simulation steps. */
208 wcycle_set_reset_counters(wcycle,ir->nsteps/2);
210 /* Signal to reset the counters halfway the simulation time. */
211 bResetCountersHalfMaxH = (max_hours > 0);
214 /* md-vv uses averaged full step velocities for T-control
215 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
216 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
217 bVV = EI_VV(ir->eI);
218 if (bVV) /* to store the initial velocities while computing virial */
220 snew(cbuf,top_global->natoms);
222 /* all the iteratative cases - only if there are constraints */
223 bIterations = ((IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
224 bTrotter = (bVV && (IR_NPT_TROTTER(ir) || (IR_NVT_TROTTER(ir))));
226 if (bRerunMD)
228 /* Since we don't know if the frames read are related in any way,
229 * rebuild the neighborlist at every step.
231 ir->nstlist = 1;
232 ir->nstcalcenergy = 1;
233 nstglobalcomm = 1;
236 check_ir_old_tpx_versions(cr,fplog,ir,top_global);
238 nstglobalcomm = check_nstglobalcomm(fplog,cr,nstglobalcomm,ir);
239 bGStatEveryStep = (nstglobalcomm == 1);
241 if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
243 fprintf(fplog,
244 "To reduce the energy communication with nstlist = -1\n"
245 "the neighbor list validity should not be checked at every step,\n"
246 "this means that exact integration is not guaranteed.\n"
247 "The neighbor list validity is checked after:\n"
248 " <n.list life time> - 2*std.dev.(n.list life time) steps.\n"
249 "In most cases this will result in exact integration.\n"
250 "This reduces the energy communication by a factor of 2 to 3.\n"
251 "If you want less energy communication, set nstlist > 3.\n\n");
254 if (bRerunMD || bFFscan)
256 ir->nstxtcout = 0;
258 groups = &top_global->groups;
260 /* Initial values */
261 init_md(fplog,cr,ir,oenv,&t,&t0,&state_global->lambda,&lam0,
262 nrnb,top_global,&upd,
263 nfile,fnm,&outf,&mdebin,
264 force_vir,shake_vir,mu_tot,&bSimAnn,&vcm,state_global,Flags);
266 clear_mat(total_vir);
267 clear_mat(pres);
268 /* Energy terms and groups */
269 snew(enerd,1);
270 init_enerdata(top_global->groups.grps[egcENER].nr,ir->n_flambda,enerd);
271 if (DOMAINDECOMP(cr))
273 f = NULL;
275 else
277 snew(f,top_global->natoms);
280 /* Kinetic energy data */
281 snew(ekind,1);
282 init_ekindata(fplog,top_global,&(ir->opts),ekind);
283 /* needed for iteration of constraints */
284 snew(ekind_save,1);
285 init_ekindata(fplog,top_global,&(ir->opts),ekind_save);
286 /* Copy the cos acceleration to the groups struct */
287 ekind->cosacc.cos_accel = ir->cos_accel;
289 gstat = global_stat_init(ir);
290 debug_gmx();
292 /* Check for polarizable models and flexible constraints */
293 shellfc = init_shell_flexcon(fplog,
294 top_global,n_flexible_constraints(constr),
295 (ir->bContinuation ||
296 (DOMAINDECOMP(cr) && !MASTER(cr))) ?
297 NULL : state_global->x);
299 if (DEFORM(*ir))
301 #ifdef GMX_THREADS
302 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
303 #endif
304 set_deform_reference_box(upd,
305 deform_init_init_step_tpx,
306 deform_init_box_tpx);
307 #ifdef GMX_THREADS
308 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
309 #endif
313 double io = compute_io(ir,top_global->natoms,groups,mdebin->ebin->nener,1);
314 if ((io > 2000) && MASTER(cr))
315 fprintf(stderr,
316 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
317 io);
320 if (DOMAINDECOMP(cr)) {
321 top = dd_init_local_top(top_global);
323 snew(state,1);
324 dd_init_local_state(cr->dd,state_global,state);
326 if (DDMASTER(cr->dd) && ir->nstfout) {
327 snew(f_global,state_global->natoms);
329 } else {
330 if (PAR(cr)) {
331 /* Initialize the particle decomposition and split the topology */
332 top = split_system(fplog,top_global,ir,cr);
334 pd_cg_range(cr,&fr->cg0,&fr->hcg);
335 pd_at_range(cr,&a0,&a1);
336 } else {
337 top = gmx_mtop_generate_local_top(top_global,ir);
339 a0 = 0;
340 a1 = top_global->natoms;
343 state = partdec_init_local_state(cr,state_global);
344 f_global = f;
346 atoms2md(top_global,ir,0,NULL,a0,a1-a0,mdatoms);
348 if (vsite) {
349 set_vsite_top(vsite,top,mdatoms,cr);
352 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols) {
353 graph = mk_graph(fplog,&(top->idef),0,top_global->natoms,FALSE,FALSE);
356 if (shellfc) {
357 make_local_shells(cr,mdatoms,shellfc);
360 if (ir->pull && PAR(cr)) {
361 dd_make_local_pull_groups(NULL,ir->pull,mdatoms);
365 if (DOMAINDECOMP(cr))
367 /* Distribute the charge groups over the nodes from the master node */
368 dd_partition_system(fplog,ir->init_step,cr,TRUE,1,
369 state_global,top_global,ir,
370 state,&f,mdatoms,top,fr,
371 vsite,shellfc,constr,
372 nrnb,wcycle,FALSE);
375 update_mdatoms(mdatoms,state->lambda);
377 if (MASTER(cr))
379 if (opt2bSet("-cpi",nfile,fnm))
381 /* Update mdebin with energy history if appending to output files */
382 if ( Flags & MD_APPENDFILES )
384 restore_energyhistory_from_state(mdebin,&state_global->enerhist);
386 else
388 /* We might have read an energy history from checkpoint,
389 * free the allocated memory and reset the counts.
391 done_energyhistory(&state_global->enerhist);
392 init_energyhistory(&state_global->enerhist);
395 /* Set the initial energy history in state by updating once */
396 update_energyhistory(&state_global->enerhist,mdebin);
399 if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG)) {
400 /* Set the random state if we read a checkpoint file */
401 set_stochd_state(upd,state);
404 /* Initialize constraints */
405 if (constr) {
406 if (!DOMAINDECOMP(cr))
407 set_constraints(constr,top,ir,mdatoms,cr);
410 /* Check whether we have to GCT stuff */
411 bTCR = ftp2bSet(efGCT,nfile,fnm);
412 if (bTCR) {
413 if (MASTER(cr)) {
414 fprintf(stderr,"Will do General Coupling Theory!\n");
416 gnx = top_global->mols.nr;
417 snew(grpindex,gnx);
418 for(i=0; (i<gnx); i++) {
419 grpindex[i] = i;
423 if (repl_ex_nst > 0)
425 /* We need to be sure replica exchange can only occur
426 * when the energies are current */
427 check_nst_param(fplog,cr,"nstcalcenergy",ir->nstcalcenergy,
428 "repl_ex_nst",&repl_ex_nst);
429 /* This check needs to happen before inter-simulation
430 * signals are initialized, too */
432 if (repl_ex_nst > 0 && MASTER(cr))
433 repl_ex = init_replica_exchange(fplog,cr->ms,state_global,ir,
434 repl_ex_nst,repl_ex_seed);
436 if (!ir->bContinuation && !bRerunMD)
438 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
440 /* Set the velocities of frozen particles to zero */
441 for(i=mdatoms->start; i<mdatoms->start+mdatoms->homenr; i++)
443 for(m=0; m<DIM; m++)
445 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
447 state->v[i][m] = 0;
453 if (constr)
455 /* Constrain the initial coordinates and velocities */
456 do_constrain_first(fplog,constr,ir,mdatoms,state,f,
457 graph,cr,nrnb,fr,top,shake_vir);
459 if (vsite)
461 /* Construct the virtual sites for the initial configuration */
462 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,NULL,
463 top->idef.iparams,top->idef.il,
464 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
468 debug_gmx();
470 /* I'm assuming we need global communication the first time! MRS */
471 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
472 | (bVV ? CGLO_PRESSURE:0)
473 | (bVV ? CGLO_CONSTRAINT:0)
474 | (bRerunMD ? CGLO_RERUNMD:0)
475 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN:0));
477 bSumEkinhOld = FALSE;
478 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
479 NULL,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
480 constr,NULL,FALSE,state->box,
481 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,cglo_flags);
482 if (ir->eI == eiVVAK) {
483 /* a second call to get the half step temperature initialized as well */
484 /* we do the same call as above, but turn the pressure off -- internally to
485 compute_globals, this is recognized as a velocity verlet half-step
486 kinetic energy calculation. This minimized excess variables, but
487 perhaps loses some logic?*/
489 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
490 NULL,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
491 constr,NULL,FALSE,state->box,
492 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
493 cglo_flags &~ CGLO_PRESSURE);
496 /* Calculate the initial half step temperature, and save the ekinh_old */
497 if (!(Flags & MD_STARTFROMCPT))
499 for(i=0; (i<ir->opts.ngtc); i++)
501 copy_mat(ekind->tcstat[i].ekinh,ekind->tcstat[i].ekinh_old);
504 if (ir->eI != eiVV)
506 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
507 and there is no previous step */
509 temp0 = enerd->term[F_TEMP];
511 /* if using an iterative algorithm, we need to create a working directory for the state. */
512 if (bIterations)
514 bufstate = init_bufstate(state);
516 if (bFFscan)
518 snew(xcopy,state->natoms);
519 snew(vcopy,state->natoms);
520 copy_rvecn(state->x,xcopy,0,state->natoms);
521 copy_rvecn(state->v,vcopy,0,state->natoms);
522 copy_mat(state->box,boxcopy);
525 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
526 temperature control */
527 trotter_seq = init_npt_vars(ir,state,&MassQ,bTrotter);
529 if (MASTER(cr))
531 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
533 fprintf(fplog,
534 "RMS relative constraint deviation after constraining: %.2e\n",
535 constr_rmsd(constr,FALSE));
537 fprintf(fplog,"Initial temperature: %g K\n",enerd->term[F_TEMP]);
538 if (bRerunMD)
540 fprintf(stderr,"starting md rerun '%s', reading coordinates from"
541 " input trajectory '%s'\n\n",
542 *(top_global->name),opt2fn("-rerun",nfile,fnm));
543 if (bVerbose)
545 fprintf(stderr,"Calculated time to finish depends on nsteps from "
546 "run input file,\nwhich may not correspond to the time "
547 "needed to process input trajectory.\n\n");
550 else
552 char tbuf[20];
553 fprintf(stderr,"starting mdrun '%s'\n",
554 *(top_global->name));
555 if (ir->nsteps >= 0)
557 sprintf(tbuf,"%8.1f",(ir->init_step+ir->nsteps)*ir->delta_t);
559 else
561 sprintf(tbuf,"%s","infinite");
563 if (ir->init_step > 0)
565 fprintf(stderr,"%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
566 gmx_step_str(ir->init_step+ir->nsteps,sbuf),tbuf,
567 gmx_step_str(ir->init_step,sbuf2),
568 ir->init_step*ir->delta_t);
570 else
572 fprintf(stderr,"%s steps, %s ps.\n",
573 gmx_step_str(ir->nsteps,sbuf),tbuf);
576 fprintf(fplog,"\n");
579 /* Set and write start time */
580 runtime_start(runtime);
581 print_date_and_time(fplog,cr->nodeid,"Started mdrun",runtime);
582 wallcycle_start(wcycle,ewcRUN);
583 if (fplog)
584 fprintf(fplog,"\n");
586 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
587 #ifdef GMX_FAHCORE
588 chkpt_ret=fcCheckPointParallel( cr->nodeid,
589 NULL,0);
590 if ( chkpt_ret == 0 )
591 gmx_fatal( 3,__FILE__,__LINE__, "Checkpoint error on step %d\n", 0 );
592 #endif
594 debug_gmx();
595 /***********************************************************
597 * Loop over MD steps
599 ************************************************************/
601 /* if rerunMD then read coordinates and velocities from input trajectory */
602 if (bRerunMD)
604 if (getenv("GMX_FORCE_UPDATE"))
606 bForceUpdate = TRUE;
609 rerun_fr.natoms = 0;
610 if (MASTER(cr))
612 bNotLastFrame = read_first_frame(oenv,&status,
613 opt2fn("-rerun",nfile,fnm),
614 &rerun_fr,TRX_NEED_X | TRX_READ_V);
615 if (rerun_fr.natoms != top_global->natoms)
617 gmx_fatal(FARGS,
618 "Number of atoms in trajectory (%d) does not match the "
619 "run input file (%d)\n",
620 rerun_fr.natoms,top_global->natoms);
622 if (ir->ePBC != epbcNONE)
624 if (!rerun_fr.bBox)
626 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);
628 if (max_cutoff2(ir->ePBC,rerun_fr.box) < sqr(fr->rlistlong))
630 gmx_fatal(FARGS,"Rerun trajectory frame step %d time %f has too small box dimensions",rerun_fr.step,rerun_fr.time);
635 if (PAR(cr))
637 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
640 if (ir->ePBC != epbcNONE)
642 /* Set the shift vectors.
643 * Necessary here when have a static box different from the tpr box.
645 calc_shifts(rerun_fr.box,fr->shift_vec);
649 /* loop over MD steps or if rerunMD to end of input trajectory */
650 bFirstStep = TRUE;
651 /* Skip the first Nose-Hoover integration when we get the state from tpx */
652 bStateFromTPX = !opt2bSet("-cpi",nfile,fnm);
653 bInitStep = bFirstStep && (bStateFromTPX || bVV);
654 bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
655 bLastStep = FALSE;
656 bSumEkinhOld = FALSE;
657 bExchanged = FALSE;
659 init_global_signals(&gs,cr,ir,repl_ex_nst);
661 step = ir->init_step;
662 step_rel = 0;
664 if (ir->nstlist == -1)
666 init_nlistheuristics(&nlh,bGStatEveryStep,step);
669 if (MULTISIM(cr) && (repl_ex_nst <=0 ))
671 /* check how many steps are left in other sims */
672 multisim_nsteps=get_multisim_nsteps(cr, ir->nsteps);
676 /* and stop now if we should */
677 bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps) ||
678 ((multisim_nsteps >= 0) && (step_rel >= multisim_nsteps )));
679 while (!bLastStep || (bRerunMD && bNotLastFrame)) {
681 wallcycle_start(wcycle,ewcSTEP);
683 GMX_MPE_LOG(ev_timestep1);
685 if (bRerunMD) {
686 if (rerun_fr.bStep) {
687 step = rerun_fr.step;
688 step_rel = step - ir->init_step;
690 if (rerun_fr.bTime) {
691 t = rerun_fr.time;
693 else
695 t = step;
698 else
700 bLastStep = (step_rel == ir->nsteps);
701 t = t0 + step*ir->delta_t;
704 if (ir->efep != efepNO)
706 if (bRerunMD && rerun_fr.bLambda && (ir->delta_lambda!=0))
708 state_global->lambda = rerun_fr.lambda;
710 else
712 state_global->lambda = lam0 + step*ir->delta_lambda;
714 state->lambda = state_global->lambda;
715 bDoDHDL = do_per_step(step,ir->nstdhdl);
718 if (bSimAnn)
720 update_annealing_target_temp(&(ir->opts),t);
723 if (bRerunMD)
725 if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
727 for(i=0; i<state_global->natoms; i++)
729 copy_rvec(rerun_fr.x[i],state_global->x[i]);
731 if (rerun_fr.bV)
733 for(i=0; i<state_global->natoms; i++)
735 copy_rvec(rerun_fr.v[i],state_global->v[i]);
738 else
740 for(i=0; i<state_global->natoms; i++)
742 clear_rvec(state_global->v[i]);
744 if (bRerunWarnNoV)
746 fprintf(stderr,"\nWARNING: Some frames do not contain velocities.\n"
747 " Ekin, temperature and pressure are incorrect,\n"
748 " the virial will be incorrect when constraints are present.\n"
749 "\n");
750 bRerunWarnNoV = FALSE;
754 copy_mat(rerun_fr.box,state_global->box);
755 copy_mat(state_global->box,state->box);
757 if (vsite && (Flags & MD_RERUN_VSITE))
759 if (DOMAINDECOMP(cr))
761 gmx_fatal(FARGS,"Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
763 if (graph)
765 /* Following is necessary because the graph may get out of sync
766 * with the coordinates if we only have every N'th coordinate set
768 mk_mshift(fplog,graph,fr->ePBC,state->box,state->x);
769 shift_self(graph,state->box,state->x);
771 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
772 top->idef.iparams,top->idef.il,
773 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
774 if (graph)
776 unshift_self(graph,state->box,state->x);
781 /* Stop Center of Mass motion */
782 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step,ir->nstcomm));
784 /* Copy back starting coordinates in case we're doing a forcefield scan */
785 if (bFFscan)
787 for(ii=0; (ii<state->natoms); ii++)
789 copy_rvec(xcopy[ii],state->x[ii]);
790 copy_rvec(vcopy[ii],state->v[ii]);
792 copy_mat(boxcopy,state->box);
795 if (bRerunMD)
797 /* for rerun MD always do Neighbour Searching */
798 bNS = (bFirstStep || ir->nstlist != 0);
799 bNStList = bNS;
801 else
803 /* Determine whether or not to do Neighbour Searching and LR */
804 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
806 bNS = (bFirstStep || bExchanged || bNStList ||
807 (ir->nstlist == -1 && nlh.nabnsb > 0));
809 if (bNS && ir->nstlist == -1)
811 set_nlistheuristics(&nlh,bFirstStep || bExchanged,step);
815 /* check whether we should stop because another simulation has
816 stopped. */
817 if (MULTISIM(cr))
819 if ( (multisim_nsteps >= 0) && (step_rel >= multisim_nsteps) &&
820 (multisim_nsteps != ir->nsteps) )
822 if (bNS)
824 if (MASTER(cr))
826 fprintf(stderr,
827 "Stopping simulation %d because another one has finished\n",
828 cr->ms->sim);
830 bLastStep=TRUE;
831 gs.sig[eglsCHKPT] = 1;
836 /* < 0 means stop at next step, > 0 means stop at next NS step */
837 if ( (gs.set[eglsSTOPCOND] < 0 ) ||
838 ( (gs.set[eglsSTOPCOND] > 0 ) && ( bNS || ir->nstlist==0)) )
840 bLastStep = TRUE;
843 /* Determine whether or not to update the Born radii if doing GB */
844 bBornRadii=bFirstStep;
845 if (ir->implicit_solvent && (step % ir->nstgbradii==0))
847 bBornRadii=TRUE;
850 do_log = do_per_step(step,ir->nstlog) || bFirstStep || bLastStep;
851 do_verbose = bVerbose &&
852 (step % stepout == 0 || bFirstStep || bLastStep);
854 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
856 if (bRerunMD)
858 bMasterState = TRUE;
860 else
862 bMasterState = FALSE;
863 /* Correct the new box if it is too skewed */
864 if (DYNAMIC_BOX(*ir))
866 if (correct_box(fplog,step,state->box,graph))
868 bMasterState = TRUE;
871 if (DOMAINDECOMP(cr) && bMasterState)
873 dd_collect_state(cr->dd,state,state_global);
877 if (DOMAINDECOMP(cr))
879 /* Repartition the domain decomposition */
880 wallcycle_start(wcycle,ewcDOMDEC);
881 dd_partition_system(fplog,step,cr,
882 bMasterState,nstglobalcomm,
883 state_global,top_global,ir,
884 state,&f,mdatoms,top,fr,
885 vsite,shellfc,constr,
886 nrnb,wcycle,do_verbose);
887 wallcycle_stop(wcycle,ewcDOMDEC);
888 /* If using an iterative integrator, reallocate space to match the decomposition */
892 if (MASTER(cr) && do_log && !bFFscan)
894 print_ebin_header(fplog,step,t,state->lambda);
897 if (ir->efep != efepNO)
899 update_mdatoms(mdatoms,state->lambda);
902 if (bRerunMD && rerun_fr.bV)
905 /* We need the kinetic energy at minus the half step for determining
906 * the full step kinetic energy and possibly for T-coupling.*/
907 /* This may not be quite working correctly yet . . . . */
908 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
909 wcycle,enerd,NULL,NULL,NULL,NULL,mu_tot,
910 constr,NULL,FALSE,state->box,
911 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
912 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
914 clear_mat(force_vir);
916 /* Ionize the atoms if necessary */
917 if (bIonize)
919 ionize(fplog,oenv,mdatoms,top_global,t,ir,state->x,state->v,
920 mdatoms->start,mdatoms->start+mdatoms->homenr,state->box,cr);
923 /* Update force field in ffscan program */
924 if (bFFscan)
926 if (update_forcefield(fplog,
927 nfile,fnm,fr,
928 mdatoms->nr,state->x,state->box)) {
929 if (gmx_parallel_env_initialized())
931 gmx_finalize();
933 exit(0);
937 GMX_MPE_LOG(ev_timestep2);
939 /* We write a checkpoint at this MD step when:
940 * either at an NS step when we signalled through gs,
941 * or at the last step (but not when we do not want confout),
942 * but never at the first step or with rerun.
944 bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
945 (bLastStep && (Flags & MD_CONFOUT))) &&
946 step > ir->init_step && !bRerunMD);
947 if (bCPT)
949 gs.set[eglsCHKPT] = 0;
952 /* Determine the energy and pressure:
953 * at nstcalcenergy steps and at energy output steps (set below).
955 bNstEner = do_per_step(step,ir->nstcalcenergy);
956 bCalcEnerPres =
957 (bNstEner ||
958 (ir->epc != epcNO && do_per_step(step,ir->nstpcouple)));
960 /* Do we need global communication ? */
961 bGStat = (bCalcEnerPres || bStopCM ||
962 do_per_step(step,nstglobalcomm) ||
963 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
965 do_ene = (do_per_step(step,ir->nstenergy) || bLastStep);
967 if (do_ene || do_log)
969 bCalcEnerPres = TRUE;
970 bGStat = TRUE;
973 /* these CGLO_ options remain the same throughout the iteration */
974 cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
975 (bStopCM ? CGLO_STOPCM : 0) |
976 (bGStat ? CGLO_GSTAT : 0)
979 force_flags = (GMX_FORCE_STATECHANGED |
980 ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
981 GMX_FORCE_ALLFORCES |
982 (bNStList ? GMX_FORCE_DOLR : 0) |
983 GMX_FORCE_SEPLRF |
984 (bCalcEnerPres ? GMX_FORCE_VIRIAL : 0) |
985 (bDoDHDL ? GMX_FORCE_DHDL : 0)
988 if (shellfc)
990 /* Now is the time to relax the shells */
991 count=relax_shell_flexcon(fplog,cr,bVerbose,bFFscan ? step+1 : step,
992 ir,bNS,force_flags,
993 bStopCM,top,top_global,
994 constr,enerd,fcd,
995 state,f,force_vir,mdatoms,
996 nrnb,wcycle,graph,groups,
997 shellfc,fr,bBornRadii,t,mu_tot,
998 state->natoms,&bConverged,vsite,
999 outf->fp_field);
1000 tcount+=count;
1002 if (bConverged)
1004 nconverged++;
1007 else
1009 /* The coordinates (x) are shifted (to get whole molecules)
1010 * in do_force.
1011 * This is parallellized as well, and does communication too.
1012 * Check comments in sim_util.c
1015 do_force(fplog,cr,ir,step,nrnb,wcycle,top,top_global,groups,
1016 state->box,state->x,&state->hist,
1017 f,force_vir,mdatoms,enerd,fcd,
1018 state->lambda,graph,
1019 fr,vsite,mu_tot,t,outf->fp_field,ed,bBornRadii,
1020 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1023 GMX_BARRIER(cr->mpi_comm_mygroup);
1025 if (bTCR)
1027 mu_aver = calc_mu_aver(cr,state->x,mdatoms->chargeA,
1028 mu_tot,&top_global->mols,mdatoms,gnx,grpindex);
1031 if (bTCR && bFirstStep)
1033 tcr=init_coupling(fplog,nfile,fnm,cr,fr,mdatoms,&(top->idef));
1034 fprintf(fplog,"Done init_coupling\n");
1035 fflush(fplog);
1038 if (bVV && !bStartingFromCpt && !bRerunMD)
1039 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1041 if (ir->eI==eiVV && bInitStep)
1043 /* if using velocity verlet with full time step Ekin,
1044 * take the first half step only to compute the
1045 * virial for the first step. From there,
1046 * revert back to the initial coordinates
1047 * so that the input is actually the initial step.
1049 copy_rvecn(state->v,cbuf,0,state->natoms); /* should make this better for parallelizing? */
1050 } else {
1051 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1052 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ1);
1055 update_coords(fplog,step,ir,mdatoms,state,
1056 f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1057 ekind,M,wcycle,upd,bInitStep,etrtVELOCITY1,
1058 cr,nrnb,constr,&top->idef);
1060 if (bIterations)
1062 gmx_iterate_init(&iterate,bIterations && !bInitStep);
1064 /* for iterations, we save these vectors, as we will be self-consistently iterating
1065 the calculations */
1067 /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1069 /* save the state */
1070 if (bIterations && iterate.bIterate) {
1071 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1074 bFirstIterate = TRUE;
1075 while (bFirstIterate || (bIterations && iterate.bIterate))
1077 if (bIterations && iterate.bIterate)
1079 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
1080 if (bFirstIterate && bTrotter)
1082 /* The first time through, we need a decent first estimate
1083 of veta(t+dt) to compute the constraints. Do
1084 this by computing the box volume part of the
1085 trotter integration at this time. Nothing else
1086 should be changed by this routine here. If
1087 !(first time), we start with the previous value
1088 of veta. */
1090 veta_save = state->veta;
1091 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ0);
1092 vetanew = state->veta;
1093 state->veta = veta_save;
1097 bOK = TRUE;
1098 if ( !bRerunMD || rerun_fr.bV || bForceUpdate) { /* Why is rerun_fr.bV here? Unclear. */
1099 dvdl = 0;
1101 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
1102 &top->idef,shake_vir,NULL,
1103 cr,nrnb,wcycle,upd,constr,
1104 bInitStep,TRUE,bCalcEnerPres,vetanew);
1106 if (!bOK && !bFFscan)
1108 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
1112 else if (graph)
1113 { /* Need to unshift here if a do_force has been
1114 called in the previous step */
1115 unshift_self(graph,state->box,state->x);
1119 /* if VV, compute the pressure and constraints */
1120 /* For VV2, we strictly only need this if using pressure
1121 * control, but we really would like to have accurate pressures
1122 * printed out.
1123 * Think about ways around this in the future?
1124 * For now, keep this choice in comments.
1126 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
1127 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
1128 bPres = TRUE;
1129 bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK));
1130 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1131 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1132 constr,NULL,FALSE,state->box,
1133 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1134 cglo_flags
1135 | CGLO_ENERGY
1136 | (bTemp ? CGLO_TEMPERATURE:0)
1137 | (bPres ? CGLO_PRESSURE : 0)
1138 | (bPres ? CGLO_CONSTRAINT : 0)
1139 | ((bIterations && iterate.bIterate) ? CGLO_ITERATE : 0)
1140 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1141 | CGLO_SCALEEKIN
1143 /* explanation of above:
1144 a) We compute Ekin at the full time step
1145 if 1) we are using the AveVel Ekin, and it's not the
1146 initial step, or 2) if we are using AveEkin, but need the full
1147 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1148 b) If we are using EkinAveEkin for the kinetic energy for the temperture control, we still feed in
1149 EkinAveVel because it's needed for the pressure */
1151 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1152 if (!bInitStep)
1154 if (bTrotter)
1156 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ2);
1158 else
1160 update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
1164 if (bIterations &&
1165 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
1166 state->veta,&vetanew))
1168 break;
1170 bFirstIterate = FALSE;
1173 if (bTrotter && !bInitStep) {
1174 copy_mat(shake_vir,state->svir_prev);
1175 copy_mat(force_vir,state->fvir_prev);
1176 if (IR_NVT_TROTTER(ir) && ir->eI==eiVV) {
1177 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1178 enerd->term[F_TEMP] = sum_ekin(&(ir->opts),ekind,NULL,(ir->eI==eiVV),FALSE,FALSE);
1179 enerd->term[F_EKIN] = trace(ekind->ekin);
1182 /* if it's the initial step, we performed this first step just to get the constraint virial */
1183 if (bInitStep && ir->eI==eiVV) {
1184 copy_rvecn(cbuf,state->v,0,state->natoms);
1187 if (fr->bSepDVDL && fplog && do_log)
1189 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
1191 enerd->term[F_DHDL_CON] += dvdl;
1193 GMX_MPE_LOG(ev_timestep1);
1196 /* MRS -- now done iterating -- compute the conserved quantity */
1197 if (bVV) {
1198 saved_conserved_quantity = compute_conserved_from_auxiliary(ir,state,&MassQ);
1199 if (ir->eI==eiVV)
1201 last_ekin = enerd->term[F_EKIN]; /* does this get preserved through checkpointing? */
1203 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1205 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1209 /* ######## END FIRST UPDATE STEP ############## */
1210 /* ######## If doing VV, we now have v(dt) ###### */
1212 /* ################## START TRAJECTORY OUTPUT ################# */
1214 /* Now we have the energies and forces corresponding to the
1215 * coordinates at time t. We must output all of this before
1216 * the update.
1217 * for RerunMD t is read from input trajectory
1219 GMX_MPE_LOG(ev_output_start);
1221 mdof_flags = 0;
1222 if (do_per_step(step,ir->nstxout)) { mdof_flags |= MDOF_X; }
1223 if (do_per_step(step,ir->nstvout)) { mdof_flags |= MDOF_V; }
1224 if (do_per_step(step,ir->nstfout)) { mdof_flags |= MDOF_F; }
1225 if (do_per_step(step,ir->nstxtcout)) { mdof_flags |= MDOF_XTC; }
1226 if (bCPT) { mdof_flags |= MDOF_CPT; };
1228 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
1229 if (bLastStep)
1231 /* Enforce writing positions and velocities at end of run */
1232 mdof_flags |= (MDOF_X | MDOF_V);
1234 #endif
1235 #ifdef GMX_FAHCORE
1236 if (MASTER(cr))
1237 fcReportProgress( ir->nsteps, step );
1239 /* sync bCPT and fc record-keeping */
1240 if (bCPT && MASTER(cr))
1241 fcRequestCheckPoint();
1242 #endif
1244 if (mdof_flags != 0)
1246 wallcycle_start(wcycle,ewcTRAJ);
1247 if (bCPT)
1249 if (state->flags & (1<<estLD_RNG))
1251 get_stochd_state(upd,state);
1253 if (MASTER(cr))
1255 if (bSumEkinhOld)
1257 state_global->ekinstate.bUpToDate = FALSE;
1259 else
1261 update_ekinstate(&state_global->ekinstate,ekind);
1262 state_global->ekinstate.bUpToDate = TRUE;
1264 update_energyhistory(&state_global->enerhist,mdebin);
1267 write_traj(fplog,cr,outf,mdof_flags,top_global,
1268 step,t,state,state_global,f,f_global,&n_xtc,&x_xtc);
1269 if (bCPT)
1271 nchkpt++;
1272 bCPT = FALSE;
1274 debug_gmx();
1275 if (bLastStep && step_rel == ir->nsteps &&
1276 (Flags & MD_CONFOUT) && MASTER(cr) &&
1277 !bRerunMD && !bFFscan)
1279 /* x and v have been collected in write_traj,
1280 * because a checkpoint file will always be written
1281 * at the last step.
1283 fprintf(stderr,"\nWriting final coordinates.\n");
1284 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols &&
1285 DOMAINDECOMP(cr))
1287 /* Make molecules whole only for confout writing */
1288 do_pbc_mtop(fplog,ir->ePBC,state->box,top_global,state_global->x);
1290 write_sto_conf_mtop(ftp2fn(efSTO,nfile,fnm),
1291 *top_global->name,top_global,
1292 state_global->x,state_global->v,
1293 ir->ePBC,state->box);
1294 debug_gmx();
1296 wallcycle_stop(wcycle,ewcTRAJ);
1298 GMX_MPE_LOG(ev_output_finish);
1300 /* kludge -- virial is lost with restart for NPT control. Must restart */
1301 if (bStartingFromCpt && bVV)
1303 copy_mat(state->svir_prev,shake_vir);
1304 copy_mat(state->fvir_prev,force_vir);
1306 /* ################## END TRAJECTORY OUTPUT ################ */
1308 /* Determine the wallclock run time up till now */
1309 run_time = gmx_gettime() - (double)runtime->real;
1311 /* Check whether everything is still allright */
1312 if (((int)gmx_get_stop_condition() > handled_stop_condition)
1313 #ifdef GMX_THREADS
1314 && MASTER(cr)
1315 #endif
1318 /* this is just make gs.sig compatible with the hack
1319 of sending signals around by MPI_Reduce with together with
1320 other floats */
1321 if ( gmx_get_stop_condition() == gmx_stop_cond_next_ns )
1322 gs.sig[eglsSTOPCOND]=1;
1323 if ( gmx_get_stop_condition() == gmx_stop_cond_next )
1324 gs.sig[eglsSTOPCOND]=-1;
1325 /* < 0 means stop at next step, > 0 means stop at next NS step */
1326 if (fplog)
1328 fprintf(fplog,
1329 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1330 gmx_get_signal_name(),
1331 gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
1332 fflush(fplog);
1334 fprintf(stderr,
1335 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1336 gmx_get_signal_name(),
1337 gs.sig[eglsSTOPCOND]==1 ? "NS " : "");
1338 fflush(stderr);
1339 handled_stop_condition=(int)gmx_get_stop_condition();
1341 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1342 (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
1343 gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
1345 /* Signal to terminate the run */
1346 gs.sig[eglsSTOPCOND] = 1;
1347 if (fplog)
1349 fprintf(fplog,"\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
1351 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n",gmx_step_str(step,sbuf),max_hours*0.99);
1354 if (bResetCountersHalfMaxH && MASTER(cr) &&
1355 run_time > max_hours*60.0*60.0*0.495)
1357 gs.sig[eglsRESETCOUNTERS] = 1;
1360 if (ir->nstlist == -1 && !bRerunMD)
1362 /* When bGStatEveryStep=FALSE, global_stat is only called
1363 * when we check the atom displacements, not at NS steps.
1364 * This means that also the bonded interaction count check is not
1365 * performed immediately after NS. Therefore a few MD steps could
1366 * be performed with missing interactions.
1367 * But wrong energies are never written to file,
1368 * since energies are only written after global_stat
1369 * has been called.
1371 if (step >= nlh.step_nscheck)
1373 nlh.nabnsb = natoms_beyond_ns_buffer(ir,fr,&top->cgs,
1374 nlh.scale_tot,state->x);
1376 else
1378 /* This is not necessarily true,
1379 * but step_nscheck is determined quite conservatively.
1381 nlh.nabnsb = 0;
1385 /* In parallel we only have to check for checkpointing in steps
1386 * where we do global communication,
1387 * otherwise the other nodes don't know.
1389 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1390 cpt_period >= 0 &&
1391 (cpt_period == 0 ||
1392 run_time >= nchkpt*cpt_period*60.0)) &&
1393 gs.set[eglsCHKPT] == 0)
1395 gs.sig[eglsCHKPT] = 1;
1398 if (bIterations)
1400 gmx_iterate_init(&iterate,bIterations);
1403 /* for iterations, we save these vectors, as we will be redoing the calculations */
1404 if (bIterations && iterate.bIterate)
1406 copy_coupling_state(state,bufstate,ekind,ekind_save,&(ir->opts));
1408 bFirstIterate = TRUE;
1409 while (bFirstIterate || (bIterations && iterate.bIterate))
1411 /* We now restore these vectors to redo the calculation with improved extended variables */
1412 if (bIterations)
1414 copy_coupling_state(bufstate,state,ekind_save,ekind,&(ir->opts));
1417 /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
1418 so scroll down for that logic */
1420 /* ######### START SECOND UPDATE STEP ################# */
1421 GMX_MPE_LOG(ev_update_start);
1422 /* Box is changed in update() when we do pressure coupling,
1423 * but we should still use the old box for energy corrections and when
1424 * writing it to the energy file, so it matches the trajectory files for
1425 * the same timestep above. Make a copy in a separate array.
1427 copy_mat(state->box,lastbox);
1429 bOK = TRUE;
1430 if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
1432 wallcycle_start(wcycle,ewcUPDATE);
1433 dvdl = 0;
1434 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1435 if (bTrotter)
1437 if (bIterations && iterate.bIterate)
1439 if (bFirstIterate)
1441 scalevir = 1;
1443 else
1445 /* we use a new value of scalevir to converge the iterations faster */
1446 scalevir = tracevir/trace(shake_vir);
1448 msmul(shake_vir,scalevir,shake_vir);
1449 m_add(force_vir,shake_vir,total_vir);
1450 clear_mat(shake_vir);
1452 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ3);
1453 /* We can only do Berendsen coupling after we have summed
1454 * the kinetic energy or virial. Since the happens
1455 * in global_state after update, we should only do it at
1456 * step % nstlist = 1 with bGStatEveryStep=FALSE.
1459 else
1461 update_tcouple(fplog,step,ir,state,ekind,wcycle,upd,&MassQ,mdatoms);
1462 update_pcouple(fplog,step,ir,state,pcoupl_mu,M,wcycle,
1463 upd,bInitStep);
1466 if (bVV)
1468 /* velocity half-step update */
1469 update_coords(fplog,step,ir,mdatoms,state,f,
1470 fr->bTwinRange && bNStList,fr->f_twin,fcd,
1471 ekind,M,wcycle,upd,FALSE,etrtVELOCITY2,
1472 cr,nrnb,constr,&top->idef);
1475 /* Above, initialize just copies ekinh into ekin,
1476 * it doesn't copy position (for VV),
1477 * and entire integrator for MD.
1480 if (ir->eI==eiVVAK)
1482 copy_rvecn(state->x,cbuf,0,state->natoms);
1485 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1486 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
1487 wallcycle_stop(wcycle,ewcUPDATE);
1489 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
1490 &top->idef,shake_vir,force_vir,
1491 cr,nrnb,wcycle,upd,constr,
1492 bInitStep,FALSE,bCalcEnerPres,state->veta);
1494 if (ir->eI==eiVVAK)
1496 /* erase F_EKIN and F_TEMP here? */
1497 /* just compute the kinetic energy at the half step to perform a trotter step */
1498 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1499 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1500 constr,NULL,FALSE,lastbox,
1501 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1502 cglo_flags | CGLO_TEMPERATURE
1504 wallcycle_start(wcycle,ewcUPDATE);
1505 trotter_update(ir,step,ekind,enerd,state,total_vir,mdatoms,&MassQ,trotter_seq,ettTSEQ4);
1506 /* now we know the scaling, we can compute the positions again again */
1507 copy_rvecn(cbuf,state->x,0,state->natoms);
1509 update_coords(fplog,step,ir,mdatoms,state,f,fr->bTwinRange && bNStList,fr->f_twin,fcd,
1510 ekind,M,wcycle,upd,bInitStep,etrtPOSITION,cr,nrnb,constr,&top->idef);
1511 wallcycle_stop(wcycle,ewcUPDATE);
1513 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1514 /* are the small terms in the shake_vir here due
1515 * to numerical errors, or are they important
1516 * physically? I'm thinking they are just errors, but not completely sure.
1517 * For now, will call without actually constraining, constr=NULL*/
1518 update_constraints(fplog,step,&dvdl,ir,ekind,mdatoms,state,graph,f,
1519 &top->idef,tmp_vir,force_vir,
1520 cr,nrnb,wcycle,upd,NULL,
1521 bInitStep,FALSE,bCalcEnerPres,
1522 state->veta);
1524 if (!bOK && !bFFscan)
1526 gmx_fatal(FARGS,"Constraint error: Shake, Lincs or Settle could not solve the constrains");
1529 if (fr->bSepDVDL && fplog && do_log)
1531 fprintf(fplog,sepdvdlformat,"Constraint",0.0,dvdl);
1533 enerd->term[F_DHDL_CON] += dvdl;
1535 else if (graph)
1537 /* Need to unshift here */
1538 unshift_self(graph,state->box,state->x);
1541 GMX_BARRIER(cr->mpi_comm_mygroup);
1542 GMX_MPE_LOG(ev_update_finish);
1544 if (vsite != NULL)
1546 wallcycle_start(wcycle,ewcVSITECONSTR);
1547 if (graph != NULL)
1549 shift_self(graph,state->box,state->x);
1551 construct_vsites(fplog,vsite,state->x,nrnb,ir->delta_t,state->v,
1552 top->idef.iparams,top->idef.il,
1553 fr->ePBC,fr->bMolPBC,graph,cr,state->box);
1555 if (graph != NULL)
1557 unshift_self(graph,state->box,state->x);
1559 wallcycle_stop(wcycle,ewcVSITECONSTR);
1562 /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
1563 if (ir->nstlist == -1 && bFirstIterate)
1565 gs.sig[eglsNABNSB] = nlh.nabnsb;
1567 compute_globals(fplog,gstat,cr,ir,fr,ekind,state,state_global,mdatoms,nrnb,vcm,
1568 wcycle,enerd,force_vir,shake_vir,total_vir,pres,mu_tot,
1569 constr,
1570 bFirstIterate ? &gs : NULL,
1571 (step_rel % gs.nstms == 0) &&
1572 (multisim_nsteps<0 || (step_rel<multisim_nsteps)),
1573 lastbox,
1574 top_global,&pcurr,top_global->natoms,&bSumEkinhOld,
1575 cglo_flags
1576 | (!EI_VV(ir->eI) ? CGLO_ENERGY : 0)
1577 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1578 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
1579 | (bIterations && iterate.bIterate ? CGLO_ITERATE : 0)
1580 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1581 | CGLO_CONSTRAINT
1583 if (ir->nstlist == -1 && bFirstIterate)
1585 nlh.nabnsb = gs.set[eglsNABNSB];
1586 gs.set[eglsNABNSB] = 0;
1588 /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
1589 /* ############# END CALC EKIN AND PRESSURE ################# */
1591 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1592 the virial that should probably be addressed eventually. state->veta has better properies,
1593 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1594 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
1596 if (bIterations &&
1597 done_iterating(cr,fplog,step,&iterate,bFirstIterate,
1598 trace(shake_vir),&tracevir))
1600 break;
1602 bFirstIterate = FALSE;
1605 update_box(fplog,step,ir,mdatoms,state,graph,f,
1606 ir->nstlist==-1 ? &nlh.scale_tot : NULL,pcoupl_mu,nrnb,wcycle,upd,bInitStep,FALSE);
1608 /* ################# END UPDATE STEP 2 ################# */
1609 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
1611 /* The coordinates (x) were unshifted in update */
1612 if (bFFscan && (shellfc==NULL || bConverged))
1614 if (print_forcefield(fplog,enerd->term,mdatoms->homenr,
1615 f,NULL,xcopy,
1616 &(top_global->mols),mdatoms->massT,pres))
1618 if (gmx_parallel_env_initialized())
1620 gmx_finalize();
1622 fprintf(stderr,"\n");
1623 exit(0);
1626 if (!bGStat)
1628 /* We will not sum ekinh_old,
1629 * so signal that we still have to do it.
1631 bSumEkinhOld = TRUE;
1634 if (bTCR)
1636 /* Only do GCT when the relaxation of shells (minimization) has converged,
1637 * otherwise we might be coupling to bogus energies.
1638 * In parallel we must always do this, because the other sims might
1639 * update the FF.
1642 /* Since this is called with the new coordinates state->x, I assume
1643 * we want the new box state->box too. / EL 20040121
1645 do_coupling(fplog,oenv,nfile,fnm,tcr,t,step,enerd->term,fr,
1646 ir,MASTER(cr),
1647 mdatoms,&(top->idef),mu_aver,
1648 top_global->mols.nr,cr,
1649 state->box,total_vir,pres,
1650 mu_tot,state->x,f,bConverged);
1651 debug_gmx();
1654 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
1656 /* sum up the foreign energy and dhdl terms */
1657 sum_dhdl(enerd,state->lambda,ir);
1659 /* use the directly determined last velocity, not actually the averaged half steps */
1660 if (bTrotter && ir->eI==eiVV)
1662 enerd->term[F_EKIN] = last_ekin;
1664 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1666 if (bVV)
1668 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1670 else
1672 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir,state,&MassQ);
1674 /* Check for excessively large energies */
1675 if (bIonize)
1677 #ifdef GMX_DOUBLE
1678 real etot_max = 1e200;
1679 #else
1680 real etot_max = 1e30;
1681 #endif
1682 if (fabs(enerd->term[F_ETOT]) > etot_max)
1684 fprintf(stderr,"Energy too large (%g), giving up\n",
1685 enerd->term[F_ETOT]);
1688 /* ######### END PREPARING EDR OUTPUT ########### */
1690 /* Time for performance */
1691 if (((step % stepout) == 0) || bLastStep)
1693 runtime_upd_proc(runtime);
1696 /* Output stuff */
1697 if (MASTER(cr))
1699 gmx_bool do_dr,do_or;
1701 if (!(bStartingFromCpt && (EI_VV(ir->eI))))
1703 if (bNstEner)
1705 upd_mdebin(mdebin,bDoDHDL, TRUE,
1706 t,mdatoms->tmass,enerd,state,lastbox,
1707 shake_vir,force_vir,total_vir,pres,
1708 ekind,mu_tot,constr);
1710 else
1712 upd_mdebin_step(mdebin);
1715 do_dr = do_per_step(step,ir->nstdisreout);
1716 do_or = do_per_step(step,ir->nstorireout);
1718 print_ebin(outf->fp_ene,do_ene,do_dr,do_or,do_log?fplog:NULL,
1719 step,t,
1720 eprNORMAL,bCompact,mdebin,fcd,groups,&(ir->opts));
1722 if (ir->ePull != epullNO)
1724 pull_print_output(ir->pull,step,t);
1727 if (do_per_step(step,ir->nstlog))
1729 if(fflush(fplog) != 0)
1731 gmx_fatal(FARGS,"Cannot flush logfile - maybe you are out of quota?");
1737 /* Remaining runtime */
1738 if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal() ))
1740 if (shellfc)
1742 fprintf(stderr,"\n");
1744 print_time(stderr,runtime,step,ir,cr);
1747 /* Replica exchange */
1748 bExchanged = FALSE;
1749 if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
1750 do_per_step(step,repl_ex_nst))
1752 bExchanged = replica_exchange(fplog,cr,repl_ex,
1753 state_global,enerd->term,
1754 state,step,t);
1756 if (bExchanged && DOMAINDECOMP(cr))
1758 dd_partition_system(fplog,step,cr,TRUE,1,
1759 state_global,top_global,ir,
1760 state,&f,mdatoms,top,fr,
1761 vsite,shellfc,constr,
1762 nrnb,wcycle,FALSE);
1766 bFirstStep = FALSE;
1767 bInitStep = FALSE;
1768 bStartingFromCpt = FALSE;
1770 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
1771 /* With all integrators, except VV, we need to retain the pressure
1772 * at the current step for coupling at the next step.
1774 if ((state->flags & (1<<estPRES_PREV)) &&
1775 (bGStatEveryStep ||
1776 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
1778 /* Store the pressure in t_state for pressure coupling
1779 * at the next MD step.
1781 copy_mat(pres,state->pres_prev);
1784 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
1786 if (bRerunMD)
1788 if (MASTER(cr))
1790 /* read next frame from input trajectory */
1791 bNotLastFrame = read_next_frame(oenv,status,&rerun_fr);
1794 if (PAR(cr))
1796 rerun_parallel_comm(cr,&rerun_fr,&bNotLastFrame);
1800 if (!bRerunMD || !rerun_fr.bStep)
1802 /* increase the MD step number */
1803 step++;
1804 step_rel++;
1807 cycles = wallcycle_stop(wcycle,ewcSTEP);
1808 if (DOMAINDECOMP(cr) && wcycle)
1810 dd_cycles_add(cr->dd,cycles,ddCyclStep);
1813 if (step_rel == wcycle_get_reset_counters(wcycle) ||
1814 gs.set[eglsRESETCOUNTERS] != 0)
1816 /* Reset all the counters related to performance over the run */
1817 reset_all_counters(fplog,cr,step,&step_rel,ir,wcycle,nrnb,runtime);
1818 wcycle_set_reset_counters(wcycle,-1);
1819 /* Correct max_hours for the elapsed time */
1820 max_hours -= run_time/(60.0*60.0);
1821 bResetCountersHalfMaxH = FALSE;
1822 gs.set[eglsRESETCOUNTERS] = 0;
1826 /* End of main MD loop */
1827 debug_gmx();
1829 /* Stop the time */
1830 runtime_end(runtime);
1832 if (bRerunMD && MASTER(cr))
1834 close_trj(status);
1837 if (!(cr->duty & DUTY_PME))
1839 /* Tell the PME only node to finish */
1840 gmx_pme_finish(cr);
1843 if (MASTER(cr))
1845 if (ir->nstcalcenergy > 0 && !bRerunMD)
1847 print_ebin(outf->fp_ene,FALSE,FALSE,FALSE,fplog,step,t,
1848 eprAVER,FALSE,mdebin,fcd,groups,&(ir->opts));
1852 done_mdoutf(outf);
1854 debug_gmx();
1856 if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
1858 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)));
1859 fprintf(fplog,"Average number of atoms that crossed the half buffer length: %.1f\n\n",nlh.ab/nlh.nns);
1862 if (shellfc && fplog)
1864 fprintf(fplog,"Fraction of iterations that converged: %.2f %%\n",
1865 (nconverged*100.0)/step_rel);
1866 fprintf(fplog,"Average number of force evaluations per MD step: %.2f\n\n",
1867 tcount/step_rel);
1870 if (repl_ex_nst > 0 && MASTER(cr))
1872 print_replica_exchange_statistics(fplog,repl_ex);
1875 runtime->nsteps_done = step_rel;
1877 return 0;