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 * Copyright (c) 2011,2012,2013,2014, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
41 #include "gromacs/legacyheaders/typedefs.h"
42 #include "gromacs/math/vec.h"
43 #include "gromacs/legacyheaders/vcm.h"
44 #include "gromacs/legacyheaders/mdebin.h"
45 #include "gromacs/legacyheaders/nrnb.h"
46 #include "gromacs/legacyheaders/calcmu.h"
47 #include "gromacs/legacyheaders/vsite.h"
48 #include "gromacs/legacyheaders/update.h"
49 #include "gromacs/legacyheaders/ns.h"
50 #include "gromacs/legacyheaders/mdrun.h"
51 #include "gromacs/legacyheaders/md_support.h"
52 #include "gromacs/legacyheaders/md_logging.h"
53 #include "gromacs/legacyheaders/network.h"
54 #include "gromacs/legacyheaders/names.h"
55 #include "gromacs/legacyheaders/force.h"
56 #include "gromacs/legacyheaders/disre.h"
57 #include "gromacs/legacyheaders/orires.h"
58 #include "gromacs/legacyheaders/pme.h"
59 #include "gromacs/legacyheaders/mdatoms.h"
62 #include "gromacs/legacyheaders/qmmm.h"
63 #include "gromacs/legacyheaders/domdec.h"
64 #include "gromacs/legacyheaders/domdec_network.h"
65 #include "gromacs/legacyheaders/coulomb.h"
66 #include "gromacs/legacyheaders/constr.h"
67 #include "gromacs/legacyheaders/shellfc.h"
68 #include "gromacs/gmxpreprocess/compute_io.h"
69 #include "gromacs/legacyheaders/checkpoint.h"
70 #include "gromacs/topology/mtop_util.h"
71 #include "gromacs/legacyheaders/sighandler.h"
72 #include "gromacs/legacyheaders/txtdump.h"
73 #include "gromacs/utility/cstringutil.h"
74 #include "pme_loadbal.h"
75 #include "gromacs/legacyheaders/bondf.h"
77 #include "gromacs/legacyheaders/types/nlistheuristics.h"
78 #include "gromacs/legacyheaders/types/iteratedconstraints.h"
79 #include "gromacs/mdlib/nbnxn_cuda/nbnxn_cuda_data_mgmt.h"
81 #include "gromacs/fileio/confio.h"
82 #include "gromacs/fileio/mdoutf.h"
83 #include "gromacs/fileio/trajectory_writing.h"
84 #include "gromacs/fileio/trnio.h"
85 #include "gromacs/fileio/trxio.h"
86 #include "gromacs/fileio/xtcio.h"
87 #include "gromacs/imd/imd.h"
88 #include "gromacs/pbcutil/mshift.h"
89 #include "gromacs/pbcutil/pbc.h"
90 #include "gromacs/pulling/pull.h"
91 #include "gromacs/swap/swapcoords.h"
92 #include "gromacs/timing/wallcycle.h"
93 #include "gromacs/timing/walltime_accounting.h"
94 #include "gromacs/utility/gmxmpi.h"
95 #include "gromacs/utility/smalloc.h"
101 static void reset_all_counters(FILE *fplog, t_commrec *cr,
103 gmx_int64_t *step_rel, t_inputrec *ir,
104 gmx_wallcycle_t wcycle, t_nrnb *nrnb,
105 gmx_walltime_accounting_t walltime_accounting,
106 struct nonbonded_verlet_t *nbv)
108 char sbuf[STEPSTRSIZE];
110 /* Reset all the counters related to performance over the run */
111 md_print_warn(cr, fplog, "step %s: resetting all time and cycle counters\n",
112 gmx_step_str(step, sbuf));
114 nbnxn_cuda_reset_timings(nbv);
116 wallcycle_stop(wcycle, ewcRUN);
117 wallcycle_reset_all(wcycle);
118 if (DOMAINDECOMP(cr))
120 reset_dd_statistics_counters(cr->dd);
123 ir->init_step += *step_rel;
124 ir->nsteps -= *step_rel;
126 wallcycle_start(wcycle, ewcRUN);
127 walltime_accounting_start(walltime_accounting);
128 print_date_and_time(fplog, cr->nodeid, "Restarted time", gmx_gettime());
131 double do_md(FILE *fplog, t_commrec *cr, int nfile, const t_filenm fnm[],
132 const output_env_t oenv, gmx_bool bVerbose, gmx_bool bCompact,
134 gmx_vsite_t *vsite, gmx_constr_t constr,
135 int stepout, t_inputrec *ir,
136 gmx_mtop_t *top_global,
138 t_state *state_global,
140 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
141 gmx_edsam_t ed, t_forcerec *fr,
142 int repl_ex_nst, int repl_ex_nex, int repl_ex_seed, gmx_membed_t membed,
143 real cpt_period, real max_hours,
144 const char gmx_unused *deviceOptions,
147 gmx_walltime_accounting_t walltime_accounting)
149 gmx_mdoutf_t outf = NULL;
150 gmx_int64_t step, step_rel;
152 double t, t0, lam0[efptNR];
153 gmx_bool bGStatEveryStep, bGStat, bCalcVir, bCalcEner;
154 gmx_bool bNS, bNStList, bSimAnn, bStopCM, bRerunMD, bNotLastFrame = FALSE,
155 bFirstStep, bStateFromCP, bStateFromTPX, bInitStep, bLastStep,
156 bBornRadii, bStartingFromCpt;
157 gmx_bool bDoDHDL = FALSE, bDoFEP = FALSE, bDoExpanded = FALSE;
158 gmx_bool do_ene, do_log, do_verbose, bRerunWarnNoV = TRUE,
159 bForceUpdate = FALSE, bCPT;
160 gmx_bool bMasterState;
161 int force_flags, cglo_flags;
162 tensor force_vir, shake_vir, total_vir, tmp_vir, pres;
167 t_state *bufstate = NULL;
171 gmx_repl_ex_t repl_ex = NULL;
174 t_mdebin *mdebin = NULL;
175 t_state *state = NULL;
176 rvec *f_global = NULL;
177 gmx_enerdata_t *enerd;
179 gmx_global_stat_t gstat;
180 gmx_update_t upd = NULL;
181 t_graph *graph = NULL;
183 gmx_groups_t *groups;
184 gmx_ekindata_t *ekind, *ekind_save;
185 gmx_shellfc_t shellfc;
186 int count, nconverged = 0;
188 gmx_bool bConverged = TRUE, bSumEkinhOld, bDoReplEx, bExchanged, bNeedRepartition;
189 gmx_bool bResetCountersHalfMaxH = FALSE;
190 gmx_bool bVV, bIterativeCase, bFirstIterate, bTemp, bPres, bTrotter;
191 gmx_bool bUpdateDoLR;
195 real veta_save, scalevir, tracevir;
201 real saved_conserved_quantity = 0;
205 char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE];
206 int handled_stop_condition = gmx_stop_cond_none; /* compare to get_stop_condition*/
207 gmx_iterate_t iterate;
208 gmx_int64_t multisim_nsteps = -1; /* number of steps to do before first multisim
209 simulation stops. If equal to zero, don't
210 communicate any more between multisims.*/
211 /* PME load balancing data for GPU kernels */
212 pme_load_balancing_t pme_loadbal = NULL;
214 gmx_bool bPMETuneTry = FALSE, bPMETuneRunning = FALSE;
217 gmx_bool bIMDstep = FALSE;
220 /* Temporary addition for FAHCORE checkpointing */
224 /* Check for special mdrun options */
225 bRerunMD = (Flags & MD_RERUN);
226 if (Flags & MD_RESETCOUNTERSHALFWAY)
230 /* Signal to reset the counters half the simulation steps. */
231 wcycle_set_reset_counters(wcycle, ir->nsteps/2);
233 /* Signal to reset the counters halfway the simulation time. */
234 bResetCountersHalfMaxH = (max_hours > 0);
237 /* md-vv uses averaged full step velocities for T-control
238 md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control)
239 md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */
241 if (bVV) /* to store the initial velocities while computing virial */
243 snew(cbuf, top_global->natoms);
245 /* all the iteratative cases - only if there are constraints */
246 bIterativeCase = ((IR_NPH_TROTTER(ir) || IR_NPT_TROTTER(ir)) && (constr) && (!bRerunMD));
247 gmx_iterate_init(&iterate, FALSE); /* The default value of iterate->bIterationActive is set to
248 false in this step. The correct value, true or false,
249 is set at each step, as it depends on the frequency of temperature
250 and pressure control.*/
251 bTrotter = (bVV && (IR_NPT_TROTTER(ir) || IR_NPH_TROTTER(ir) || IR_NVT_TROTTER(ir)));
255 /* Since we don't know if the frames read are related in any way,
256 * rebuild the neighborlist at every step.
259 ir->nstcalcenergy = 1;
263 check_ir_old_tpx_versions(cr, fplog, ir, top_global);
265 nstglobalcomm = check_nstglobalcomm(fplog, cr, nstglobalcomm, ir);
266 bGStatEveryStep = (nstglobalcomm == 1);
268 if (!bGStatEveryStep && ir->nstlist == -1 && fplog != NULL)
271 "To reduce the energy communication with nstlist = -1\n"
272 "the neighbor list validity should not be checked at every step,\n"
273 "this means that exact integration is not guaranteed.\n"
274 "The neighbor list validity is checked after:\n"
275 " <n.list life time> - 2*std.dev.(n.list life time) steps.\n"
276 "In most cases this will result in exact integration.\n"
277 "This reduces the energy communication by a factor of 2 to 3.\n"
278 "If you want less energy communication, set nstlist > 3.\n\n");
283 ir->nstxout_compressed = 0;
285 groups = &top_global->groups;
288 init_md(fplog, cr, ir, oenv, &t, &t0, state_global->lambda,
289 &(state_global->fep_state), lam0,
290 nrnb, top_global, &upd,
291 nfile, fnm, &outf, &mdebin,
292 force_vir, shake_vir, mu_tot, &bSimAnn, &vcm, Flags);
294 clear_mat(total_vir);
296 /* Energy terms and groups */
298 init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
300 if (DOMAINDECOMP(cr))
306 snew(f, top_global->natoms);
309 /* Kinetic energy data */
311 init_ekindata(fplog, top_global, &(ir->opts), ekind);
312 /* needed for iteration of constraints */
314 init_ekindata(fplog, top_global, &(ir->opts), ekind_save);
315 /* Copy the cos acceleration to the groups struct */
316 ekind->cosacc.cos_accel = ir->cos_accel;
318 gstat = global_stat_init(ir);
321 /* Check for polarizable models and flexible constraints */
322 shellfc = init_shell_flexcon(fplog,
323 top_global, n_flexible_constraints(constr),
324 (ir->bContinuation ||
325 (DOMAINDECOMP(cr) && !MASTER(cr))) ?
326 NULL : state_global->x);
327 if (shellfc && ir->nstcalcenergy != 1)
329 gmx_fatal(FARGS, "You have nstcalcenergy set to a value (%d) that is different from 1.\nThis is not supported in combinations with shell particles.\nPlease make a new tpr file.", ir->nstcalcenergy);
331 if (shellfc && DOMAINDECOMP(cr))
333 gmx_fatal(FARGS, "Shell particles are not implemented with domain decomposition, use a single rank");
335 if (shellfc && ir->eI == eiNM)
337 /* Currently shells don't work with Normal Modes */
338 gmx_fatal(FARGS, "Normal Mode analysis is not supported with shells.\nIf you'd like to help with adding support, we have an open discussion at http://redmine.gromacs.org/issues/879\n");
341 if (vsite && ir->eI == eiNM)
343 /* Currently virtual sites don't work with Normal Modes */
344 gmx_fatal(FARGS, "Normal Mode analysis is not supported with virtual sites.\nIf you'd like to help with adding support, we have an open discussion at http://redmine.gromacs.org/issues/879\n");
349 tMPI_Thread_mutex_lock(&deform_init_box_mutex);
350 set_deform_reference_box(upd,
351 deform_init_init_step_tpx,
352 deform_init_box_tpx);
353 tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
357 double io = compute_io(ir, top_global->natoms, groups, mdebin->ebin->nener, 1);
358 if ((io > 2000) && MASTER(cr))
361 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
366 if (DOMAINDECOMP(cr))
368 top = dd_init_local_top(top_global);
371 dd_init_local_state(cr->dd, state_global, state);
373 if (DDMASTER(cr->dd) && ir->nstfout)
375 snew(f_global, state_global->natoms);
380 top = gmx_mtop_generate_local_top(top_global, ir);
382 forcerec_set_excl_load(fr, top);
384 state = serial_init_local_state(state_global);
387 atoms2md(top_global, ir, 0, NULL, top_global->natoms, mdatoms);
391 set_vsite_top(vsite, top, mdatoms, cr);
394 if (ir->ePBC != epbcNONE && !fr->bMolPBC)
396 graph = mk_graph(fplog, &(top->idef), 0, top_global->natoms, FALSE, FALSE);
401 make_local_shells(cr, mdatoms, shellfc);
404 setup_bonded_threading(fr, &top->idef);
407 /* Set up interactive MD (IMD) */
408 init_IMD(ir, cr, top_global, fplog, ir->nstcalcenergy, state_global->x,
409 nfile, fnm, oenv, imdport, Flags);
411 if (DOMAINDECOMP(cr))
413 /* Distribute the charge groups over the nodes from the master node */
414 dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
415 state_global, top_global, ir,
416 state, &f, mdatoms, top, fr,
417 vsite, shellfc, constr,
418 nrnb, wcycle, FALSE);
422 update_mdatoms(mdatoms, state->lambda[efptMASS]);
424 if (opt2bSet("-cpi", nfile, fnm))
426 bStateFromCP = gmx_fexist_master(opt2fn_master("-cpi", nfile, fnm, cr), cr);
430 bStateFromCP = FALSE;
435 init_expanded_ensemble(bStateFromCP, ir, &state->dfhist);
442 /* Update mdebin with energy history if appending to output files */
443 if (Flags & MD_APPENDFILES)
445 restore_energyhistory_from_state(mdebin, &state_global->enerhist);
449 /* We might have read an energy history from checkpoint,
450 * free the allocated memory and reset the counts.
452 done_energyhistory(&state_global->enerhist);
453 init_energyhistory(&state_global->enerhist);
456 /* Set the initial energy history in state by updating once */
457 update_energyhistory(&state_global->enerhist, mdebin);
460 /* Initialize constraints */
461 if (constr && !DOMAINDECOMP(cr))
463 set_constraints(constr, top, ir, mdatoms, cr);
466 if (repl_ex_nst > 0 && MASTER(cr))
468 repl_ex = init_replica_exchange(fplog, cr->ms, state_global, ir,
469 repl_ex_nst, repl_ex_nex, repl_ex_seed);
472 /* PME tuning is only supported with GPUs or PME nodes and not with rerun.
473 * PME tuning is not supported with PME only for LJ and not for Coulomb.
475 if ((Flags & MD_TUNEPME) &&
476 EEL_PME(fr->eeltype) &&
477 ( use_GPU(fr->nbv) || !(cr->duty & DUTY_PME)) &&
480 pme_loadbal_init(&pme_loadbal, ir, state->box, fr->ic, fr->pmedata);
482 if (cr->duty & DUTY_PME)
484 /* Start tuning right away, as we can't measure the load */
485 bPMETuneRunning = TRUE;
489 /* Separate PME nodes, we can measure the PP/PME load balance */
494 if (!ir->bContinuation && !bRerunMD)
496 if (mdatoms->cFREEZE && (state->flags & (1<<estV)))
498 /* Set the velocities of frozen particles to zero */
499 for (i = 0; i < mdatoms->homenr; i++)
501 for (m = 0; m < DIM; m++)
503 if (ir->opts.nFreeze[mdatoms->cFREEZE[i]][m])
513 /* Constrain the initial coordinates and velocities */
514 do_constrain_first(fplog, constr, ir, mdatoms, state,
519 /* Construct the virtual sites for the initial configuration */
520 construct_vsites(vsite, state->x, ir->delta_t, NULL,
521 top->idef.iparams, top->idef.il,
522 fr->ePBC, fr->bMolPBC, cr, state->box);
528 /* set free energy calculation frequency as the minimum
529 greatest common denominator of nstdhdl, nstexpanded, and repl_ex_nst*/
530 nstfep = ir->fepvals->nstdhdl;
533 nstfep = gmx_greatest_common_divisor(ir->fepvals->nstdhdl, nstfep);
537 nstfep = gmx_greatest_common_divisor(repl_ex_nst, nstfep);
540 /* I'm assuming we need global communication the first time! MRS */
541 cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT
542 | ((ir->comm_mode != ecmNO) ? CGLO_STOPCM : 0)
543 | (bVV ? CGLO_PRESSURE : 0)
544 | (bVV ? CGLO_CONSTRAINT : 0)
545 | (bRerunMD ? CGLO_RERUNMD : 0)
546 | ((Flags & MD_READ_EKIN) ? CGLO_READEKIN : 0));
548 bSumEkinhOld = FALSE;
549 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
550 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
551 constr, NULL, FALSE, state->box,
552 top_global, &bSumEkinhOld, cglo_flags);
553 if (ir->eI == eiVVAK)
555 /* a second call to get the half step temperature initialized as well */
556 /* we do the same call as above, but turn the pressure off -- internally to
557 compute_globals, this is recognized as a velocity verlet half-step
558 kinetic energy calculation. This minimized excess variables, but
559 perhaps loses some logic?*/
561 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
562 NULL, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
563 constr, NULL, FALSE, state->box,
564 top_global, &bSumEkinhOld,
565 cglo_flags &~(CGLO_STOPCM | CGLO_PRESSURE));
568 /* Calculate the initial half step temperature, and save the ekinh_old */
569 if (!(Flags & MD_STARTFROMCPT))
571 for (i = 0; (i < ir->opts.ngtc); i++)
573 copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old);
578 enerd->term[F_TEMP] *= 2; /* result of averages being done over previous and current step,
579 and there is no previous step */
582 /* if using an iterative algorithm, we need to create a working directory for the state. */
585 bufstate = init_bufstate(state);
588 /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter
589 temperature control */
590 trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter);
594 if (constr && !ir->bContinuation && ir->eConstrAlg == econtLINCS)
597 "RMS relative constraint deviation after constraining: %.2e\n",
598 constr_rmsd(constr, FALSE));
600 if (EI_STATE_VELOCITY(ir->eI))
602 fprintf(fplog, "Initial temperature: %g K\n", enerd->term[F_TEMP]);
606 fprintf(stderr, "starting md rerun '%s', reading coordinates from"
607 " input trajectory '%s'\n\n",
608 *(top_global->name), opt2fn("-rerun", nfile, fnm));
611 fprintf(stderr, "Calculated time to finish depends on nsteps from "
612 "run input file,\nwhich may not correspond to the time "
613 "needed to process input trajectory.\n\n");
619 fprintf(stderr, "starting mdrun '%s'\n",
620 *(top_global->name));
623 sprintf(tbuf, "%8.1f", (ir->init_step+ir->nsteps)*ir->delta_t);
627 sprintf(tbuf, "%s", "infinite");
629 if (ir->init_step > 0)
631 fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n",
632 gmx_step_str(ir->init_step+ir->nsteps, sbuf), tbuf,
633 gmx_step_str(ir->init_step, sbuf2),
634 ir->init_step*ir->delta_t);
638 fprintf(stderr, "%s steps, %s ps.\n",
639 gmx_step_str(ir->nsteps, sbuf), tbuf);
642 fprintf(fplog, "\n");
645 walltime_accounting_start(walltime_accounting);
646 wallcycle_start(wcycle, ewcRUN);
647 print_start(fplog, cr, walltime_accounting, "mdrun");
649 /* safest point to do file checkpointing is here. More general point would be immediately before integrator call */
651 chkpt_ret = fcCheckPointParallel( cr->nodeid,
655 gmx_fatal( 3, __FILE__, __LINE__, "Checkpoint error on step %d\n", 0 );
660 /***********************************************************
664 ************************************************************/
666 /* if rerunMD then read coordinates and velocities from input trajectory */
669 if (getenv("GMX_FORCE_UPDATE"))
677 bNotLastFrame = read_first_frame(oenv, &status,
678 opt2fn("-rerun", nfile, fnm),
679 &rerun_fr, TRX_NEED_X | TRX_READ_V);
680 if (rerun_fr.natoms != top_global->natoms)
683 "Number of atoms in trajectory (%d) does not match the "
684 "run input file (%d)\n",
685 rerun_fr.natoms, top_global->natoms);
687 if (ir->ePBC != epbcNONE)
691 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);
693 if (max_cutoff2(ir->ePBC, rerun_fr.box) < sqr(fr->rlistlong))
695 gmx_fatal(FARGS, "Rerun trajectory frame step %d time %f has too small box dimensions", rerun_fr.step, rerun_fr.time);
702 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
705 if (ir->ePBC != epbcNONE)
707 /* Set the shift vectors.
708 * Necessary here when have a static box different from the tpr box.
710 calc_shifts(rerun_fr.box, fr->shift_vec);
714 /* loop over MD steps or if rerunMD to end of input trajectory */
716 /* Skip the first Nose-Hoover integration when we get the state from tpx */
717 bStateFromTPX = !bStateFromCP;
718 bInitStep = bFirstStep && (bStateFromTPX || bVV);
719 bStartingFromCpt = (Flags & MD_STARTFROMCPT) && bInitStep;
720 bSumEkinhOld = FALSE;
722 bNeedRepartition = FALSE;
724 init_global_signals(&gs, cr, ir, repl_ex_nst);
726 step = ir->init_step;
729 init_nlistheuristics(&nlh, bGStatEveryStep, step);
731 if (MULTISIM(cr) && (repl_ex_nst <= 0 ))
733 /* check how many steps are left in other sims */
734 multisim_nsteps = get_multisim_nsteps(cr, ir->nsteps);
738 /* and stop now if we should */
739 bLastStep = (bRerunMD || (ir->nsteps >= 0 && step_rel > ir->nsteps) ||
740 ((multisim_nsteps >= 0) && (step_rel >= multisim_nsteps )));
741 while (!bLastStep || (bRerunMD && bNotLastFrame))
744 wallcycle_start(wcycle, ewcSTEP);
750 step = rerun_fr.step;
751 step_rel = step - ir->init_step;
764 bLastStep = (step_rel == ir->nsteps);
765 t = t0 + step*ir->delta_t;
768 if (ir->efep != efepNO || ir->bSimTemp)
770 /* find and set the current lambdas. If rerunning, we either read in a state, or a lambda value,
771 requiring different logic. */
773 set_current_lambdas(step, ir->fepvals, bRerunMD, &rerun_fr, state_global, state, lam0);
774 bDoDHDL = do_per_step(step, ir->fepvals->nstdhdl);
775 bDoFEP = (do_per_step(step, nstfep) && (ir->efep != efepNO));
776 bDoExpanded = (do_per_step(step, ir->expandedvals->nstexpanded)
777 && (ir->bExpanded) && (step > 0) && (!bStartingFromCpt));
780 bDoReplEx = ((repl_ex_nst > 0) && (step > 0) && !bLastStep &&
781 do_per_step(step, repl_ex_nst));
785 update_annealing_target_temp(&(ir->opts), t);
790 if (!DOMAINDECOMP(cr) || MASTER(cr))
792 for (i = 0; i < state_global->natoms; i++)
794 copy_rvec(rerun_fr.x[i], state_global->x[i]);
798 for (i = 0; i < state_global->natoms; i++)
800 copy_rvec(rerun_fr.v[i], state_global->v[i]);
805 for (i = 0; i < state_global->natoms; i++)
807 clear_rvec(state_global->v[i]);
811 fprintf(stderr, "\nWARNING: Some frames do not contain velocities.\n"
812 " Ekin, temperature and pressure are incorrect,\n"
813 " the virial will be incorrect when constraints are present.\n"
815 bRerunWarnNoV = FALSE;
819 copy_mat(rerun_fr.box, state_global->box);
820 copy_mat(state_global->box, state->box);
822 if (vsite && (Flags & MD_RERUN_VSITE))
824 if (DOMAINDECOMP(cr))
826 gmx_fatal(FARGS, "Vsite recalculation with -rerun is not implemented with domain decomposition, use a single rank");
830 /* Following is necessary because the graph may get out of sync
831 * with the coordinates if we only have every N'th coordinate set
833 mk_mshift(fplog, graph, fr->ePBC, state->box, state->x);
834 shift_self(graph, state->box, state->x);
836 construct_vsites(vsite, state->x, ir->delta_t, state->v,
837 top->idef.iparams, top->idef.il,
838 fr->ePBC, fr->bMolPBC, cr, state->box);
841 unshift_self(graph, state->box, state->x);
846 /* Stop Center of Mass motion */
847 bStopCM = (ir->comm_mode != ecmNO && do_per_step(step, ir->nstcomm));
851 /* for rerun MD always do Neighbour Searching */
852 bNS = (bFirstStep || ir->nstlist != 0);
857 /* Determine whether or not to do Neighbour Searching and LR */
858 bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0);
860 bNS = (bFirstStep || bExchanged || bNeedRepartition || bNStList || bDoFEP ||
861 (ir->nstlist == -1 && nlh.nabnsb > 0));
863 if (bNS && ir->nstlist == -1)
865 set_nlistheuristics(&nlh, bFirstStep || bExchanged || bNeedRepartition || bDoFEP, step);
869 /* check whether we should stop because another simulation has
873 if ( (multisim_nsteps >= 0) && (step_rel >= multisim_nsteps) &&
874 (multisim_nsteps != ir->nsteps) )
881 "Stopping simulation %d because another one has finished\n",
885 gs.sig[eglsCHKPT] = 1;
890 /* < 0 means stop at next step, > 0 means stop at next NS step */
891 if ( (gs.set[eglsSTOPCOND] < 0) ||
892 ( (gs.set[eglsSTOPCOND] > 0) && (bNStList || ir->nstlist == 0) ) )
897 /* Determine whether or not to update the Born radii if doing GB */
898 bBornRadii = bFirstStep;
899 if (ir->implicit_solvent && (step % ir->nstgbradii == 0))
904 do_log = do_per_step(step, ir->nstlog) || bFirstStep || bLastStep;
905 do_verbose = bVerbose &&
906 (step % stepout == 0 || bFirstStep || bLastStep);
908 if (bNS && !(bFirstStep && ir->bContinuation && !bRerunMD))
916 bMasterState = FALSE;
917 /* Correct the new box if it is too skewed */
918 if (DYNAMIC_BOX(*ir))
920 if (correct_box(fplog, step, state->box, graph))
925 if (DOMAINDECOMP(cr) && bMasterState)
927 dd_collect_state(cr->dd, state, state_global);
931 if (DOMAINDECOMP(cr))
933 /* Repartition the domain decomposition */
934 wallcycle_start(wcycle, ewcDOMDEC);
935 dd_partition_system(fplog, step, cr,
936 bMasterState, nstglobalcomm,
937 state_global, top_global, ir,
938 state, &f, mdatoms, top, fr,
939 vsite, shellfc, constr,
941 do_verbose && !bPMETuneRunning);
942 wallcycle_stop(wcycle, ewcDOMDEC);
943 /* If using an iterative integrator, reallocate space to match the decomposition */
947 if (MASTER(cr) && do_log)
949 print_ebin_header(fplog, step, t, state->lambda[efptFEP]); /* can we improve the information printed here? */
952 if (ir->efep != efepNO)
954 update_mdatoms(mdatoms, state->lambda[efptMASS]);
957 if ((bRerunMD && rerun_fr.bV) || bExchanged)
960 /* We need the kinetic energy at minus the half step for determining
961 * the full step kinetic energy and possibly for T-coupling.*/
962 /* This may not be quite working correctly yet . . . . */
963 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
964 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
965 constr, NULL, FALSE, state->box,
966 top_global, &bSumEkinhOld,
967 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
969 clear_mat(force_vir);
971 /* We write a checkpoint at this MD step when:
972 * either at an NS step when we signalled through gs,
973 * or at the last step (but not when we do not want confout),
974 * but never at the first step or with rerun.
976 bCPT = (((gs.set[eglsCHKPT] && (bNS || ir->nstlist == 0)) ||
977 (bLastStep && (Flags & MD_CONFOUT))) &&
978 step > ir->init_step && !bRerunMD);
981 gs.set[eglsCHKPT] = 0;
984 /* Determine the energy and pressure:
985 * at nstcalcenergy steps and at energy output steps (set below).
987 if (EI_VV(ir->eI) && (!bInitStep))
989 /* for vv, the first half of the integration actually corresponds
990 to the previous step. bCalcEner is only required to be evaluated on the 'next' step,
991 but the virial needs to be calculated on both the current step and the 'next' step. Future
992 reorganization may be able to get rid of one of the bCalcVir=TRUE steps. */
994 bCalcEner = do_per_step(step-1, ir->nstcalcenergy);
995 bCalcVir = bCalcEner ||
996 (ir->epc != epcNO && (do_per_step(step, ir->nstpcouple) || do_per_step(step-1, ir->nstpcouple)));
1000 bCalcEner = do_per_step(step, ir->nstcalcenergy);
1001 bCalcVir = bCalcEner ||
1002 (ir->epc != epcNO && do_per_step(step, ir->nstpcouple));
1005 /* Do we need global communication ? */
1006 bGStat = (bCalcVir || bCalcEner || bStopCM ||
1007 do_per_step(step, nstglobalcomm) || (bVV && IR_NVT_TROTTER(ir) && do_per_step(step-1, nstglobalcomm)) ||
1008 (ir->nstlist == -1 && !bRerunMD && step >= nlh.step_nscheck));
1010 do_ene = (do_per_step(step, ir->nstenergy) || bLastStep);
1012 if (do_ene || do_log || bDoReplEx)
1019 /* these CGLO_ options remain the same throughout the iteration */
1020 cglo_flags = ((bRerunMD ? CGLO_RERUNMD : 0) |
1021 (bGStat ? CGLO_GSTAT : 0)
1024 force_flags = (GMX_FORCE_STATECHANGED |
1025 ((DYNAMIC_BOX(*ir) || bRerunMD) ? GMX_FORCE_DYNAMICBOX : 0) |
1026 GMX_FORCE_ALLFORCES |
1028 (bCalcVir ? GMX_FORCE_VIRIAL : 0) |
1029 (bCalcEner ? GMX_FORCE_ENERGY : 0) |
1030 (bDoFEP ? GMX_FORCE_DHDL : 0)
1035 if (do_per_step(step, ir->nstcalclr))
1037 force_flags |= GMX_FORCE_DO_LR;
1043 /* Now is the time to relax the shells */
1044 count = relax_shell_flexcon(fplog, cr, bVerbose, step,
1045 ir, bNS, force_flags,
1048 state, f, force_vir, mdatoms,
1049 nrnb, wcycle, graph, groups,
1050 shellfc, fr, bBornRadii, t, mu_tot,
1052 mdoutf_get_fp_field(outf));
1062 /* The coordinates (x) are shifted (to get whole molecules)
1064 * This is parallellized as well, and does communication too.
1065 * Check comments in sim_util.c
1067 do_force(fplog, cr, ir, step, nrnb, wcycle, top, groups,
1068 state->box, state->x, &state->hist,
1069 f, force_vir, mdatoms, enerd, fcd,
1070 state->lambda, graph,
1071 fr, vsite, mu_tot, t, mdoutf_get_fp_field(outf), ed, bBornRadii,
1072 (bNS ? GMX_FORCE_NS : 0) | force_flags);
1075 if (bVV && !bStartingFromCpt && !bRerunMD)
1076 /* ############### START FIRST UPDATE HALF-STEP FOR VV METHODS############### */
1078 if (ir->eI == eiVV && bInitStep)
1080 /* if using velocity verlet with full time step Ekin,
1081 * take the first half step only to compute the
1082 * virial for the first step. From there,
1083 * revert back to the initial coordinates
1084 * so that the input is actually the initial step.
1086 copy_rvecn(state->v, cbuf, 0, state->natoms); /* should make this better for parallelizing? */
1090 /* this is for NHC in the Ekin(t+dt/2) version of vv */
1091 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ1);
1094 /* If we are using twin-range interactions where the long-range component
1095 * is only evaluated every nstcalclr>1 steps, we should do a special update
1096 * step to combine the long-range forces on these steps.
1097 * For nstcalclr=1 this is not done, since the forces would have been added
1098 * directly to the short-range forces already.
1100 * TODO Remove various aspects of VV+twin-range in master
1101 * branch, because VV integrators did not ever support
1102 * twin-range multiple time stepping with constraints.
1104 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1106 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC,
1107 f, bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1108 ekind, M, upd, bInitStep, etrtVELOCITY1,
1109 cr, nrnb, constr, &top->idef);
1111 if (bIterativeCase && do_per_step(step-1, ir->nstpcouple) && !bInitStep)
1113 gmx_iterate_init(&iterate, TRUE);
1115 /* for iterations, we save these vectors, as we will be self-consistently iterating
1118 /*#### UPDATE EXTENDED VARIABLES IN TROTTER FORMULATION */
1120 /* save the state */
1121 if (iterate.bIterationActive)
1123 copy_coupling_state(state, bufstate, ekind, ekind_save, &(ir->opts));
1126 bFirstIterate = TRUE;
1127 while (bFirstIterate || iterate.bIterationActive)
1129 if (iterate.bIterationActive)
1131 copy_coupling_state(bufstate, state, ekind_save, ekind, &(ir->opts));
1132 if (bFirstIterate && bTrotter)
1134 /* The first time through, we need a decent first estimate
1135 of veta(t+dt) to compute the constraints. Do
1136 this by computing the box volume part of the
1137 trotter integration at this time. Nothing else
1138 should be changed by this routine here. If
1139 !(first time), we start with the previous value
1142 veta_save = state->veta;
1143 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ0);
1144 vetanew = state->veta;
1145 state->veta = veta_save;
1149 if (!bRerunMD || rerun_fr.bV || bForceUpdate) /* Why is rerun_fr.bV here? Unclear. */
1151 update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1152 state, fr->bMolPBC, graph, f,
1153 &top->idef, shake_vir,
1154 cr, nrnb, wcycle, upd, constr,
1155 TRUE, bCalcVir, vetanew);
1157 if (bCalcVir && bUpdateDoLR && ir->nstcalclr > 1)
1159 /* Correct the virial for multiple time stepping */
1160 m_sub(shake_vir, fr->vir_twin_constr, shake_vir);
1165 /* Need to unshift here if a do_force has been
1166 called in the previous step */
1167 unshift_self(graph, state->box, state->x);
1170 /* if VV, compute the pressure and constraints */
1171 /* For VV2, we strictly only need this if using pressure
1172 * control, but we really would like to have accurate pressures
1174 * Think about ways around this in the future?
1175 * For now, keep this choice in comments.
1177 /*bPres = (ir->eI==eiVV || IR_NPT_TROTTER(ir)); */
1178 /*bTemp = ((ir->eI==eiVV &&(!bInitStep)) || (ir->eI==eiVVAK && IR_NPT_TROTTER(ir)));*/
1180 bTemp = ((ir->eI == eiVV && (!bInitStep)) || (ir->eI == eiVVAK));
1181 if (bCalcEner && ir->eI == eiVVAK) /*MRS: 7/9/2010 -- this still doesn't fix it?*/
1183 bSumEkinhOld = TRUE;
1185 /* for vv, the first half of the integration actually corresponds to the previous step.
1186 So we need information from the last step in the first half of the integration */
1187 if (bGStat || do_per_step(step-1, nstglobalcomm))
1189 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1190 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1191 constr, NULL, FALSE, state->box,
1192 top_global, &bSumEkinhOld,
1195 | (bTemp ? CGLO_TEMPERATURE : 0)
1196 | (bPres ? CGLO_PRESSURE : 0)
1197 | (bPres ? CGLO_CONSTRAINT : 0)
1198 | ((iterate.bIterationActive) ? CGLO_ITERATE : 0)
1199 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1202 /* explanation of above:
1203 a) We compute Ekin at the full time step
1204 if 1) we are using the AveVel Ekin, and it's not the
1205 initial step, or 2) if we are using AveEkin, but need the full
1206 time step kinetic energy for the pressure (always true now, since we want accurate statistics).
1207 b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in
1208 EkinAveVel because it's needed for the pressure */
1210 /* temperature scaling and pressure scaling to produce the extended variables at t+dt */
1215 m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */
1216 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ2);
1223 /* We need the kinetic energy at minus the half step for determining
1224 * the full step kinetic energy and possibly for T-coupling.*/
1225 /* This may not be quite working correctly yet . . . . */
1226 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1227 wcycle, enerd, NULL, NULL, NULL, NULL, mu_tot,
1228 constr, NULL, FALSE, state->box,
1229 top_global, &bSumEkinhOld,
1230 CGLO_RERUNMD | CGLO_GSTAT | CGLO_TEMPERATURE);
1235 if (iterate.bIterationActive &&
1236 done_iterating(cr, fplog, step, &iterate, bFirstIterate,
1237 state->veta, &vetanew))
1241 bFirstIterate = FALSE;
1244 if (bTrotter && !bInitStep)
1246 copy_mat(shake_vir, state->svir_prev);
1247 copy_mat(force_vir, state->fvir_prev);
1248 if (IR_NVT_TROTTER(ir) && ir->eI == eiVV)
1250 /* update temperature and kinetic energy now that step is over - this is the v(t+dt) point */
1251 enerd->term[F_TEMP] = sum_ekin(&(ir->opts), ekind, NULL, (ir->eI == eiVV), FALSE);
1252 enerd->term[F_EKIN] = trace(ekind->ekin);
1255 /* if it's the initial step, we performed this first step just to get the constraint virial */
1256 if (bInitStep && ir->eI == eiVV)
1258 copy_rvecn(cbuf, state->v, 0, state->natoms);
1262 /* MRS -- now done iterating -- compute the conserved quantity */
1265 saved_conserved_quantity = compute_conserved_from_auxiliary(ir, state, &MassQ);
1268 last_ekin = enerd->term[F_EKIN];
1270 if ((ir->eDispCorr != edispcEnerPres) && (ir->eDispCorr != edispcAllEnerPres))
1272 saved_conserved_quantity -= enerd->term[F_DISPCORR];
1274 /* sum up the foreign energy and dhdl terms for vv. currently done every step so that dhdl is correct in the .edr */
1277 sum_dhdl(enerd, state->lambda, ir->fepvals);
1281 /* ######## END FIRST UPDATE STEP ############## */
1282 /* ######## If doing VV, we now have v(dt) ###### */
1285 /* perform extended ensemble sampling in lambda - we don't
1286 actually move to the new state before outputting
1287 statistics, but if performing simulated tempering, we
1288 do update the velocities and the tau_t. */
1290 lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, state->fep_state, &state->dfhist, step, state->v, mdatoms);
1291 /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */
1292 copy_df_history(&state_global->dfhist, &state->dfhist);
1295 /* Now we have the energies and forces corresponding to the
1296 * coordinates at time t. We must output all of this before
1299 do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t,
1300 ir, state, state_global, top_global, fr,
1301 outf, mdebin, ekind, f, f_global,
1303 bCPT, bRerunMD, bLastStep, (Flags & MD_CONFOUT),
1305 /* Check if IMD step and do IMD communication, if bIMD is TRUE. */
1306 bIMDstep = do_IMD(ir->bIMD, step, cr, bNS, state->box, state->x, ir, t, wcycle);
1308 /* kludge -- virial is lost with restart for NPT control. Must restart */
1309 if (bStartingFromCpt && bVV)
1311 copy_mat(state->svir_prev, shake_vir);
1312 copy_mat(state->fvir_prev, force_vir);
1315 elapsed_time = walltime_accounting_get_current_elapsed_time(walltime_accounting);
1317 /* Check whether everything is still allright */
1318 if (((int)gmx_get_stop_condition() > handled_stop_condition)
1319 #ifdef GMX_THREAD_MPI
1324 /* this is just make gs.sig compatible with the hack
1325 of sending signals around by MPI_Reduce with together with
1327 if (gmx_get_stop_condition() == gmx_stop_cond_next_ns)
1329 gs.sig[eglsSTOPCOND] = 1;
1331 if (gmx_get_stop_condition() == gmx_stop_cond_next)
1333 gs.sig[eglsSTOPCOND] = -1;
1335 /* < 0 means stop at next step, > 0 means stop at next NS step */
1339 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1340 gmx_get_signal_name(),
1341 gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1345 "\n\nReceived the %s signal, stopping at the next %sstep\n\n",
1346 gmx_get_signal_name(),
1347 gs.sig[eglsSTOPCOND] == 1 ? "NS " : "");
1349 handled_stop_condition = (int)gmx_get_stop_condition();
1351 else if (MASTER(cr) && (bNS || ir->nstlist <= 0) &&
1352 (max_hours > 0 && elapsed_time > max_hours*60.0*60.0*0.99) &&
1353 gs.sig[eglsSTOPCOND] == 0 && gs.set[eglsSTOPCOND] == 0)
1355 /* Signal to terminate the run */
1356 gs.sig[eglsSTOPCOND] = 1;
1359 fprintf(fplog, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1361 fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, will terminate the run\n", gmx_step_str(step, sbuf), max_hours*0.99);
1364 if (bResetCountersHalfMaxH && MASTER(cr) &&
1365 elapsed_time > max_hours*60.0*60.0*0.495)
1367 gs.sig[eglsRESETCOUNTERS] = 1;
1370 if (ir->nstlist == -1 && !bRerunMD)
1372 /* When bGStatEveryStep=FALSE, global_stat is only called
1373 * when we check the atom displacements, not at NS steps.
1374 * This means that also the bonded interaction count check is not
1375 * performed immediately after NS. Therefore a few MD steps could
1376 * be performed with missing interactions.
1377 * But wrong energies are never written to file,
1378 * since energies are only written after global_stat
1381 if (step >= nlh.step_nscheck)
1383 nlh.nabnsb = natoms_beyond_ns_buffer(ir, fr, &top->cgs,
1384 nlh.scale_tot, state->x);
1388 /* This is not necessarily true,
1389 * but step_nscheck is determined quite conservatively.
1395 /* In parallel we only have to check for checkpointing in steps
1396 * where we do global communication,
1397 * otherwise the other nodes don't know.
1399 if (MASTER(cr) && ((bGStat || !PAR(cr)) &&
1402 elapsed_time >= nchkpt*cpt_period*60.0)) &&
1403 gs.set[eglsCHKPT] == 0)
1405 gs.sig[eglsCHKPT] = 1;
1408 /* at the start of step, randomize or scale the velocities (trotter done elsewhere) */
1413 update_tcouple(step, ir, state, ekind, &MassQ, mdatoms);
1415 if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */
1417 gmx_bool bIfRandomize;
1418 bIfRandomize = update_randomize_velocities(ir, step, cr, mdatoms, state, upd, constr);
1419 /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */
1420 if (constr && bIfRandomize)
1422 update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1423 state, fr->bMolPBC, graph, f,
1424 &top->idef, tmp_vir,
1425 cr, nrnb, wcycle, upd, constr,
1426 TRUE, bCalcVir, vetanew);
1431 if (bIterativeCase && do_per_step(step, ir->nstpcouple))
1433 gmx_iterate_init(&iterate, TRUE);
1434 /* for iterations, we save these vectors, as we will be redoing the calculations */
1435 copy_coupling_state(state, bufstate, ekind, ekind_save, &(ir->opts));
1438 bFirstIterate = TRUE;
1439 while (bFirstIterate || iterate.bIterationActive)
1441 /* We now restore these vectors to redo the calculation with improved extended variables */
1442 if (iterate.bIterationActive)
1444 copy_coupling_state(bufstate, state, ekind_save, ekind, &(ir->opts));
1447 /* We make the decision to break or not -after- the calculation of Ekin and Pressure,
1448 so scroll down for that logic */
1450 /* ######### START SECOND UPDATE STEP ################# */
1451 /* Box is changed in update() when we do pressure coupling,
1452 * but we should still use the old box for energy corrections and when
1453 * writing it to the energy file, so it matches the trajectory files for
1454 * the same timestep above. Make a copy in a separate array.
1456 copy_mat(state->box, lastbox);
1460 if (!(bRerunMD && !rerun_fr.bV && !bForceUpdate))
1462 wallcycle_start(wcycle, ewcUPDATE);
1463 /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */
1466 if (iterate.bIterationActive)
1474 /* we use a new value of scalevir to converge the iterations faster */
1475 scalevir = tracevir/trace(shake_vir);
1477 msmul(shake_vir, scalevir, shake_vir);
1478 m_add(force_vir, shake_vir, total_vir);
1479 clear_mat(shake_vir);
1481 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ3);
1482 /* We can only do Berendsen coupling after we have summed
1483 * the kinetic energy or virial. Since the happens
1484 * in global_state after update, we should only do it at
1485 * step % nstlist = 1 with bGStatEveryStep=FALSE.
1490 update_tcouple(step, ir, state, ekind, &MassQ, mdatoms);
1491 update_pcouple(fplog, step, ir, state, pcoupl_mu, M, bInitStep);
1496 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1498 /* velocity half-step update */
1499 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1500 bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1501 ekind, M, upd, FALSE, etrtVELOCITY2,
1502 cr, nrnb, constr, &top->idef);
1505 /* Above, initialize just copies ekinh into ekin,
1506 * it doesn't copy position (for VV),
1507 * and entire integrator for MD.
1510 if (ir->eI == eiVVAK)
1512 copy_rvecn(state->x, cbuf, 0, state->natoms);
1514 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1516 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1517 bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1518 ekind, M, upd, bInitStep, etrtPOSITION, cr, nrnb, constr, &top->idef);
1519 wallcycle_stop(wcycle, ewcUPDATE);
1521 update_constraints(fplog, step, &dvdl_constr, ir, ekind, mdatoms, state,
1522 fr->bMolPBC, graph, f,
1523 &top->idef, shake_vir,
1524 cr, nrnb, wcycle, upd, constr,
1525 FALSE, bCalcVir, state->veta);
1527 if (bCalcVir && bUpdateDoLR && ir->nstcalclr > 1)
1529 /* Correct the virial for multiple time stepping */
1530 m_sub(shake_vir, fr->vir_twin_constr, shake_vir);
1533 if (ir->eI == eiVVAK)
1535 /* erase F_EKIN and F_TEMP here? */
1536 /* just compute the kinetic energy at the half step to perform a trotter step */
1537 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1538 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1539 constr, NULL, FALSE, lastbox,
1540 top_global, &bSumEkinhOld,
1541 cglo_flags | CGLO_TEMPERATURE
1543 wallcycle_start(wcycle, ewcUPDATE);
1544 trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, &MassQ, trotter_seq, ettTSEQ4);
1545 /* now we know the scaling, we can compute the positions again again */
1546 copy_rvecn(cbuf, state->x, 0, state->natoms);
1548 bUpdateDoLR = (fr->bTwinRange && do_per_step(step, ir->nstcalclr));
1550 update_coords(fplog, step, ir, mdatoms, state, fr->bMolPBC, f,
1551 bUpdateDoLR, fr->f_twin, bCalcVir ? &fr->vir_twin_constr : NULL, fcd,
1552 ekind, M, upd, bInitStep, etrtPOSITION, cr, nrnb, constr, &top->idef);
1553 wallcycle_stop(wcycle, ewcUPDATE);
1555 /* do we need an extra constraint here? just need to copy out of state->v to upd->xp? */
1556 /* are the small terms in the shake_vir here due
1557 * to numerical errors, or are they important
1558 * physically? I'm thinking they are just errors, but not completely sure.
1559 * For now, will call without actually constraining, constr=NULL*/
1560 update_constraints(fplog, step, NULL, ir, ekind, mdatoms,
1561 state, fr->bMolPBC, graph, f,
1562 &top->idef, tmp_vir,
1563 cr, nrnb, wcycle, upd, NULL,
1570 /* this factor or 2 correction is necessary
1571 because half of the constraint force is removed
1572 in the vv step, so we have to double it. See
1573 the Redmine issue #1255. It is not yet clear
1574 if the factor of 2 is exact, or just a very
1575 good approximation, and this will be
1576 investigated. The next step is to see if this
1577 can be done adding a dhdl contribution from the
1578 rattle step, but this is somewhat more
1579 complicated with the current code. Will be
1580 investigated, hopefully for 4.6.3. However,
1581 this current solution is much better than
1582 having it completely wrong.
1584 enerd->term[F_DVDL_CONSTR] += 2*dvdl_constr;
1588 enerd->term[F_DVDL_CONSTR] += dvdl_constr;
1593 /* Need to unshift here */
1594 unshift_self(graph, state->box, state->x);
1599 wallcycle_start(wcycle, ewcVSITECONSTR);
1602 shift_self(graph, state->box, state->x);
1604 construct_vsites(vsite, state->x, ir->delta_t, state->v,
1605 top->idef.iparams, top->idef.il,
1606 fr->ePBC, fr->bMolPBC, cr, state->box);
1610 unshift_self(graph, state->box, state->x);
1612 wallcycle_stop(wcycle, ewcVSITECONSTR);
1615 /* ############## IF NOT VV, Calculate globals HERE, also iterate constraints ############ */
1616 /* With Leap-Frog we can skip compute_globals at
1617 * non-communication steps, but we need to calculate
1618 * the kinetic energy one step before communication.
1620 if (bGStat || (!EI_VV(ir->eI) && do_per_step(step+1, nstglobalcomm)))
1622 if (ir->nstlist == -1 && bFirstIterate)
1624 gs.sig[eglsNABNSB] = nlh.nabnsb;
1626 compute_globals(fplog, gstat, cr, ir, fr, ekind, state, state_global, mdatoms, nrnb, vcm,
1627 wcycle, enerd, force_vir, shake_vir, total_vir, pres, mu_tot,
1629 bFirstIterate ? &gs : NULL,
1630 (step_rel % gs.nstms == 0) &&
1631 (multisim_nsteps < 0 || (step_rel < multisim_nsteps)),
1633 top_global, &bSumEkinhOld,
1635 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_ENERGY : 0)
1636 | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0)
1637 | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0)
1638 | (!EI_VV(ir->eI) || bRerunMD ? CGLO_PRESSURE : 0)
1639 | (iterate.bIterationActive ? CGLO_ITERATE : 0)
1640 | (bFirstIterate ? CGLO_FIRSTITERATE : 0)
1643 if (ir->nstlist == -1 && bFirstIterate)
1645 nlh.nabnsb = gs.set[eglsNABNSB];
1646 gs.set[eglsNABNSB] = 0;
1649 /* bIterate is set to keep it from eliminating the old ekin kinetic energy terms */
1650 /* ############# END CALC EKIN AND PRESSURE ################# */
1652 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
1653 the virial that should probably be addressed eventually. state->veta has better properies,
1654 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
1655 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
1657 if (iterate.bIterationActive &&
1658 done_iterating(cr, fplog, step, &iterate, bFirstIterate,
1659 trace(shake_vir), &tracevir))
1663 bFirstIterate = FALSE;
1666 if (!bVV || bRerunMD)
1668 /* sum up the foreign energy and dhdl terms for md and sd. currently done every step so that dhdl is correct in the .edr */
1669 sum_dhdl(enerd, state->lambda, ir->fepvals);
1671 update_box(fplog, step, ir, mdatoms, state, f,
1672 ir->nstlist == -1 ? &nlh.scale_tot : NULL, pcoupl_mu, nrnb, upd);
1674 /* ################# END UPDATE STEP 2 ################# */
1675 /* #### We now have r(t+dt) and v(t+dt/2) ############# */
1677 /* The coordinates (x) were unshifted in update */
1680 /* We will not sum ekinh_old,
1681 * so signal that we still have to do it.
1683 bSumEkinhOld = TRUE;
1686 /* ######### BEGIN PREPARING EDR OUTPUT ########### */
1688 /* use the directly determined last velocity, not actually the averaged half steps */
1689 if (bTrotter && ir->eI == eiVV)
1691 enerd->term[F_EKIN] = last_ekin;
1693 enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN];
1697 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity;
1701 enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + compute_conserved_from_auxiliary(ir, state, &MassQ);
1703 /* ######### END PREPARING EDR OUTPUT ########### */
1708 gmx_bool do_dr, do_or;
1710 if (fplog && do_log && bDoExpanded)
1712 /* only needed if doing expanded ensemble */
1713 PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, ir->bSimTemp ? ir->simtempvals : NULL,
1714 &state_global->dfhist, state->fep_state, ir->nstlog, step);
1716 if (!(bStartingFromCpt && (EI_VV(ir->eI))))
1720 upd_mdebin(mdebin, bDoDHDL, TRUE,
1721 t, mdatoms->tmass, enerd, state,
1722 ir->fepvals, ir->expandedvals, lastbox,
1723 shake_vir, force_vir, total_vir, pres,
1724 ekind, mu_tot, constr);
1728 upd_mdebin_step(mdebin);
1731 do_dr = do_per_step(step, ir->nstdisreout);
1732 do_or = do_per_step(step, ir->nstorireout);
1734 print_ebin(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, do_log ? fplog : NULL,
1736 eprNORMAL, bCompact, mdebin, fcd, groups, &(ir->opts));
1738 if (ir->ePull != epullNO)
1740 pull_print_output(ir->pull, step, t);
1743 if (do_per_step(step, ir->nstlog))
1745 if (fflush(fplog) != 0)
1747 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
1753 /* Have to do this part _after_ outputting the logfile and the edr file */
1754 /* Gets written into the state at the beginning of next loop*/
1755 state->fep_state = lamnew;
1757 /* Print the remaining wall clock time for the run */
1758 if (MULTIMASTER(cr) && (do_verbose || gmx_got_usr_signal()) && !bPMETuneRunning)
1762 fprintf(stderr, "\n");
1764 print_time(stderr, walltime_accounting, step, ir, cr);
1767 /* Ion/water position swapping.
1768 * Not done in last step since trajectory writing happens before this call
1769 * in the MD loop and exchanges would be lost anyway. */
1770 bNeedRepartition = FALSE;
1771 if ((ir->eSwapCoords != eswapNO) && (step > 0) && !bLastStep &&
1772 do_per_step(step, ir->swap->nstswap))
1774 bNeedRepartition = do_swapcoords(cr, step, t, ir, wcycle,
1775 bRerunMD ? rerun_fr.x : state->x,
1776 bRerunMD ? rerun_fr.box : state->box,
1777 top_global, MASTER(cr) && bVerbose, bRerunMD);
1779 if (bNeedRepartition && DOMAINDECOMP(cr))
1781 dd_collect_state(cr->dd, state, state_global);
1785 /* Replica exchange */
1789 bExchanged = replica_exchange(fplog, cr, repl_ex,
1790 state_global, enerd,
1794 if ( (bExchanged || bNeedRepartition) && DOMAINDECOMP(cr) )
1796 dd_partition_system(fplog, step, cr, TRUE, 1,
1797 state_global, top_global, ir,
1798 state, &f, mdatoms, top, fr,
1799 vsite, shellfc, constr,
1800 nrnb, wcycle, FALSE);
1805 bStartingFromCpt = FALSE;
1807 /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */
1808 /* With all integrators, except VV, we need to retain the pressure
1809 * at the current step for coupling at the next step.
1811 if ((state->flags & (1<<estPRES_PREV)) &&
1813 (ir->nstpcouple > 0 && step % ir->nstpcouple == 0)))
1815 /* Store the pressure in t_state for pressure coupling
1816 * at the next MD step.
1818 copy_mat(pres, state->pres_prev);
1821 /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */
1823 if ( (membed != NULL) && (!bLastStep) )
1825 rescale_membed(step_rel, membed, state_global->x);
1832 /* read next frame from input trajectory */
1833 bNotLastFrame = read_next_frame(oenv, status, &rerun_fr);
1838 rerun_parallel_comm(cr, &rerun_fr, &bNotLastFrame);
1842 if (!bRerunMD || !rerun_fr.bStep)
1844 /* increase the MD step number */
1849 cycles = wallcycle_stop(wcycle, ewcSTEP);
1850 if (DOMAINDECOMP(cr) && wcycle)
1852 dd_cycles_add(cr->dd, cycles, ddCyclStep);
1855 if (bPMETuneRunning || bPMETuneTry)
1857 /* PME grid + cut-off optimization with GPUs or PME nodes */
1859 /* Count the total cycles over the last steps */
1860 cycles_pmes += cycles;
1862 /* We can only switch cut-off at NS steps */
1863 if (step % ir->nstlist == 0)
1865 /* PME grid + cut-off optimization with GPUs or PME nodes */
1868 if (DDMASTER(cr->dd))
1870 /* PME node load is too high, start tuning */
1871 bPMETuneRunning = (dd_pme_f_ratio(cr->dd) >= 1.05);
1873 dd_bcast(cr->dd, sizeof(gmx_bool), &bPMETuneRunning);
1875 if (bPMETuneRunning || step_rel > ir->nstlist*50)
1877 bPMETuneTry = FALSE;
1880 if (bPMETuneRunning)
1882 /* init_step might not be a multiple of nstlist,
1883 * but the first cycle is always skipped anyhow.
1886 pme_load_balance(pme_loadbal, cr,
1887 (bVerbose && MASTER(cr)) ? stderr : NULL,
1889 ir, state, cycles_pmes,
1890 fr->ic, fr->nbv, &fr->pmedata,
1893 /* Update constants in forcerec/inputrec to keep them in sync with fr->ic */
1894 fr->ewaldcoeff_q = fr->ic->ewaldcoeff_q;
1895 fr->ewaldcoeff_lj = fr->ic->ewaldcoeff_lj;
1896 fr->rlist = fr->ic->rlist;
1897 fr->rlistlong = fr->ic->rlistlong;
1898 fr->rcoulomb = fr->ic->rcoulomb;
1899 fr->rvdw = fr->ic->rvdw;
1901 if (ir->eDispCorr != edispcNO)
1903 calc_enervirdiff(NULL, ir->eDispCorr, fr);
1910 if (step_rel == wcycle_get_reset_counters(wcycle) ||
1911 gs.set[eglsRESETCOUNTERS] != 0)
1913 /* Reset all the counters related to performance over the run */
1914 reset_all_counters(fplog, cr, step, &step_rel, ir, wcycle, nrnb, walltime_accounting,
1915 use_GPU(fr->nbv) ? fr->nbv : NULL);
1916 wcycle_set_reset_counters(wcycle, -1);
1917 if (!(cr->duty & DUTY_PME))
1919 /* Tell our PME node to reset its counters */
1920 gmx_pme_send_resetcounters(cr, step);
1922 /* Correct max_hours for the elapsed time */
1923 max_hours -= elapsed_time/(60.0*60.0);
1924 bResetCountersHalfMaxH = FALSE;
1925 gs.set[eglsRESETCOUNTERS] = 0;
1928 /* If bIMD is TRUE, the master updates the IMD energy record and sends positions to VMD client */
1929 IMD_prep_energies_send_positions(ir->bIMD && MASTER(cr), bIMDstep, ir->imd, enerd, step, bCalcEner, wcycle);
1932 /* End of main MD loop */
1935 /* Stop measuring walltime */
1936 walltime_accounting_end(walltime_accounting);
1938 if (bRerunMD && MASTER(cr))
1943 if (!(cr->duty & DUTY_PME))
1945 /* Tell the PME only node to finish */
1946 gmx_pme_send_finish(cr);
1951 if (ir->nstcalcenergy > 0 && !bRerunMD)
1953 print_ebin(mdoutf_get_fp_ene(outf), FALSE, FALSE, FALSE, fplog, step, t,
1954 eprAVER, FALSE, mdebin, fcd, groups, &(ir->opts));
1961 if (ir->nstlist == -1 && nlh.nns > 0 && fplog)
1963 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)));
1964 fprintf(fplog, "Average number of atoms that crossed the half buffer length: %.1f\n\n", nlh.ab/nlh.nns);
1967 if (pme_loadbal != NULL)
1969 pme_loadbal_done(pme_loadbal, cr, fplog,
1973 if (shellfc && fplog)
1975 fprintf(fplog, "Fraction of iterations that converged: %.2f %%\n",
1976 (nconverged*100.0)/step_rel);
1977 fprintf(fplog, "Average number of force evaluations per MD step: %.2f\n\n",
1981 if (repl_ex_nst > 0 && MASTER(cr))
1983 print_replica_exchange_statistics(fplog, repl_ex);
1986 /* IMD cleanup, if bIMD is TRUE. */
1987 IMD_finalize(ir->bIMD, ir->imd);
1989 walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);