Add InteractionDefinitions
[alexxy/gromacs.git] / src / gromacs / mdrun / rerun.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  *
37  * \brief Implements the loop for simulation reruns
38  *
39  * \author Pascal Merz <pascal.merz@colorado.edu>
40  * \ingroup module_mdrun
41  */
42 #include "gmxpre.h"
43
44 #include <cinttypes>
45 #include <cmath>
46 #include <cstdio>
47 #include <cstdlib>
48
49 #include <algorithm>
50 #include <memory>
51
52 #include "gromacs/awh/awh.h"
53 #include "gromacs/commandline/filenm.h"
54 #include "gromacs/domdec/collect.h"
55 #include "gromacs/domdec/dlbtiming.h"
56 #include "gromacs/domdec/domdec.h"
57 #include "gromacs/domdec/domdec_network.h"
58 #include "gromacs/domdec/domdec_struct.h"
59 #include "gromacs/domdec/mdsetup.h"
60 #include "gromacs/domdec/partition.h"
61 #include "gromacs/essentialdynamics/edsam.h"
62 #include "gromacs/ewald/pme_load_balancing.h"
63 #include "gromacs/ewald/pme_pp.h"
64 #include "gromacs/fileio/trxio.h"
65 #include "gromacs/gmxlib/network.h"
66 #include "gromacs/gmxlib/nrnb.h"
67 #include "gromacs/gpu_utils/gpu_utils.h"
68 #include "gromacs/listed_forces/manage_threading.h"
69 #include "gromacs/math/functions.h"
70 #include "gromacs/math/utilities.h"
71 #include "gromacs/math/vec.h"
72 #include "gromacs/math/vectypes.h"
73 #include "gromacs/mdlib/checkpointhandler.h"
74 #include "gromacs/mdlib/compute_io.h"
75 #include "gromacs/mdlib/constr.h"
76 #include "gromacs/mdlib/ebin.h"
77 #include "gromacs/mdlib/enerdata_utils.h"
78 #include "gromacs/mdlib/energyoutput.h"
79 #include "gromacs/mdlib/expanded.h"
80 #include "gromacs/mdlib/force.h"
81 #include "gromacs/mdlib/force_flags.h"
82 #include "gromacs/mdlib/forcerec.h"
83 #include "gromacs/mdlib/md_support.h"
84 #include "gromacs/mdlib/mdatoms.h"
85 #include "gromacs/mdlib/mdoutf.h"
86 #include "gromacs/mdlib/membed.h"
87 #include "gromacs/mdlib/resethandler.h"
88 #include "gromacs/mdlib/sighandler.h"
89 #include "gromacs/mdlib/simulationsignal.h"
90 #include "gromacs/mdlib/stat.h"
91 #include "gromacs/mdlib/stophandler.h"
92 #include "gromacs/mdlib/tgroup.h"
93 #include "gromacs/mdlib/trajectory_writing.h"
94 #include "gromacs/mdlib/update.h"
95 #include "gromacs/mdlib/vcm.h"
96 #include "gromacs/mdlib/vsite.h"
97 #include "gromacs/mdrunutility/handlerestart.h"
98 #include "gromacs/mdrunutility/multisim.h"
99 #include "gromacs/mdrunutility/printtime.h"
100 #include "gromacs/mdtypes/awh_history.h"
101 #include "gromacs/mdtypes/awh_params.h"
102 #include "gromacs/mdtypes/commrec.h"
103 #include "gromacs/mdtypes/df_history.h"
104 #include "gromacs/mdtypes/energyhistory.h"
105 #include "gromacs/mdtypes/fcdata.h"
106 #include "gromacs/mdtypes/forcerec.h"
107 #include "gromacs/mdtypes/group.h"
108 #include "gromacs/mdtypes/inputrec.h"
109 #include "gromacs/mdtypes/interaction_const.h"
110 #include "gromacs/mdtypes/md_enums.h"
111 #include "gromacs/mdtypes/mdatom.h"
112 #include "gromacs/mdtypes/mdrunoptions.h"
113 #include "gromacs/mdtypes/observableshistory.h"
114 #include "gromacs/mdtypes/state.h"
115 #include "gromacs/mimic/utilities.h"
116 #include "gromacs/pbcutil/mshift.h"
117 #include "gromacs/pbcutil/pbc.h"
118 #include "gromacs/pulling/pull.h"
119 #include "gromacs/swap/swapcoords.h"
120 #include "gromacs/timing/wallcycle.h"
121 #include "gromacs/timing/walltime_accounting.h"
122 #include "gromacs/topology/atoms.h"
123 #include "gromacs/topology/idef.h"
124 #include "gromacs/topology/mtop_util.h"
125 #include "gromacs/topology/topology.h"
126 #include "gromacs/trajectory/trajectoryframe.h"
127 #include "gromacs/utility/basedefinitions.h"
128 #include "gromacs/utility/cstringutil.h"
129 #include "gromacs/utility/fatalerror.h"
130 #include "gromacs/utility/logger.h"
131 #include "gromacs/utility/real.h"
132 #include "gromacs/utility/smalloc.h"
133
134 #include "legacysimulator.h"
135 #include "replicaexchange.h"
136 #include "shellfc.h"
137
138 using gmx::SimulationSignaller;
139
140 /*! \brief Copy the state from \p rerunFrame to \p globalState and, if requested, construct vsites
141  *
142  * \param[in]     rerunFrame      The trajectory frame to compute energy/forces for
143  * \param[in,out] globalState     The global state container
144  * \param[in]     constructVsites When true, vsite coordinates are constructed
145  * \param[in]     vsite           Vsite setup, can be nullptr when \p constructVsites = false
146  * \param[in]     idef            Topology parameters, used for constructing vsites
147  * \param[in]     timeStep        Time step, used for constructing vsites
148  * \param[in]     forceRec        Force record, used for constructing vsites
149  * \param[in,out] graph           The molecular graph, used for constructing vsites when != nullptr
150  */
151 static void prepareRerunState(const t_trxframe&             rerunFrame,
152                               t_state*                      globalState,
153                               bool                          constructVsites,
154                               const gmx_vsite_t*            vsite,
155                               const InteractionDefinitions& idef,
156                               double                        timeStep,
157                               const t_forcerec&             forceRec,
158                               t_graph*                      graph)
159 {
160     auto x      = makeArrayRef(globalState->x);
161     auto rerunX = arrayRefFromArray(reinterpret_cast<gmx::RVec*>(rerunFrame.x), globalState->natoms);
162     std::copy(rerunX.begin(), rerunX.end(), x.begin());
163     copy_mat(rerunFrame.box, globalState->box);
164
165     if (constructVsites)
166     {
167         GMX_ASSERT(vsite, "Need valid vsite for constructing vsites");
168
169         if (graph)
170         {
171             /* Following is necessary because the graph may get out of sync
172              * with the coordinates if we only have every N'th coordinate set
173              */
174             mk_mshift(nullptr, graph, forceRec.pbcType, globalState->box, globalState->x.rvec_array());
175             shift_self(graph, globalState->box, as_rvec_array(globalState->x.data()));
176         }
177         construct_vsites(vsite, globalState->x.rvec_array(), timeStep, globalState->v.rvec_array(),
178                          idef.iparams, idef.il, forceRec.pbcType, forceRec.bMolPBC, nullptr,
179                          globalState->box);
180         if (graph)
181         {
182             unshift_self(graph, globalState->box, globalState->x.rvec_array());
183         }
184     }
185 }
186
187 void gmx::LegacySimulator::do_rerun()
188 {
189     // TODO Historically, the EM and MD "integrators" used different
190     // names for the t_inputrec *parameter, but these must have the
191     // same name, now that it's a member of a struct. We use this ir
192     // alias to avoid a large ripple of nearly useless changes.
193     // t_inputrec is being replaced by IMdpOptionsProvider, so this
194     // will go away eventually.
195     t_inputrec*                 ir = inputrec;
196     int64_t                     step, step_rel;
197     double                      t, lam0[efptNR];
198     bool                        isLastStep               = false;
199     bool                        doFreeEnergyPerturbation = false;
200     unsigned int                force_flags;
201     tensor                      force_vir, shake_vir, total_vir, pres;
202     t_trxstatus*                status = nullptr;
203     rvec                        mu_tot;
204     t_trxframe                  rerun_fr;
205     gmx_localtop_t              top(top_global->ffparams);
206     PaddedHostVector<gmx::RVec> f{};
207     gmx_global_stat_t           gstat;
208     t_graph*                    graph = nullptr;
209     gmx_shellfc_t*              shellfc;
210
211     double cycles;
212
213     /* Domain decomposition could incorrectly miss a bonded
214        interaction, but checking for that requires a global
215        communication stage, which does not otherwise happen in DD
216        code. So we do that alongside the first global energy reduction
217        after a new DD is made. These variables handle whether the
218        check happens, and the result it returns. */
219     bool shouldCheckNumberOfBondedInteractions = false;
220     int  totalNumberOfBondedInteractions       = -1;
221
222     SimulationSignals signals;
223     // Most global communnication stages don't propagate mdrun
224     // signals, and will use this object to achieve that.
225     SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false);
226
227     GMX_LOG(mdlog.info)
228             .asParagraph()
229             .appendText(
230                     "Note that it is planned that the command gmx mdrun -rerun will "
231                     "be available in a different form in a future version of GROMACS, "
232                     "e.g. gmx rerun -f.");
233
234     if (ir->efep != efepNO
235         && (mdAtoms->mdatoms()->nMassPerturbed > 0 || (constr && constr->havePerturbedConstraints())))
236     {
237         gmx_fatal(FARGS,
238                   "Perturbed masses or constraints are not supported by rerun. "
239                   "Either make a .tpr without mass and constraint perturbation, "
240                   "or use GROMACS 2018.4, 2018.5 or later 2018 version.");
241     }
242     if (ir->bExpanded)
243     {
244         gmx_fatal(FARGS, "Expanded ensemble not supported by rerun.");
245     }
246     if (ir->bSimTemp)
247     {
248         gmx_fatal(FARGS, "Simulated tempering not supported by rerun.");
249     }
250     if (ir->bDoAwh)
251     {
252         gmx_fatal(FARGS, "AWH not supported by rerun.");
253     }
254     if (replExParams.exchangeInterval > 0)
255     {
256         gmx_fatal(FARGS, "Replica exchange not supported by rerun.");
257     }
258     if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
259     {
260         gmx_fatal(FARGS, "Essential dynamics not supported by rerun.");
261     }
262     if (ir->bIMD)
263     {
264         gmx_fatal(FARGS, "Interactive MD not supported by rerun.");
265     }
266     if (isMultiSim(ms))
267     {
268         gmx_fatal(FARGS, "Multiple simulations not supported by rerun.");
269     }
270     if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc,
271                     [](int i) { return i != eannNO; }))
272     {
273         gmx_fatal(FARGS, "Simulated annealing not supported by rerun.");
274     }
275
276     /* Rerun can't work if an output file name is the same as the input file name.
277      * If this is the case, the user will get an error telling them what the issue is.
278      */
279     if (strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-o", nfile, fnm)) == 0
280         || strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-x", nfile, fnm)) == 0)
281     {
282         gmx_fatal(FARGS,
283                   "When using mdrun -rerun, the name of the input trajectory file "
284                   "%s cannot be identical to the name of an output file (whether "
285                   "given explicitly with -o or -x, or by default)",
286                   opt2fn("-rerun", nfile, fnm));
287     }
288
289     /* Settings for rerun */
290     ir->nstlist              = 1;
291     ir->nstcalcenergy        = 1;
292     int        nstglobalcomm = 1;
293     const bool bNS           = true;
294
295     ir->nstxout_compressed   = 0;
296     SimulationGroups* groups = &top_global->groups;
297     if (ir->eI == eiMimic)
298     {
299         top_global->intermolecularExclusionGroup = genQmmmIndices(*top_global);
300     }
301
302     initialize_lambdas(fplog, *ir, MASTER(cr), &state_global->fep_state, state_global->lambda, lam0);
303     const bool        simulationsShareState = false;
304     gmx_mdoutf*       outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider,
305                                    mdModulesNotifier, ir, top_global, oenv, wcycle,
306                                    StartingBehavior::NewSimulation, simulationsShareState, ms);
307     gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, ir, pull_work,
308                                    mdoutf_get_fp_dhdl(outf), true, StartingBehavior::NewSimulation,
309                                    mdModulesNotifier);
310
311     gstat = global_stat_init(ir);
312
313     /* Check for polarizable models and flexible constraints */
314     shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0,
315                                  ir->nstcalcenergy, DOMAINDECOMP(cr));
316
317     {
318         double io = compute_io(ir, top_global->natoms, *groups, energyOutput.numEnergyTerms(), 1);
319         if ((io > 2000) && MASTER(cr))
320         {
321             fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
322         }
323     }
324
325     // Local state only becomes valid now.
326     std::unique_ptr<t_state> stateInstance;
327     t_state*                 state;
328
329     if (DOMAINDECOMP(cr))
330     {
331         stateInstance = std::make_unique<t_state>();
332         state         = stateInstance.get();
333         dd_init_local_state(cr->dd, state_global, state);
334
335         /* Distribute the charge groups over the nodes from the master node */
336         dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, *top_global, ir,
337                             imdSession, pull_work, state, &f, mdAtoms, &top, fr, vsite, constr,
338                             nrnb, nullptr, FALSE);
339         shouldCheckNumberOfBondedInteractions = true;
340     }
341     else
342     {
343         state_change_natoms(state_global, state_global->natoms);
344         /* We need to allocate one element extra, since we might use
345          * (unaligned) 4-wide SIMD loads to access rvec entries.
346          */
347         f.resizeWithPadding(state_global->natoms);
348         /* Copy the pointer to the global state */
349         state = state_global;
350
351         mdAlgorithmsSetupAtomData(cr, ir, *top_global, &top, fr, &graph, mdAtoms, constr, vsite, shellfc);
352     }
353
354     auto mdatoms = mdAtoms->mdatoms();
355
356     // NOTE: The global state is no longer used at this point.
357     // But state_global is still used as temporary storage space for writing
358     // the global state to file and potentially for replica exchange.
359     // (Global topology should persist.)
360
361     update_mdatoms(mdatoms, state->lambda[efptMASS]);
362
363     if (ir->efep != efepNO && ir->fepvals->nstdhdl != 0)
364     {
365         doFreeEnergyPerturbation = true;
366     }
367
368     {
369         int cglo_flags =
370                 (CGLO_GSTAT
371                  | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0));
372         bool   bSumEkinhOld = false;
373         t_vcm* vcm          = nullptr;
374         compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x),
375                         makeConstArrayRef(state->v), state->box, state->lambda[efptVDW], mdatoms, nrnb,
376                         vcm, nullptr, enerd, force_vir, shake_vir, total_vir, pres, constr, &nullSignaller,
377                         state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags);
378     }
379     checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, &top,
380                                     makeConstArrayRef(state->x), state->box,
381                                     &shouldCheckNumberOfBondedInteractions);
382
383     if (MASTER(cr))
384     {
385         fprintf(stderr,
386                 "starting md rerun '%s', reading coordinates from"
387                 " input trajectory '%s'\n\n",
388                 *(top_global->name), opt2fn("-rerun", nfile, fnm));
389         if (mdrunOptions.verbose)
390         {
391             fprintf(stderr,
392                     "Calculated time to finish depends on nsteps from "
393                     "run input file,\nwhich may not correspond to the time "
394                     "needed to process input trajectory.\n\n");
395         }
396         fprintf(fplog, "\n");
397     }
398
399     walltime_accounting_start_time(walltime_accounting);
400     wallcycle_start(wcycle, ewcRUN);
401     print_start(fplog, cr, walltime_accounting, "mdrun");
402
403     /***********************************************************
404      *
405      *             Loop over MD steps
406      *
407      ************************************************************/
408
409     if (constr)
410     {
411         GMX_LOG(mdlog.info)
412                 .asParagraph()
413                 .appendText("Simulations has constraints. Rerun does not recalculate constraints.");
414     }
415
416     rerun_fr.natoms = 0;
417     if (MASTER(cr))
418     {
419         isLastStep = !read_first_frame(oenv, &status, opt2fn("-rerun", nfile, fnm), &rerun_fr, TRX_NEED_X);
420         if (rerun_fr.natoms != top_global->natoms)
421         {
422             gmx_fatal(FARGS,
423                       "Number of atoms in trajectory (%d) does not match the "
424                       "run input file (%d)\n",
425                       rerun_fr.natoms, top_global->natoms);
426         }
427
428         if (ir->pbcType != PbcType::No)
429         {
430             if (!rerun_fr.bBox)
431             {
432                 gmx_fatal(FARGS,
433                           "Rerun trajectory frame step %" PRId64
434                           " time %f "
435                           "does not contain a box, while pbc is used",
436                           rerun_fr.step, rerun_fr.time);
437             }
438             if (max_cutoff2(ir->pbcType, rerun_fr.box) < gmx::square(fr->rlist))
439             {
440                 gmx_fatal(FARGS,
441                           "Rerun trajectory frame step %" PRId64
442                           " time %f "
443                           "has too small box dimensions",
444                           rerun_fr.step, rerun_fr.time);
445             }
446         }
447     }
448
449     GMX_LOG(mdlog.info)
450             .asParagraph()
451             .appendText(
452                     "Rerun does not report kinetic energy, total energy, temperature, virial and "
453                     "pressure.");
454
455     if (PAR(cr))
456     {
457         rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
458     }
459
460     if (ir->pbcType != PbcType::No)
461     {
462         /* Set the shift vectors.
463          * Necessary here when have a static box different from the tpr box.
464          */
465         calc_shifts(rerun_fr.box, fr->shift_vec);
466     }
467
468     auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
469             compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]), false, MASTER(cr),
470             ir->nstlist, mdrunOptions.reproducible, nstglobalcomm, mdrunOptions.maximumHoursToRun,
471             ir->nstlist == 0, fplog, step, bNS, walltime_accounting);
472
473     // we don't do counter resetting in rerun - finish will always be valid
474     walltime_accounting_set_valid_finish(walltime_accounting);
475
476     const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
477
478     step     = ir->init_step;
479     step_rel = 0;
480
481     /* and stop now if we should */
482     isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
483     while (!isLastStep)
484     {
485         wallcycle_start(wcycle, ewcSTEP);
486
487         if (rerun_fr.bStep)
488         {
489             step     = rerun_fr.step;
490             step_rel = step - ir->init_step;
491         }
492         if (rerun_fr.bTime)
493         {
494             t = rerun_fr.time;
495         }
496         else
497         {
498             t = step;
499         }
500
501         if (ir->efep != efepNO && MASTER(cr))
502         {
503             setCurrentLambdasRerun(step, ir->fepvals, &rerun_fr, lam0, state_global);
504         }
505
506         if (MASTER(cr))
507         {
508             const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
509             if (constructVsites && DOMAINDECOMP(cr))
510             {
511                 gmx_fatal(FARGS,
512                           "Vsite recalculation with -rerun is not implemented with domain "
513                           "decomposition, "
514                           "use a single rank");
515             }
516             prepareRerunState(rerun_fr, state_global, constructVsites, vsite, top.idef, ir->delta_t,
517                               *fr, graph);
518         }
519
520         isLastStep = isLastStep || stopHandler->stoppingAfterCurrentStep(bNS);
521
522         if (DOMAINDECOMP(cr))
523         {
524             /* Repartition the domain decomposition */
525             const bool bMasterState = true;
526             dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global,
527                                 *top_global, ir, imdSession, pull_work, state, &f, mdAtoms, &top,
528                                 fr, vsite, constr, nrnb, wcycle, mdrunOptions.verbose);
529             shouldCheckNumberOfBondedInteractions = true;
530         }
531
532         if (MASTER(cr))
533         {
534             energyOutput.printHeader(fplog, step, t); /* can we improve the information printed here? */
535         }
536
537         if (ir->efep != efepNO)
538         {
539             update_mdatoms(mdatoms, state->lambda[efptMASS]);
540         }
541
542         force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
543                        | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 and #3400 are solved
544                        GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
545
546         if (shellfc)
547         {
548             /* Now is the time to relax the shells */
549             relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir,
550                                 imdSession, pull_work, bNS, force_flags, &top, constr, enerd, fcd,
551                                 state->natoms, state->x.arrayRefWithPadding(),
552                                 state->v.arrayRefWithPadding(), state->box, state->lambda, &state->hist,
553                                 f.arrayRefWithPadding(), force_vir, mdatoms, nrnb, wcycle, graph,
554                                 shellfc, fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler);
555         }
556         else
557         {
558             /* The coordinates (x) are shifted (to get whole molecules)
559              * in do_force.
560              * This is parallellized as well, and does communication too.
561              * Check comments in sim_util.c
562              */
563             Awh*       awh = nullptr;
564             gmx_edsam* ed  = nullptr;
565             do_force(fplog, cr, ms, ir, awh, enforcedRotation, imdSession, pull_work, step, nrnb,
566                      wcycle, &top, state->box, state->x.arrayRefWithPadding(), &state->hist,
567                      f.arrayRefWithPadding(), force_vir, mdatoms, enerd, fcd, state->lambda, graph,
568                      fr, runScheduleWork, vsite, mu_tot, t, ed, GMX_FORCE_NS | force_flags,
569                      ddBalanceRegionHandler);
570         }
571
572         /* Now we have the energies and forces corresponding to the
573          * coordinates at time t.
574          */
575         {
576             const bool isCheckpointingStep = false;
577             const bool doRerun             = true;
578             const bool bSumEkinhOld        = false;
579             do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state,
580                                      state_global, observablesHistory, top_global, fr, outf,
581                                      energyOutput, ekind, f, isCheckpointingStep, doRerun,
582                                      isLastStep, mdrunOptions.writeConfout, bSumEkinhOld);
583         }
584
585         stopHandler->setSignal();
586
587         if (graph)
588         {
589             /* Need to unshift here */
590             unshift_self(graph, state->box, as_rvec_array(state->x.data()));
591         }
592
593         if (vsite != nullptr)
594         {
595             wallcycle_start(wcycle, ewcVSITECONSTR);
596             if (graph != nullptr)
597             {
598                 shift_self(graph, state->box, as_rvec_array(state->x.data()));
599             }
600             construct_vsites(vsite, as_rvec_array(state->x.data()), ir->delta_t,
601                              as_rvec_array(state->v.data()), top.idef.iparams, top.idef.il,
602                              fr->pbcType, fr->bMolPBC, cr, state->box);
603
604             if (graph != nullptr)
605             {
606                 unshift_self(graph, state->box, as_rvec_array(state->x.data()));
607             }
608             wallcycle_stop(wcycle, ewcVSITECONSTR);
609         }
610
611         {
612             const bool          doInterSimSignal = false;
613             const bool          doIntraSimSignal = true;
614             bool                bSumEkinhOld     = false;
615             t_vcm*              vcm              = nullptr;
616             SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
617
618             compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x),
619                             makeConstArrayRef(state->v), state->box, state->lambda[efptVDW], mdatoms,
620                             nrnb, vcm, wcycle, enerd, force_vir, shake_vir, total_vir, pres, constr,
621                             &signaller, state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld,
622                             CGLO_GSTAT | CGLO_ENERGY
623                                     | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS
624                                                                              : 0));
625             checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global,
626                                             &top, makeConstArrayRef(state->x), state->box,
627                                             &shouldCheckNumberOfBondedInteractions);
628         }
629
630         /* Note: this is OK, but there are some numerical precision issues with using the convergence of
631            the virial that should probably be addressed eventually. state->veta has better properies,
632            but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
633            generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
634
635         if (ir->efep != efepNO)
636         {
637             /* Sum up the foreign energy and dhdl terms for md and sd.
638                Currently done every step so that dhdl is correct in the .edr */
639             sum_dhdl(enerd, state->lambda, *ir->fepvals);
640         }
641
642         /* Output stuff */
643         if (MASTER(cr))
644         {
645             const bool bCalcEnerStep = true;
646             energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation, bCalcEnerStep, t,
647                                              mdatoms->tmass, enerd, state, ir->fepvals,
648                                              ir->expandedvals, state->box, shake_vir, force_vir,
649                                              total_vir, pres, ekind, mu_tot, constr);
650
651             const bool do_ene = true;
652             const bool do_log = true;
653             Awh*       awh    = nullptr;
654             const bool do_dr  = ir->nstdisreout != 0;
655             const bool do_or  = ir->nstorireout != 0;
656
657             energyOutput.printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
658             energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or,
659                                                do_log ? fplog : nullptr, step, t, fcd, awh);
660
661             if (do_per_step(step, ir->nstlog))
662             {
663                 if (fflush(fplog) != 0)
664                 {
665                     gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
666                 }
667             }
668         }
669
670         /* Print the remaining wall clock time for the run */
671         if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
672         {
673             if (shellfc)
674             {
675                 fprintf(stderr, "\n");
676             }
677             print_time(stderr, walltime_accounting, step, ir, cr);
678         }
679
680         /* Ion/water position swapping.
681          * Not done in last step since trajectory writing happens before this call
682          * in the MD loop and exchanges would be lost anyway. */
683         if ((ir->eSwapCoords != eswapNO) && (step > 0) && !isLastStep && do_per_step(step, ir->swap->nstswap))
684         {
685             const bool doRerun = true;
686             do_swapcoords(cr, step, t, ir, swap, wcycle, rerun_fr.x, rerun_fr.box,
687                           MASTER(cr) && mdrunOptions.verbose, doRerun);
688         }
689
690         if (MASTER(cr))
691         {
692             /* read next frame from input trajectory */
693             isLastStep = !read_next_frame(oenv, status, &rerun_fr);
694         }
695
696         if (PAR(cr))
697         {
698             rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
699         }
700
701         cycles = wallcycle_stop(wcycle, ewcSTEP);
702         if (DOMAINDECOMP(cr) && wcycle)
703         {
704             dd_cycles_add(cr->dd, cycles, ddCyclStep);
705         }
706
707         if (!rerun_fr.bStep)
708         {
709             /* increase the MD step number */
710             step++;
711             step_rel++;
712         }
713     }
714     /* End of main MD loop */
715
716     /* Closing TNG files can include compressing data. Therefore it is good to do that
717      * before stopping the time measurements. */
718     mdoutf_tng_close(outf);
719
720     /* Stop measuring walltime */
721     walltime_accounting_end_time(walltime_accounting);
722
723     if (MASTER(cr))
724     {
725         close_trx(status);
726     }
727
728     if (!thisRankHasDuty(cr, DUTY_PME))
729     {
730         /* Tell the PME only node to finish */
731         gmx_pme_send_finish(cr);
732     }
733
734     done_mdoutf(outf);
735
736     done_shellfc(fplog, shellfc, step_rel);
737
738     walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
739 }