2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team,
6 * check out http://www.gromacs.org for more information.
7 * Copyright (c) 2012,2013, by the GROMACS development team, led by
8 * David van der Spoel, Berk Hess, Erik Lindahl, and including many
9 * others, as listed in the AUTHORS file in the top-level source
10 * directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
58 #include "md_support.h"
59 #include "md_logging.h"
74 #include "mpelogging.h"
76 #include "domdec_network.h"
82 #include "compute_io.h"
84 #include "checkpoint.h"
85 #include "mtop_util.h"
86 #include "sighandler.h"
89 #include "pme_loadbal.h"
92 #include "types/nlistheuristics.h"
93 #include "types/iteratedconstraints.h"
94 #include "nbnxn_cuda_data_mgmt.h"
104 #include "corewrap.h"
107 static void reset_all_counters(FILE *fplog, t_commrec *cr,
108 gmx_large_int_t step,
109 gmx_large_int_t *step_rel, t_inputrec *ir,
110 gmx_wallcycle_t wcycle, t_nrnb *nrnb,
111 gmx_runtime_t *runtime,
112 nbnxn_cuda_ptr_t cu_nbv)
114 char sbuf[STEPSTRSIZE];
116 /* Reset all the counters related to performance over the run */
117 md_print_warn(cr, fplog, "step %s: resetting all time and cycle counters\n",
118 gmx_step_str(step, sbuf));
122 nbnxn_cuda_reset_timings(cu_nbv);
125 wallcycle_stop(wcycle, ewcRUN);
126 wallcycle_reset_all(wcycle);
127 if (DOMAINDECOMP(cr))
129 reset_dd_statistics_counters(cr->dd);
132 ir->init_step += *step_rel;
133 ir->nsteps -= *step_rel;
135 wallcycle_start(wcycle, ewcRUN);
136 runtime_start(runtime);
137 print_date_and_time(fplog, cr->nodeid, "Restarted time", runtime);
140 double do_md(FILE *fplog, t_commrec *cr, int nfile, const t_filenm fnm[],
141 const output_env_t oenv, gmx_bool bVerbose, gmx_bool bCompact,
143 gmx_vsite_t *vsite, gmx_constr_t constr,
144 int stepout, t_inputrec *ir,
145 gmx_mtop_t *top_global,
147 t_state *state_global,
149 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
150 gmx_edsam_t ed, t_forcerec *fr,
151 int repl_ex_nst, int repl_ex_nex, int repl_ex_seed, gmx_membed_t membed,
152 real cpt_period, real max_hours,
153 const char *deviceOptions,
155 gmx_runtime_t *runtime)
158 gmx_large_int_t step, step_rel;
160 double t, t0, lam0[efptNR];
161 gmx_bool bGStatEveryStep, bGStat, bCalcVir, bCalcEner;
162 gmx_bool bNS, bNStList, bSimAnn, bStopCM, bRerunMD, bNotLastFrame = FALSE,
163 bFirstStep, bStateFromCP, bStateFromTPX, bInitStep, bLastStep,
164 bBornRadii, bStartingFromCpt;
165 gmx_bool bDoDHDL = FALSE, bDoFEP = FALSE, bDoExpanded = FALSE;
166 gmx_bool do_ene, do_log, do_verbose, bRerunWarnNoV = TRUE,
167 bForceUpdate = FALSE, bCPT;
169 gmx_bool bMasterState;
170 int force_flags, cglo_flags;
171 tensor force_vir, shake_vir, total_vir, tmp_vir, pres;
176 t_state *bufstate = NULL;
177 matrix *scale_tot, pcoupl_mu, M, ebox;
180 gmx_repl_ex_t repl_ex = NULL;
183 t_mdebin *mdebin = NULL;
184 df_history_t df_history;
185 t_state *state = NULL;
186 rvec *f_global = NULL;
189 gmx_enerdata_t *enerd;
191 gmx_global_stat_t gstat;
192 gmx_update_t upd = NULL;
193 t_graph *graph = NULL;
195 gmx_rng_t mcrng = NULL;
197 gmx_groups_t *groups;
198 gmx_ekindata_t *ekind, *ekind_save;
199 gmx_shellfc_t shellfc;
200 int count, nconverged = 0;
203 gmx_bool bIonize = FALSE;
204 gmx_bool bTCR = FALSE, bConverged = TRUE, bOK, bSumEkinhOld, bExchanged;
206 gmx_bool bResetCountersHalfMaxH = FALSE;
207 gmx_bool bVV, bIterativeCase, bFirstIterate, bTemp, bPres, bTrotter;
208 gmx_bool bUpdateDoLR;
209 real mu_aver = 0, dvdl_constr;
210 int a0, a1, gnx = 0, ii;
211 atom_id *grpindex = NULL;
213 t_coupl_rec *tcr = NULL;
214 rvec *xcopy = NULL, *vcopy = NULL, *cbuf = NULL;
215 matrix boxcopy = {{0}}, lastbox;
217 real fom, oldfom, veta_save, pcurr, scalevir, tracevir;
224 real saved_conserved_quantity = 0;
229 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
230 int handled_stop_condition = gmx_stop_cond_none; /* compare to get_stop_condition*/
231 gmx_iterate_t iterate;
232 gmx_large_int_t multisim_nsteps = -1; /* number of steps to do before first multisim
233 simulation stops. If equal to zero, don't
234 communicate any more between multisims.*/
235 /* PME load balancing data for GPU kernels */
236 pme_load_balancing_t pme_loadbal = NULL;
238 gmx_bool bPMETuneTry = FALSE, bPMETuneRunning = FALSE;
241 /* Temporary addition for FAHCORE checkpointing */
245 /* Check for special mdrun options */
246 bRerunMD = (Flags & MD_RERUN);
247 bIonize = (Flags & MD_IONIZE);
248 bFFscan = (Flags & MD_FFSCAN);
249 bAppend = (Flags & MD_APPENDFILES);
250 if (Flags & MD_RESETCOUNTERSHALFWAY)
254 /* Signal to reset the counters half the simulation steps. */
255 wcycle_set_reset_counters(wcycle, ir->nsteps/2);
257 /* Signal to reset the counters halfway the simulation time. */
258 bResetCountersHalfMaxH = (max_hours > 0);
261 /* md-vv uses averaged full step velocities for T-control
262 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
263 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
265 if (bVV) /* to store the initial velocities while computing virial */
267 snew(cbuf, top_global->natoms);
269 /* all the iteratative cases - only if there are constraints */
270 bIterativeCase = ((IR_NPH_TROTTER(ir) || IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
271 gmx_iterate_init(&iterate, FALSE); /* The default value of iterate->bIterationActive is set to
272 false in this step. The correct value, true or false,
273 is set at each step, as it depends on the frequency of temperature
274 and pressure control.*/
275 bTrotter = (bVV && (IR_NPT_TROTTER(ir) || IR_NPH_TROTTER(ir) || IR_NVT_TROTTER(ir)));
279 /* Since we don't know if the frames read are related in any way,
280 * rebuild the neighborlist at every step.
283 ir->nstcalcenergy = 1;
287 check_ir_old_tpx_versions(cr, fplog, ir, top_global);
289 nstglobalcomm = check_nstglobalcomm(fplog, cr, nstglobalcomm, ir);
290 bGStatEveryStep = (nstglobalcomm == 1);
292 if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
295 "To reduce the energy communication with nstlist = -1\n"
296 "the neighbor list validity should not be checked at every step,\n"
297 "this means that exact integration is not guaranteed.\n"
298 "The neighbor list validity is checked after:\n"
299 " <n.list life time> - 2*std.dev.(n.list life time) steps.\n"
300 "In most cases this will result in exact integration.\n"
301 "This reduces the energy communication by a factor of 2 to 3.\n"
302 "If you want less energy communication, set nstlist > 3.\n\n");
305 if (bRerunMD || bFFscan)
309 groups = &top_global->groups;
312 init_md(fplog, cr, ir, oenv, &t, &t0, state_global->lambda,
313 &(state_global->fep_state), lam0,
314 nrnb, top_global, &upd,
315 nfile, fnm, &outf, &mdebin,
316 force_vir, shake_vir, mu_tot, &bSimAnn, &vcm, state_global, Flags);
318 clear_mat(total_vir);
320 /* Energy terms and groups */
322 init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
324 if (DOMAINDECOMP(cr))
330 snew(f, top_global->natoms);
333 /* lambda Monte carlo random number generator */
336 mcrng = gmx_rng_init(ir->expandedvals->lmc_seed);
338 /* copy the state into df_history */
339 copy_df_history(&df_history, &state_global->dfhist);
341 /* Kinetic energy data */
343 init_ekindata(fplog, top_global, &(ir->opts), ekind);
344 /* needed for iteration of constraints */
346 init_ekindata(fplog, top_global, &(ir->opts), ekind_save);
347 /* Copy the cos acceleration to the groups struct */
348 ekind->cosacc.cos_accel = ir->cos_accel;
350 gstat = global_stat_init(ir);
353 /* Check for polarizable models and flexible constraints */
354 shellfc = init_shell_flexcon(fplog,
355 top_global, n_flexible_constraints(constr),
356 (ir->bContinuation ||
357 (DOMAINDECOMP(cr) && !MASTER(cr))) ?
358 NULL : state_global->x);
362 #ifdef GMX_THREAD_MPI
363 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
365 set_deform_reference_box(upd,
366 deform_init_init_step_tpx,
367 deform_init_box_tpx);
368 #ifdef GMX_THREAD_MPI
369 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
374 double io = compute_io(ir, top_global->natoms, groups, mdebin->ebin->nener, 1);
375 if ((io > 2000) && MASTER(cr))
378 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
383 if (DOMAINDECOMP(cr))
385 top = dd_init_local_top(top_global);
388 dd_init_local_state(cr->dd, state_global, state);
390 if (DDMASTER(cr->dd) && ir->nstfout)
392 snew(f_global, state_global->natoms);
399 /* Initialize the particle decomposition and split the topology */
400 top = split_system(fplog, top_global, ir, cr);
402 pd_cg_range(cr, &fr->cg0, &fr->hcg);
403 pd_at_range(cr, &a0, &a1);
407 top = gmx_mtop_generate_local_top(top_global, ir);
410 a1 = top_global->natoms;
413 forcerec_set_excl_load(fr, top, cr);
415 state = partdec_init_local_state(cr, state_global);
418 atoms2md(top_global, ir, 0, NULL, a0, a1-a0, mdatoms);
422 set_vsite_top(vsite, top, mdatoms, cr);
425 if (ir->ePBC != epbcNONE && !fr->bMolPBC)
427 graph = mk_graph(fplog, &(top->idef), 0, top_global->natoms, FALSE, FALSE);
432 make_local_shells(cr, mdatoms, shellfc);
435 init_bonded_thread_force_reduction(fr, &top->idef);
437 if (ir->pull && PAR(cr))
439 dd_make_local_pull_groups(NULL, ir->pull, mdatoms);
443 if (DOMAINDECOMP(cr))
445 /* Distribute the charge groups over the nodes from the master node */
446 dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
447 state_global, top_global, ir,
448 state, &f, mdatoms, top, fr,
449 vsite, shellfc, constr,
450 nrnb, wcycle, FALSE);
454 update_mdatoms(mdatoms, state->lambda[efptMASS]);
456 if (opt2bSet("-cpi", nfile, fnm))
458 bStateFromCP = gmx_fexist_master(opt2fn_master("-cpi", nfile, fnm, cr), cr);
462 bStateFromCP = FALSE;
469 /* Update mdebin with energy history if appending to output files */
470 if (Flags & MD_APPENDFILES)
472 restore_energyhistory_from_state(mdebin, &state_global->enerhist);
476 /* We might have read an energy history from checkpoint,
477 * free the allocated memory and reset the counts.
479 done_energyhistory(&state_global->enerhist);
480 init_energyhistory(&state_global->enerhist);
483 /* Set the initial energy history in state by updating once */
484 update_energyhistory(&state_global->enerhist, mdebin);
487 if ((state->flags & (1<<estLD_RNG)) && (Flags & MD_READ_RNG))
489 /* Set the random state if we read a checkpoint file */
490 set_stochd_state(upd, state);
493 if (state->flags & (1<<estMC_RNG))
495 set_mc_state(mcrng, state);
498 /* Initialize constraints */
501 if (!DOMAINDECOMP(cr))
503 set_constraints(constr, top, ir, mdatoms, cr);
507 /* Check whether we have to GCT stuff */
508 bTCR = ftp2bSet(efGCT, nfile, fnm);
513 fprintf(stderr, "Will do General Coupling Theory!\n");
515 gnx = top_global->mols.nr;
517 for (i = 0; (i < gnx); i++)
525 /* We need to be sure replica exchange can only occur
526 * when the energies are current */
527 check_nst_param(fplog, cr, "nstcalcenergy", ir->nstcalcenergy,
528 "repl_ex_nst", &repl_ex_nst);
529 /* This check needs to happen before inter-simulation
530 * signals are initialized, too */
532 if (repl_ex_nst > 0 && MASTER(cr))
534 repl_ex = init_replica_exchange(fplog, cr->ms, state_global, ir,
535 repl_ex_nst, repl_ex_nex, repl_ex_seed);
538 /* PME tuning is only supported with GPUs or PME nodes and not with rerun.
539 * With perturbed charges with soft-core we should not change the cut-off.
541 if ((Flags & MD_TUNEPME) &&
542 EEL_PME(fr->eeltype) &&
543 ( (fr->cutoff_scheme == ecutsVERLET && fr->nbv->bUseGPU) || !(cr->duty & DUTY_PME)) &&
544 !(ir->efep != efepNO && mdatoms->nChargePerturbed > 0 && ir->fepvals->bScCoul) &&
547 pme_loadbal_init(&pme_loadbal, ir, state->box, fr->ic, fr->pmedata);
549 if (cr->duty & DUTY_PME)
551 /* Start tuning right away, as we can't measure the load */
552 bPMETuneRunning = TRUE;
556 /* Separate PME nodes, we can measure the PP/PME load balance */
561 if (!ir->bContinuation && !bRerunMD)
563 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
565 /* Set the velocities of frozen particles to zero */
566 for (i = mdatoms->start; i < mdatoms->start+mdatoms->homenr; i++)
568 for (m = 0; m < DIM; m++)
570 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
580 /* Constrain the initial coordinates and velocities */
581 do_constrain_first(fplog, constr, ir, mdatoms, state, f,
582 graph, cr, nrnb, fr, top, shake_vir);
586 /* Construct the virtual sites for the initial configuration */
587 construct_vsites(fplog, vsite, state->x, nrnb, ir->delta_t, NULL,
588 top->idef.iparams, top->idef.il,
589 fr->ePBC, fr->bMolPBC, graph, cr, state->box);
595 /* set free energy calculation frequency as the minimum of nstdhdl, nstexpanded, and nstrepl_ex_nst*/
596 nstfep = ir->fepvals->nstdhdl;
597 if (ir->bExpanded && (nstfep > ir->expandedvals->nstexpanded))
599 nstfep = ir->expandedvals->nstexpanded;
601 if (repl_ex_nst > 0 && nstfep > repl_ex_nst)
603 nstfep = repl_ex_nst;
606 /* I'm assuming we need global communication the first time! MRS */
607 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
608 | ((ir->comm_mode != ecmNO) ? CGLO_STOPCM : 0)
609 | (bVV ? CGLO_PRESSURE : 0)
610 | (bVV ? CGLO_CONSTRAINT : 0)
611 | (bRerunMD ? CGLO_RERUNMD : 0)
612 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN : 0));
614 bSumEkinhOld = FALSE;
615 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
616 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
617 constr, NULL, FALSE, state->box,
618 top_global, &pcurr, top_global->natoms, &bSumEkinhOld, cglo_flags);
619 if (ir->eI == eiVVAK)
621 /* a second call to get the half step temperature initialized as well */
622 /* we do the same call as above, but turn the pressure off -- internally to
623 compute_globals, this is recognized as a velocity verlet half-step
624 kinetic energy calculation. This minimized excess variables, but
625 perhaps loses some logic?*/
627 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
628 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
629 constr, NULL, FALSE, state->box,
630 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
631 cglo_flags &~(CGLO_STOPCM | CGLO_PRESSURE));
634 /* Calculate the initial half step temperature, and save the ekinh_old */
635 if (!(Flags & MD_STARTFROMCPT))
637 for (i = 0; (i < ir->opts.ngtc); i++)
639 copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old);
644 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
645 and there is no previous step */
648 /* if using an iterative algorithm, we need to create a working directory for the state. */
651 bufstate = init_bufstate(state);
655 snew(xcopy, state->natoms);
656 snew(vcopy, state->natoms);
657 copy_rvecn(state->x, xcopy, 0, state->natoms);
658 copy_rvecn(state->v, vcopy, 0, state->natoms);
659 copy_mat(state->box, boxcopy);
662 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
663 temperature control */
664 trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter);
668 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
671 "RMS relative constraint deviation after constraining: %.2e\n",
672 constr_rmsd(constr, FALSE));
674 if (EI_STATE_VELOCITY(ir->eI))
676 fprintf(fplog, "Initial temperature: %g K\n", enerd->term[F_TEMP]);
680 fprintf(stderr, "starting md rerun '%s', reading coordinates from"
681 " input trajectory '%s'\n\n",
682 *(top_global->name), opt2fn("-rerun", nfile, fnm));
685 fprintf(stderr, "Calculated time to finish depends on nsteps from "
686 "run input file,\nwhich may not correspond to the time "
687 "needed to process input trajectory.\n\n");
693 fprintf(stderr, "starting mdrun '%s'\n",
694 *(top_global->name));
697 sprintf(tbuf, "%8.1f", (ir->init_step+ir->nsteps)*ir->delta_t);
701 sprintf(tbuf, "%s", "infinite");
703 if (ir->init_step > 0)
705 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
706 gmx_step_str(ir->init_step+ir->nsteps, sbuf), tbuf,
707 gmx_step_str(ir->init_step, sbuf2),
708 ir->init_step*ir->delta_t);
712 fprintf(stderr, "%s steps, %s ps.\n",
713 gmx_step_str(ir->nsteps, sbuf), tbuf);
716 fprintf(fplog, "\n");
719 /* Set and write start time */
720 runtime_start(runtime);
721 print_date_and_time(fplog, cr->nodeid, "Started mdrun", runtime);
722 wallcycle_start(wcycle, ewcRUN);
725 fprintf(fplog, "\n");
728 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
730 chkpt_ret = fcCheckPointParallel( cr->nodeid,
734 gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", 0 );
739 /***********************************************************
743 ************************************************************/
745 /* if rerunMD then read coordinates and velocities from input trajectory */
748 if (getenv("GMX_FORCE_UPDATE"))
756 bNotLastFrame = read_first_frame(oenv, &status,
757 opt2fn("-rerun", nfile, fnm),
758 &rerun_fr, TRX_NEED_X | TRX_READ_V);
759 if (rerun_fr.natoms != top_global->natoms)
762 "Number of atoms in trajectory (%d) does not match the "
763 "run input file (%d)\n",
764 rerun_fr.natoms, top_global->natoms);
766 if (ir->ePBC != epbcNONE)
770 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);
772 if (max_cutoff2(ir->ePBC, rerun_fr.box) < sqr(fr->rlistlong))
774 gmx_fatal(FARGS, "Rerun trajectory frame step %d time %f has too small box dimensions", rerun_fr.step, rerun_fr.time);
781 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
784 if (ir->ePBC != epbcNONE)
786 /* Set the shift vectors.
787 * Necessary here when have a static box different from the tpr box.
789 calc_shifts(rerun_fr.box, fr->shift_vec);
793 /* loop over MD steps or if rerunMD to end of input trajectory */
795 /* Skip the first Nose-Hoover integration when we get the state from tpx */
796 bStateFromTPX = !bStateFromCP;
797 bInitStep = bFirstStep && (bStateFromTPX || bVV);
798 bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
800 bSumEkinhOld = FALSE;
803 init_global_signals(&gs, cr, ir, repl_ex_nst);
805 step = ir->init_step;
808 if (ir->nstlist == -1)
810 init_nlistheuristics(&nlh, bGStatEveryStep, step);
813 if (MULTISIM(cr) && (repl_ex_nst <= 0 ))
815 /* check how many steps are left in other sims */
816 multisim_nsteps = get_multisim_nsteps(cr, ir->nsteps);
820 /* and stop now if we should */
821 bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps) ||
822 ((multisim_nsteps >= 0) && (step_rel >= multisim_nsteps )));
823 while (!bLastStep || (bRerunMD && bNotLastFrame))
826 wallcycle_start(wcycle, ewcSTEP);
828 GMX_MPE_LOG(ev_timestep1);
834 step = rerun_fr.step;
835 step_rel = step - ir->init_step;
848 bLastStep = (step_rel == ir->nsteps);
849 t = t0 + step*ir->delta_t;
852 if (ir->efep != efepNO || ir->bSimTemp)
854 /* find and set the current lambdas. If rerunning, we either read in a state, or a lambda value,
855 requiring different logic. */
857 set_current_lambdas(step, ir->fepvals, bRerunMD, &rerun_fr, state_global, state, lam0);
858 bDoDHDL = do_per_step(step, ir->fepvals->nstdhdl);
859 bDoFEP = (do_per_step(step, nstfep) && (ir->efep != efepNO));
860 bDoExpanded = (do_per_step(step, ir->expandedvals->nstexpanded) && (ir->bExpanded) && (step > 0));
865 update_annealing_target_temp(&(ir->opts), t);
870 if (!(DOMAINDECOMP(cr) && !MASTER(cr)))
872 for (i = 0; i < state_global->natoms; i++)
874 copy_rvec(rerun_fr.x[i], state_global->x[i]);
878 for (i = 0; i < state_global->natoms; i++)
880 copy_rvec(rerun_fr.v[i], state_global->v[i]);
885 for (i = 0; i < state_global->natoms; i++)
887 clear_rvec(state_global->v[i]);
891 fprintf(stderr, "\nWARNING: Some frames do not contain velocities.\n"
892 " Ekin, temperature and pressure are incorrect,\n"
893 " the virial will be incorrect when constraints are present.\n"
895 bRerunWarnNoV = FALSE;
899 copy_mat(rerun_fr.box, state_global->box);
900 copy_mat(state_global->box, state->box);
902 if (vsite && (Flags & MD_RERUN_VSITE))
904 if (DOMAINDECOMP(cr))
906 gmx_fatal(FARGS, "Vsite recalculation with -rerun is not implemented for domain decomposition, use particle decomposition");
910 /* Following is necessary because the graph may get out of sync
911 * with the coordinates if we only have every N'th coordinate set
913 mk_mshift(fplog, graph, fr->ePBC, state->box, state->x);
914 shift_self(graph, state->box, state->x);
916 construct_vsites(fplog, vsite, state->x, nrnb, ir->delta_t, state->v,
917 top->idef.iparams, top->idef.il,
918 fr->ePBC, fr->bMolPBC, graph, cr, state->box);
921 unshift_self(graph, state->box, state->x);
926 /* Stop Center of Mass motion */
927 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step, ir->nstcomm));
929 /* Copy back starting coordinates in case we're doing a forcefield scan */
932 for (ii = 0; (ii < state->natoms); ii++)
934 copy_rvec(xcopy[ii], state->x[ii]);
935 copy_rvec(vcopy[ii], state->v[ii]);
937 copy_mat(boxcopy, state->box);
942 /* for rerun MD always do Neighbour Searching */
943 bNS = (bFirstStep || ir->nstlist != 0);
948 /* Determine whether or not to do Neighbour Searching and LR */
949 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
951 bNS = (bFirstStep || bExchanged || bNStList || bDoFEP ||
952 (ir->nstlist == -1 && nlh.nabnsb > 0));
954 if (bNS && ir->nstlist == -1)
956 set_nlistheuristics(&nlh, bFirstStep || bExchanged || bDoFEP, step);
960 /* check whether we should stop because another simulation has
964 if ( (multisim_nsteps >= 0) && (step_rel >= multisim_nsteps) &&
965 (multisim_nsteps != ir->nsteps) )
972 "Stopping simulation %d because another one has finished\n",
976 gs.sig[eglsCHKPT] = 1;
981 /* < 0 means stop at next step, > 0 means stop at next NS step */
982 if ( (gs.set[eglsSTOPCOND] < 0) ||
983 ( (gs.set[eglsSTOPCOND] > 0) && (bNStList || ir->nstlist == 0) ) )
988 /* Determine whether or not to update the Born radii if doing GB */
989 bBornRadii = bFirstStep;
990 if (ir->implicit_solvent && (step % ir->nstgbradii == 0))
995 do_log = do_per_step(step, ir->nstlog) || bFirstStep || bLastStep;
996 do_verbose = bVerbose &&
997 (step % stepout == 0 || bFirstStep || bLastStep);
999 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
1003 bMasterState = TRUE;
1007 bMasterState = FALSE;
1008 /* Correct the new box if it is too skewed */
1009 if (DYNAMIC_BOX(*ir))
1011 if (correct_box(fplog, step, state->box, graph))
1013 bMasterState = TRUE;
1016 if (DOMAINDECOMP(cr) && bMasterState)
1018 dd_collect_state(cr->dd, state, state_global);
1022 if (DOMAINDECOMP(cr))
1024 /* Repartition the domain decomposition */
1025 wallcycle_start(wcycle, ewcDOMDEC);
1026 dd_partition_system(fplog, step, cr,
1027 bMasterState, nstglobalcomm,
1028 state_global, top_global, ir,
1029 state, &f, mdatoms, top, fr,
1030 vsite, shellfc, constr,
1032 do_verbose && !bPMETuneRunning);
1033 wallcycle_stop(wcycle, ewcDOMDEC);
1034 /* If using an iterative integrator, reallocate space to match the decomposition */
1038 if (MASTER(cr) && do_log && !bFFscan)
1040 print_ebin_header(fplog, step, t, state->lambda[efptFEP]); /* can we improve the information printed here? */
1043 if (ir->efep != efepNO)
1045 update_mdatoms(mdatoms, state->lambda[efptMASS]);
1048 if ((bRerunMD && rerun_fr.bV) || bExchanged)
1051 /* We need the kinetic energy at minus the half step for determining
1052 * the full step kinetic energy and possibly for T-coupling.*/
1053 /* This may not be quite working correctly yet . . . . */
1054 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1055 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1056 constr, NULL, FALSE, state->box,
1057 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1058 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1060 clear_mat(force_vir);
1062 /* Ionize the atoms if necessary */
1065 ionize(fplog, oenv, mdatoms, top_global, t, ir, state->x, state->v,
1066 mdatoms->start, mdatoms->start+mdatoms->homenr, state->box, cr);
1069 /* Update force field in ffscan program */
1072 if (update_forcefield(fplog,
1074 mdatoms->nr, state->x, state->box))
1082 GMX_MPE_LOG(ev_timestep2);
1084 /* We write a checkpoint at this MD step when:
1085 * either at an NS step when we signalled through gs,
1086 * or at the last step (but not when we do not want confout),
1087 * but never at the first step or with rerun.
1089 bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
1090 (bLastStep && (Flags & MD_CONFOUT))) &&
1091 step > ir->init_step && !bRerunMD);
1094 gs.set[eglsCHKPT] = 0;
1097 /* Determine the energy and pressure:
1098 * at nstcalcenergy steps and at energy output steps (set below).
1100 if (EI_VV(ir->eI) && (!bInitStep))
1102 /* for vv, the first half of the integration actually corresponds
1103 to the previous step. bCalcEner is only required to be evaluated on the 'next' step,
1104 but the virial needs to be calculated on both the current step and the 'next' step. Future
1105 reorganization may be able to get rid of one of the bCalcVir=TRUE steps. */
1107 bCalcEner = do_per_step(step-1, ir->nstcalcenergy);
1108 bCalcVir = bCalcEner ||
1109 (ir->epc != epcNO && (do_per_step(step, ir->nstpcouple) || do_per_step(step-1, ir->nstpcouple)));
1113 bCalcEner = do_per_step(step, ir->nstcalcenergy);
1114 bCalcVir = bCalcEner ||
1115 (ir->epc != epcNO && do_per_step(step, ir->nstpcouple));
1118 /* Do we need global communication ? */
1119 bGStat = (bCalcVir || bCalcEner || bStopCM ||
1120 do_per_step(step, nstglobalcomm) || (bVV && IR_NVT_TROTTER(ir) && do_per_step(step-1, nstglobalcomm)) ||
1121 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
1123 do_ene = (do_per_step(step, ir->nstenergy) || bLastStep);
1125 if (do_ene || do_log)
1132 /* these CGLO_ options remain the same throughout the iteration */
1133 cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
1134 (bGStat ? CGLO_GSTAT : 0)
1137 force_flags = (GMX_FORCE_STATECHANGED |
1138 ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1139 GMX_FORCE_ALLFORCES |
1141 (bCalcVir ? GMX_FORCE_VIRIAL : 0) |
1142 (bCalcEner ? GMX_FORCE_ENERGY : 0) |
1143 (bDoFEP ? GMX_FORCE_DHDL : 0)
1148 if (do_per_step(step, ir->nstcalclr))
1150 force_flags |= GMX_FORCE_DO_LR;
1156 /* Now is the time to relax the shells */
1157 count = relax_shell_flexcon(fplog, cr, bVerbose, bFFscan ? step+1 : step,
1158 ir, bNS, force_flags,
1159 bStopCM, top, top_global,
1161 state, f, force_vir, mdatoms,
1162 nrnb, wcycle, graph, groups,
1163 shellfc, fr, bBornRadii, t, mu_tot,
1164 state->natoms, &bConverged, vsite,
1175 /* The coordinates (x) are shifted (to get whole molecules)
1177 * This is parallellized as well, and does communication too.
1178 * Check comments in sim_util.c
1180 do_force(fplog, cr, ir, step, nrnb, wcycle, top, top_global, groups,
1181 state->box, state->x, &state->hist,
1182 f, force_vir, mdatoms, enerd, fcd,
1183 state->lambda, graph,
1184 fr, vsite, mu_tot, t, outf->fp_field, ed, bBornRadii,
1185 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1188 GMX_BARRIER(cr->mpi_comm_mygroup);
1192 mu_aver = calc_mu_aver(cr, state->x, mdatoms->chargeA,
1193 mu_tot, &top_global->mols, mdatoms, gnx, grpindex);
1196 if (bTCR && bFirstStep)
1198 tcr = init_coupling(fplog, nfile, fnm, cr, fr, mdatoms, &(top->idef));
1199 fprintf(fplog, "Done init_coupling\n");
1203 if (bVV && !bStartingFromCpt && !bRerunMD)
1204 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1206 if (ir->eI == eiVV && bInitStep)
1208 /* if using velocity verlet with full time step Ekin,
1209 * take the first half step only to compute the
1210 * virial for the first step. From there,
1211 * revert back to the initial coordinates
1212 * so that the input is actually the initial step.
1214 copy_rvecn(state->v, cbuf, 0, state->natoms); /* should make this better for parallelizing? */
1218 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1219 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ1);
1222 /* If we are using twin-range interactions where the long-range component
1223 * is only evaluated every nstcalclr>1 steps, we should do a special update
1224 * step to combine the long-range forces on these steps.
1225 * For nstcalclr=1 this is not done, since the forces would have been added
1226 * directly to the short-range forces already.
1228 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1230 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC,
1231 f, bUpdateDoLR, fr->f_twin, fcd,
1232 ekind, M, wcycle, upd, bInitStep, etrtVELOCITY1,
1233 cr, nrnb, constr, &top->idef);
1235 if (bIterativeCase && do_per_step(step-1, ir->nstpcouple) && !bInitStep)
1237 gmx_iterate_init(&iterate, TRUE);
1239 /* for iterations, we save these vectors, as we will be self-consistently iterating
1242 /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1244 /* save the state */
1245 if (iterate.bIterationActive)
1247 copy_coupling_state(state, bufstate, ekind, ekind_save, &(ir->opts));
1250 bFirstIterate = TRUE;
1251 while (bFirstIterate || iterate.bIterationActive)
1253 if (iterate.bIterationActive)
1255 copy_coupling_state(bufstate, state, ekind_save, ekind, &(ir->opts));
1256 if (bFirstIterate && bTrotter)
1258 /* The first time through, we need a decent first estimate
1259 of veta(t+dt) to compute the constraints. Do
1260 this by computing the box volume part of the
1261 trotter integration at this time. Nothing else
1262 should be changed by this routine here. If
1263 !(first time), we start with the previous value
1266 veta_save = state->veta;
1267 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ0);
1268 vetanew = state->veta;
1269 state->veta = veta_save;
1274 if (!bRerunMD || rerun_fr.bV || bForceUpdate) /* Why is rerun_fr.bV here? Unclear. */
1276 update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1277 state, fr->bMolPBC, graph, f,
1278 &top->idef, shake_vir, NULL,
1279 cr, nrnb, wcycle, upd, constr,
1280 bInitStep, TRUE, bCalcVir, vetanew);
1282 if (!bOK && !bFFscan)
1284 gmx_fatal(FARGS, "Constraint error: Shake, Lincs or Settle could not solve the constrains");
1290 /* Need to unshift here if a do_force has been
1291 called in the previous step */
1292 unshift_self(graph, state->box, state->x);
1295 /* if VV, compute the pressure and constraints */
1296 /* For VV2, we strictly only need this if using pressure
1297 * control, but we really would like to have accurate pressures
1299 * Think about ways around this in the future?
1300 * For now, keep this choice in comments.
1302 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
1303 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
1305 bTemp = ((ir->eI == eiVV && (!bInitStep)) || (ir->eI == eiVVAK));
1306 if (bCalcEner && ir->eI == eiVVAK) /*MRS: 7/9/2010 -- this still doesn't fix it?*/
1308 bSumEkinhOld = TRUE;
1310 /* for vv, the first half of the integration actually corresponds to the previous step.
1311 So we need information from the last step in the first half of the integration */
1312 if (bGStat || do_per_step(step-1, nstglobalcomm))
1314 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1315 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1316 constr, NULL, FALSE, state->box,
1317 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1320 | (bTemp ? CGLO_TEMPERATURE : 0)
1321 | (bPres ? CGLO_PRESSURE : 0)
1322 | (bPres ? CGLO_CONSTRAINT : 0)
1323 | ((iterate.bIterationActive) ? CGLO_ITERATE : 0)
1324 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1327 /* explanation of above:
1328 a) We compute Ekin at the full time step
1329 if 1) we are using the AveVel Ekin, and it's not the
1330 initial step, or 2) if we are using AveEkin, but need the full
1331 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1332 b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in
1333 EkinAveVel because it's needed for the pressure */
1335 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1340 m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */
1341 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ2);
1348 /* We need the kinetic energy at minus the half step for determining
1349 * the full step kinetic energy and possibly for T-coupling.*/
1350 /* This may not be quite working correctly yet . . . . */
1351 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1352 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1353 constr, NULL, FALSE, state->box,
1354 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1355 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1360 if (iterate.bIterationActive &&
1361 done_iterating(cr, fplog, step, &iterate, bFirstIterate,
1362 state->veta, &vetanew))
1366 bFirstIterate = FALSE;
1369 if (bTrotter && !bInitStep)
1371 copy_mat(shake_vir, state->svir_prev);
1372 copy_mat(force_vir, state->fvir_prev);
1373 if (IR_NVT_TROTTER(ir) && ir->eI == eiVV)
1375 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1376 enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, NULL, (ir->eI == eiVV), FALSE, FALSE);
1377 enerd->term[F_EKIN] = trace(ekind->ekin);
1380 /* if it's the initial step, we performed this first step just to get the constraint virial */
1381 if (bInitStep && ir->eI == eiVV)
1383 copy_rvecn(cbuf, state->v, 0, state->natoms);
1386 GMX_MPE_LOG(ev_timestep1);
1389 /* MRS -- now done iterating -- compute the conserved quantity */
1392 saved_conserved_quantity = compute_conserved_from_auxiliary(ir, state, &MassQ);
1395 last_ekin = enerd->term[F_EKIN];
1397 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1399 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1401 /* sum up the foreign energy and dhdl terms for vv. currently done every step so that dhdl is correct in the .edr */
1404 sum_dhdl(enerd, state->lambda, ir->fepvals);
1408 /* ######## END FIRST UPDATE STEP ############## */
1409 /* ######## If doing VV, we now have v(dt) ###### */
1412 /* perform extended ensemble sampling in lambda - we don't
1413 actually move to the new state before outputting
1414 statistics, but if performing simulated tempering, we
1415 do update the velocities and the tau_t. */
1417 lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, &df_history, step, mcrng, state->v, mdatoms);
1419 /* ################## START TRAJECTORY OUTPUT ################# */
1421 /* Now we have the energies and forces corresponding to the
1422 * coordinates at time t. We must output all of this before
1424 * for RerunMD t is read from input trajectory
1426 GMX_MPE_LOG(ev_output_start);
1429 if (do_per_step(step, ir->nstxout))
1431 mdof_flags |= MDOF_X;
1433 if (do_per_step(step, ir->nstvout))
1435 mdof_flags |= MDOF_V;
1437 if (do_per_step(step, ir->nstfout))
1439 mdof_flags |= MDOF_F;
1441 if (do_per_step(step, ir->nstxtcout))
1443 mdof_flags |= MDOF_XTC;
1447 mdof_flags |= MDOF_CPT;
1451 #if defined(GMX_FAHCORE) || defined(GMX_WRITELASTSTEP)
1454 /* Enforce writing positions and velocities at end of run */
1455 mdof_flags |= (MDOF_X | MDOF_V);
1461 fcReportProgress( ir->nsteps, step );
1464 /* sync bCPT and fc record-keeping */
1465 if (bCPT && MASTER(cr))
1467 fcRequestCheckPoint();
1471 if (mdof_flags != 0)
1473 wallcycle_start(wcycle, ewcTRAJ);
1476 if (state->flags & (1<<estLD_RNG))
1478 get_stochd_state(upd, state);
1480 if (state->flags & (1<<estMC_RNG))
1482 get_mc_state(mcrng, state);
1488 state_global->ekinstate.bUpToDate = FALSE;
1492 update_ekinstate(&state_global->ekinstate, ekind);
1493 state_global->ekinstate.bUpToDate = TRUE;
1495 update_energyhistory(&state_global->enerhist, mdebin);
1496 if (ir->efep != efepNO || ir->bSimTemp)
1498 state_global->fep_state = state->fep_state; /* MRS: seems kludgy. The code should be
1499 structured so this isn't necessary.
1500 Note this reassignment is only necessary
1501 for single threads.*/
1502 copy_df_history(&state_global->dfhist, &df_history);
1506 write_traj(fplog, cr, outf, mdof_flags, top_global,
1507 step, t, state, state_global, f, f_global, &n_xtc, &x_xtc);
1514 if (bLastStep && step_rel == ir->nsteps &&
1515 (Flags & MD_CONFOUT) && MASTER(cr) &&
1516 !bRerunMD && !bFFscan)
1518 /* x and v have been collected in write_traj,
1519 * because a checkpoint file will always be written
1522 fprintf(stderr, "\nWriting final coordinates.\n");
1525 /* Make molecules whole only for confout writing */
1526 do_pbc_mtop(fplog, ir->ePBC, state->box, top_global, state_global->x);
1528 write_sto_conf_mtop(ftp2fn(efSTO, nfile, fnm),
1529 *top_global->name, top_global,
1530 state_global->x, state_global->v,
1531 ir->ePBC, state->box);
1534 wallcycle_stop(wcycle, ewcTRAJ);
1536 GMX_MPE_LOG(ev_output_finish);
1538 /* kludge -- virial is lost with restart for NPT control. Must restart */
1539 if (bStartingFromCpt && bVV)
1541 copy_mat(state->svir_prev, shake_vir);
1542 copy_mat(state->fvir_prev, force_vir);
1544 /* ################## END TRAJECTORY OUTPUT ################ */
1546 /* Determine the wallclock run time up till now */
1547 run_time = gmx_gettime() - (double)runtime->real;
1549 /* Check whether everything is still allright */
1550 if (((int)gmx_get_stop_condition() > handled_stop_condition)
1551 #ifdef GMX_THREAD_MPI
1556 /* this is just make gs.sig compatible with the hack
1557 of sending signals around by MPI_Reduce with together with
1559 if (gmx_get_stop_condition() == gmx_stop_cond_next_ns)
1561 gs.sig[eglsSTOPCOND] = 1;
1563 if (gmx_get_stop_condition() == gmx_stop_cond_next)
1565 gs.sig[eglsSTOPCOND] = -1;
1567 /* < 0 means stop at next step, > 0 means stop at next NS step */
1571 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1572 gmx_get_signal_name(),
1573 gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1577 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1578 gmx_get_signal_name(),
1579 gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1581 handled_stop_condition = (int)gmx_get_stop_condition();
1583 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1584 (max_hours > 0 && run_time > max_hours*60.0*60.0*0.99) &&
1585 gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
1587 /* Signal to terminate the run */
1588 gs.sig[eglsSTOPCOND] = 1;
1591 fprintf(fplog, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1593 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1596 if (bResetCountersHalfMaxH && MASTER(cr) &&
1597 run_time > max_hours*60.0*60.0*0.495)
1599 gs.sig[eglsRESETCOUNTERS] = 1;
1602 if (ir->nstlist == -1 && !bRerunMD)
1604 /* When bGStatEveryStep=FALSE, global_stat is only called
1605 * when we check the atom displacements, not at NS steps.
1606 * This means that also the bonded interaction count check is not
1607 * performed immediately after NS. Therefore a few MD steps could
1608 * be performed with missing interactions.
1609 * But wrong energies are never written to file,
1610 * since energies are only written after global_stat
1613 if (step >= nlh.step_nscheck)
1615 nlh.nabnsb = natoms_beyond_ns_buffer(ir, fr, &top->cgs,
1616 nlh.scale_tot, state->x);
1620 /* This is not necessarily true,
1621 * but step_nscheck is determined quite conservatively.
1627 /* In parallel we only have to check for checkpointing in steps
1628 * where we do global communication,
1629 * otherwise the other nodes don't know.
1631 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1634 run_time >= nchkpt*cpt_period*60.0)) &&
1635 gs.set[eglsCHKPT] == 0)
1637 gs.sig[eglsCHKPT] = 1;
1640 /* at the start of step, randomize or scale the velocities (trotter done elsewhere) */
1645 update_tcouple(fplog, step, ir, state, ekind, wcycle, upd, &MassQ, mdatoms);
1647 if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */
1649 gmx_bool bIfRandomize;
1650 bIfRandomize = update_randomize_velocities(ir, step, mdatoms, state, upd, &top->idef, constr);
1651 /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */
1652 if (constr && bIfRandomize)
1654 update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1655 state, fr->bMolPBC, graph, f,
1656 &top->idef, tmp_vir, NULL,
1657 cr, nrnb, wcycle, upd, constr,
1658 bInitStep, TRUE, bCalcVir, vetanew);
1663 if (bIterativeCase && do_per_step(step, ir->nstpcouple))
1665 gmx_iterate_init(&iterate, TRUE);
1666 /* for iterations, we save these vectors, as we will be redoing the calculations */
1667 copy_coupling_state(state, bufstate, ekind, ekind_save, &(ir->opts));
1670 bFirstIterate = TRUE;
1671 while (bFirstIterate || iterate.bIterationActive)
1673 /* We now restore these vectors to redo the calculation with improved extended variables */
1674 if (iterate.bIterationActive)
1676 copy_coupling_state(bufstate, state, ekind_save, ekind, &(ir->opts));
1679 /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
1680 so scroll down for that logic */
1682 /* ######### START SECOND UPDATE STEP ################# */
1683 GMX_MPE_LOG(ev_update_start);
1684 /* Box is changed in update() when we do pressure coupling,
1685 * but we should still use the old box for energy corrections and when
1686 * writing it to the energy file, so it matches the trajectory files for
1687 * the same timestep above. Make a copy in a separate array.
1689 copy_mat(state->box, lastbox);
1694 if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
1696 wallcycle_start(wcycle, ewcUPDATE);
1697 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1700 if (iterate.bIterationActive)
1708 /* we use a new value of scalevir to converge the iterations faster */
1709 scalevir = tracevir/trace(shake_vir);
1711 msmul(shake_vir, scalevir, shake_vir);
1712 m_add(force_vir, shake_vir, total_vir);
1713 clear_mat(shake_vir);
1715 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ3);
1716 /* We can only do Berendsen coupling after we have summed
1717 * the kinetic energy or virial. Since the happens
1718 * in global_state after update, we should only do it at
1719 * step % nstlist = 1 with bGStatEveryStep=FALSE.
1724 update_tcouple(fplog, step, ir, state, ekind, wcycle, upd, &MassQ, mdatoms);
1725 update_pcouple(fplog, step, ir, state, pcoupl_mu, M, wcycle,
1731 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1733 /* velocity half-step update */
1734 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1735 bUpdateDoLR, fr->f_twin, fcd,
1736 ekind, M, wcycle, upd, FALSE, etrtVELOCITY2,
1737 cr, nrnb, constr, &top->idef);
1740 /* Above, initialize just copies ekinh into ekin,
1741 * it doesn't copy position (for VV),
1742 * and entire integrator for MD.
1745 if (ir->eI == eiVVAK)
1747 copy_rvecn(state->x, cbuf, 0, state->natoms);
1749 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1751 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1752 bUpdateDoLR, fr->f_twin, fcd,
1753 ekind, M, wcycle, upd, bInitStep, etrtPOSITION, cr, nrnb, constr, &top->idef);
1754 wallcycle_stop(wcycle, ewcUPDATE);
1756 update_constraints(fplog, step, &dvdl_constr, ir, ekind, mdatoms, state,
1757 fr->bMolPBC, graph, f,
1758 &top->idef, shake_vir, force_vir,
1759 cr, nrnb, wcycle, upd, constr,
1760 bInitStep, FALSE, bCalcVir, state->veta);
1762 if (ir->eI == eiVVAK)
1764 /* erase F_EKIN and F_TEMP here? */
1765 /* just compute the kinetic energy at the half step to perform a trotter step */
1766 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1767 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1768 constr, NULL, FALSE, lastbox,
1769 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1770 cglo_flags | CGLO_TEMPERATURE
1772 wallcycle_start(wcycle, ewcUPDATE);
1773 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ4);
1774 /* now we know the scaling, we can compute the positions again again */
1775 copy_rvecn(cbuf, state->x, 0, state->natoms);
1777 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1779 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1780 bUpdateDoLR, fr->f_twin, fcd,
1781 ekind, M, wcycle, upd, bInitStep, etrtPOSITION, cr, nrnb, constr, &top->idef);
1782 wallcycle_stop(wcycle, ewcUPDATE);
1784 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1785 /* are the small terms in the shake_vir here due
1786 * to numerical errors, or are they important
1787 * physically? I'm thinking they are just errors, but not completely sure.
1788 * For now, will call without actually constraining, constr=NULL*/
1789 update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1790 state, fr->bMolPBC, graph, f,
1791 &top->idef, tmp_vir, force_vir,
1792 cr, nrnb, wcycle, upd, NULL,
1793 bInitStep, FALSE, bCalcVir,
1796 if (!bOK && !bFFscan)
1798 gmx_fatal(FARGS, "Constraint error: Shake, Lincs or Settle could not solve the constrains");
1801 if (fr->bSepDVDL && fplog && do_log)
1803 fprintf(fplog, sepdvdlformat, "Constraint dV/dl", 0.0, dvdl_constr);
1807 /* this factor or 2 correction is necessary
1808 because half of the constraint force is removed
1809 in the vv step, so we have to double it. See
1810 the Redmine issue #1255. It is not yet clear
1811 if the factor of 2 is exact, or just a very
1812 good approximation, and this will be
1813 investigated. The next step is to see if this
1814 can be done adding a dhdl contribution from the
1815 rattle step, but this is somewhat more
1816 complicated with the current code. Will be
1817 investigated, hopefully for 4.6.3. However,
1818 this current solution is much better than
1819 having it completely wrong.
1821 enerd->term[F_DVDL_CONSTR] += 2*dvdl_constr;
1825 enerd->term[F_DVDL_CONSTR] += dvdl_constr;
1830 /* Need to unshift here */
1831 unshift_self(graph, state->box, state->x);
1834 GMX_BARRIER(cr->mpi_comm_mygroup);
1835 GMX_MPE_LOG(ev_update_finish);
1839 wallcycle_start(wcycle, ewcVSITECONSTR);
1842 shift_self(graph, state->box, state->x);
1844 construct_vsites(fplog, vsite, state->x, nrnb, ir->delta_t, state->v,
1845 top->idef.iparams, top->idef.il,
1846 fr->ePBC, fr->bMolPBC, graph, cr, state->box);
1850 unshift_self(graph, state->box, state->x);
1852 wallcycle_stop(wcycle, ewcVSITECONSTR);
1855 /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
1856 /* With Leap-Frog we can skip compute_globals at
1857 * non-communication steps, but we need to calculate
1858 * the kinetic energy one step before communication.
1860 if (bGStat || (!EI_VV(ir->eI) && do_per_step(step+1, nstglobalcomm)))
1862 if (ir->nstlist == -1 && bFirstIterate)
1864 gs.sig[eglsNABNSB] = nlh.nabnsb;
1866 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1867 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1869 bFirstIterate ? &gs : NULL,
1870 (step_rel % gs.nstms == 0) &&
1871 (multisim_nsteps < 0 || (step_rel < multisim_nsteps)),
1873 top_global, &pcurr, top_global->natoms, &bSumEkinhOld,
1875 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_ENERGY : 0)
1876 | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0)
1877 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1878 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
1879 | (iterate.bIterationActive ? CGLO_ITERATE : 0)
1880 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1883 if (ir->nstlist == -1 && bFirstIterate)
1885 nlh.nabnsb = gs.set[eglsNABNSB];
1886 gs.set[eglsNABNSB] = 0;
1889 /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
1890 /* ############# END CALC EKIN AND PRESSURE ################# */
1892 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1893 the virial that should probably be addressed eventually. state->veta has better properies,
1894 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1895 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
1897 if (iterate.bIterationActive &&
1898 done_iterating(cr, fplog, step, &iterate, bFirstIterate,
1899 trace(shake_vir), &tracevir))
1903 bFirstIterate = FALSE;
1906 if (!bVV || bRerunMD)
1908 /* sum up the foreign energy and dhdl terms for md and sd. currently done every step so that dhdl is correct in the .edr */
1909 sum_dhdl(enerd, state->lambda, ir->fepvals);
1911 update_box(fplog, step, ir, mdatoms, state, graph, f,
1912 ir->nstlist == -1 ? &nlh.scale_tot : NULL, pcoupl_mu, nrnb, wcycle, upd, bInitStep, FALSE);
1914 /* ################# END UPDATE STEP 2 ################# */
1915 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
1917 /* The coordinates (x) were unshifted in update */
1918 if (bFFscan && (shellfc == NULL || bConverged))
1920 if (print_forcefield(fplog, enerd->term, mdatoms->homenr,
1922 &(top_global->mols), mdatoms->massT, pres))
1926 fprintf(stderr, "\n");
1932 /* We will not sum ekinh_old,
1933 * so signal that we still have to do it.
1935 bSumEkinhOld = TRUE;
1940 /* Only do GCT when the relaxation of shells (minimization) has converged,
1941 * otherwise we might be coupling to bogus energies.
1942 * In parallel we must always do this, because the other sims might
1946 /* Since this is called with the new coordinates state->x, I assume
1947 * we want the new box state->box too. / EL 20040121
1949 do_coupling(fplog, oenv, nfile, fnm, tcr, t, step, enerd->term, fr,
1951 mdatoms, &(top->idef), mu_aver,
1952 top_global->mols.nr, cr,
1953 state->box, total_vir, pres,
1954 mu_tot, state->x, f, bConverged);
1958 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
1960 /* use the directly determined last velocity, not actually the averaged half steps */
1961 if (bTrotter && ir->eI == eiVV)
1963 enerd->term[F_EKIN] = last_ekin;
1965 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1969 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1973 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir, state, &MassQ);
1975 /* Check for excessively large energies */
1979 real etot_max = 1e200;
1981 real etot_max = 1e30;
1983 if (fabs(enerd->term[F_ETOT]) > etot_max)
1985 fprintf(stderr, "Energy too large (%g), giving up\n",
1986 enerd->term[F_ETOT]);
1989 /* ######### END PREPARING EDR OUTPUT ########### */
1991 /* Time for performance */
1992 if (((step % stepout) == 0) || bLastStep)
1994 runtime_upd_proc(runtime);
2000 gmx_bool do_dr, do_or;
2002 if (fplog && do_log && bDoExpanded)
2004 /* only needed if doing expanded ensemble */
2005 PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, ir->bSimTemp ? ir->simtempvals : NULL,
2006 &df_history, state->fep_state, ir->nstlog, step);
2008 if (!(bStartingFromCpt && (EI_VV(ir->eI))))
2012 upd_mdebin(mdebin, bDoDHDL, TRUE,
2013 t, mdatoms->tmass, enerd, state,
2014 ir->fepvals, ir->expandedvals, lastbox,
2015 shake_vir, force_vir, total_vir, pres,
2016 ekind, mu_tot, constr);
2020 upd_mdebin_step(mdebin);
2023 do_dr = do_per_step(step, ir->nstdisreout);
2024 do_or = do_per_step(step, ir->nstorireout);
2026 print_ebin(outf->fp_ene, do_ene, do_dr, do_or, do_log ? fplog : NULL,
2028 eprNORMAL, bCompact, mdebin, fcd, groups, &(ir->opts));
2030 if (ir->ePull != epullNO)
2032 pull_print_output(ir->pull, step, t);
2035 if (do_per_step(step, ir->nstlog))
2037 if (fflush(fplog) != 0)
2039 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
2045 /* Have to do this part after outputting the logfile and the edr file */
2046 state->fep_state = lamnew;
2047 for (i = 0; i < efptNR; i++)
2049 state_global->lambda[i] = ir->fepvals->all_lambda[i][lamnew];
2052 /* Remaining runtime */
2053 if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal()) && !bPMETuneRunning)
2057 fprintf(stderr, "\n");
2059 print_time(stderr, runtime, step, ir, cr);
2062 /* Replica exchange */
2064 if ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
2065 do_per_step(step, repl_ex_nst))
2067 bExchanged = replica_exchange(fplog, cr, repl_ex,
2068 state_global, enerd,
2071 if (bExchanged && DOMAINDECOMP(cr))
2073 dd_partition_system(fplog, step, cr, TRUE, 1,
2074 state_global, top_global, ir,
2075 state, &f, mdatoms, top, fr,
2076 vsite, shellfc, constr,
2077 nrnb, wcycle, FALSE);
2083 bStartingFromCpt = FALSE;
2085 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
2086 /* With all integrators, except VV, we need to retain the pressure
2087 * at the current step for coupling at the next step.
2089 if ((state->flags & (1<<estPRES_PREV)) &&
2091 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
2093 /* Store the pressure in t_state for pressure coupling
2094 * at the next MD step.
2096 copy_mat(pres, state->pres_prev);
2099 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
2101 if ( (membed != NULL) && (!bLastStep) )
2103 rescale_membed(step_rel, membed, state_global->x);
2110 /* read next frame from input trajectory */
2111 bNotLastFrame = read_next_frame(oenv, status, &rerun_fr);
2116 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
2120 if (!bRerunMD || !rerun_fr.bStep)
2122 /* increase the MD step number */
2127 cycles = wallcycle_stop(wcycle, ewcSTEP);
2128 if (DOMAINDECOMP(cr) && wcycle)
2130 dd_cycles_add(cr->dd, cycles, ddCyclStep);
2133 if (bPMETuneRunning || bPMETuneTry)
2135 /* PME grid + cut-off optimization with GPUs or PME nodes */
2137 /* Count the total cycles over the last steps */
2138 cycles_pmes += cycles;
2140 /* We can only switch cut-off at NS steps */
2141 if (step % ir->nstlist == 0)
2143 /* PME grid + cut-off optimization with GPUs or PME nodes */
2146 if (DDMASTER(cr->dd))
2148 /* PME node load is too high, start tuning */
2149 bPMETuneRunning = (dd_pme_f_ratio(cr->dd) >= 1.05);
2151 dd_bcast(cr->dd, sizeof(gmx_bool), &bPMETuneRunning);
2153 if (bPMETuneRunning || step_rel > ir->nstlist*50)
2155 bPMETuneTry = FALSE;
2158 if (bPMETuneRunning)
2160 /* init_step might not be a multiple of nstlist,
2161 * but the first cycle is always skipped anyhow.
2164 pme_load_balance(pme_loadbal, cr,
2165 (bVerbose && MASTER(cr)) ? stderr : NULL,
2167 ir, state, cycles_pmes,
2168 fr->ic, fr->nbv, &fr->pmedata,
2171 /* Update constants in forcerec/inputrec to keep them in sync with fr->ic */
2172 fr->ewaldcoeff = fr->ic->ewaldcoeff;
2173 fr->rlist = fr->ic->rlist;
2174 fr->rlistlong = fr->ic->rlistlong;
2175 fr->rcoulomb = fr->ic->rcoulomb;
2176 fr->rvdw = fr->ic->rvdw;
2182 if (step_rel == wcycle_get_reset_counters(wcycle) ||
2183 gs.set[eglsRESETCOUNTERS] != 0)
2185 /* Reset all the counters related to performance over the run */
2186 reset_all_counters(fplog, cr, step, &step_rel, ir, wcycle, nrnb, runtime,
2187 fr->nbv != NULL && fr->nbv->bUseGPU ? fr->nbv->cu_nbv : NULL);
2188 wcycle_set_reset_counters(wcycle, -1);
2189 if (!(cr->duty & DUTY_PME))
2191 /* Tell our PME node to reset its counters */
2192 gmx_pme_send_resetcounters(cr, step);
2194 /* Correct max_hours for the elapsed time */
2195 max_hours -= run_time/(60.0*60.0);
2196 bResetCountersHalfMaxH = FALSE;
2197 gs.set[eglsRESETCOUNTERS] = 0;
2201 /* End of main MD loop */
2205 runtime_end(runtime);
2207 if (bRerunMD && MASTER(cr))
2212 if (!(cr->duty & DUTY_PME))
2214 /* Tell the PME only node to finish */
2215 gmx_pme_send_finish(cr);
2220 if (ir->nstcalcenergy > 0 && !bRerunMD)
2222 print_ebin(outf->fp_ene, FALSE, FALSE, FALSE, fplog, step, t,
2223 eprAVER, FALSE, mdebin, fcd, groups, &(ir->opts));
2231 if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
2233 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)));
2234 fprintf(fplog, "Average number of atoms that crossed the half buffer length: %.1f\n\n", nlh.ab/nlh.nns);
2237 if (pme_loadbal != NULL)
2239 pme_loadbal_done(pme_loadbal, cr, fplog,
2240 fr->nbv != NULL && fr->nbv->bUseGPU);
2243 if (shellfc && fplog)
2245 fprintf(fplog, "Fraction of iterations that converged: %.2f %%\n",
2246 (nconverged*100.0)/step_rel);
2247 fprintf(fplog, "Average number of force evaluations per MD step: %.2f\n\n",
2251 if (repl_ex_nst > 0 && MASTER(cr))
2253 print_replica_exchange_statistics(fplog, repl_ex);
2256 runtime->nsteps_done = step_rel;