Simplify and fix how lambda values are set
[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/applied_forces/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/listed_forces.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/freeenergyparameters.h"
84 #include "gromacs/mdlib/md_support.h"
85 #include "gromacs/mdlib/mdatoms.h"
86 #include "gromacs/mdlib/mdoutf.h"
87 #include "gromacs/mdlib/membed.h"
88 #include "gromacs/mdlib/resethandler.h"
89 #include "gromacs/mdlib/sighandler.h"
90 #include "gromacs/mdlib/simulationsignal.h"
91 #include "gromacs/mdlib/stat.h"
92 #include "gromacs/mdlib/stophandler.h"
93 #include "gromacs/mdlib/tgroup.h"
94 #include "gromacs/mdlib/trajectory_writing.h"
95 #include "gromacs/mdlib/update.h"
96 #include "gromacs/mdlib/vcm.h"
97 #include "gromacs/mdlib/vsite.h"
98 #include "gromacs/mdrunutility/handlerestart.h"
99 #include "gromacs/mdrunutility/multisim.h"
100 #include "gromacs/mdrunutility/printtime.h"
101 #include "gromacs/mdtypes/awh_history.h"
102 #include "gromacs/mdtypes/awh_params.h"
103 #include "gromacs/mdtypes/commrec.h"
104 #include "gromacs/mdtypes/df_history.h"
105 #include "gromacs/mdtypes/energyhistory.h"
106 #include "gromacs/mdtypes/forcebuffers.h"
107 #include "gromacs/mdtypes/forcerec.h"
108 #include "gromacs/mdtypes/group.h"
109 #include "gromacs/mdtypes/inputrec.h"
110 #include "gromacs/mdtypes/interaction_const.h"
111 #include "gromacs/mdtypes/md_enums.h"
112 #include "gromacs/mdtypes/mdatom.h"
113 #include "gromacs/mdtypes/mdrunoptions.h"
114 #include "gromacs/mdtypes/observableshistory.h"
115 #include "gromacs/mdtypes/state.h"
116 #include "gromacs/mimic/utilities.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 using gmx::VirtualSitesHandler;
140
141 /*! \brief Copy the state from \p rerunFrame to \p globalState and, if requested, construct vsites
142  *
143  * \param[in]     rerunFrame      The trajectory frame to compute energy/forces for
144  * \param[in,out] globalState     The global state container
145  * \param[in]     constructVsites When true, vsite coordinates are constructed
146  * \param[in]     vsite           Vsite setup, can be nullptr when \p constructVsites = false
147  * \param[in]     timeStep        Time step, used for constructing vsites
148  */
149 static void prepareRerunState(const t_trxframe&          rerunFrame,
150                               t_state*                   globalState,
151                               bool                       constructVsites,
152                               const VirtualSitesHandler* vsite,
153                               double                     timeStep)
154 {
155     auto x      = makeArrayRef(globalState->x);
156     auto rerunX = arrayRefFromArray(reinterpret_cast<gmx::RVec*>(rerunFrame.x), globalState->natoms);
157     std::copy(rerunX.begin(), rerunX.end(), x.begin());
158     copy_mat(rerunFrame.box, globalState->box);
159
160     if (constructVsites)
161     {
162         GMX_ASSERT(vsite, "Need valid vsite for constructing vsites");
163
164         vsite->construct(globalState->x, timeStep, globalState->v, globalState->box);
165     }
166 }
167
168 void gmx::LegacySimulator::do_rerun()
169 {
170     // TODO Historically, the EM and MD "integrators" used different
171     // names for the t_inputrec *parameter, but these must have the
172     // same name, now that it's a member of a struct. We use this ir
173     // alias to avoid a large ripple of nearly useless changes.
174     // t_inputrec is being replaced by IMdpOptionsProvider, so this
175     // will go away eventually.
176     t_inputrec*       ir = inputrec;
177     int64_t           step, step_rel;
178     double            t;
179     bool              isLastStep               = false;
180     bool              doFreeEnergyPerturbation = false;
181     unsigned int      force_flags;
182     tensor            force_vir, shake_vir, total_vir, pres;
183     t_trxstatus*      status = nullptr;
184     rvec              mu_tot;
185     t_trxframe        rerun_fr;
186     gmx_localtop_t    top(top_global->ffparams);
187     ForceBuffers      f;
188     gmx_global_stat_t gstat;
189     gmx_shellfc_t*    shellfc;
190
191     double cycles;
192
193     /* Domain decomposition could incorrectly miss a bonded
194        interaction, but checking for that requires a global
195        communication stage, which does not otherwise happen in DD
196        code. So we do that alongside the first global energy reduction
197        after a new DD is made. These variables handle whether the
198        check happens, and the result it returns. */
199     bool shouldCheckNumberOfBondedInteractions = false;
200     int  totalNumberOfBondedInteractions       = -1;
201
202     SimulationSignals signals;
203     // Most global communnication stages don't propagate mdrun
204     // signals, and will use this object to achieve that.
205     SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false);
206
207     GMX_LOG(mdlog.info)
208             .asParagraph()
209             .appendText(
210                     "Note that it is planned that the command gmx mdrun -rerun will "
211                     "be available in a different form in a future version of GROMACS, "
212                     "e.g. gmx rerun -f.");
213
214     if (ir->efep != efepNO
215         && (mdAtoms->mdatoms()->nMassPerturbed > 0 || (constr && constr->havePerturbedConstraints())))
216     {
217         gmx_fatal(FARGS,
218                   "Perturbed masses or constraints are not supported by rerun. "
219                   "Either make a .tpr without mass and constraint perturbation, "
220                   "or use GROMACS 2018.4, 2018.5 or later 2018 version.");
221     }
222     if (ir->bExpanded)
223     {
224         gmx_fatal(FARGS, "Expanded ensemble not supported by rerun.");
225     }
226     if (ir->bSimTemp)
227     {
228         gmx_fatal(FARGS, "Simulated tempering not supported by rerun.");
229     }
230     if (ir->bDoAwh)
231     {
232         gmx_fatal(FARGS, "AWH not supported by rerun.");
233     }
234     if (replExParams.exchangeInterval > 0)
235     {
236         gmx_fatal(FARGS, "Replica exchange not supported by rerun.");
237     }
238     if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
239     {
240         gmx_fatal(FARGS, "Essential dynamics not supported by rerun.");
241     }
242     if (ir->bIMD)
243     {
244         gmx_fatal(FARGS, "Interactive MD not supported by rerun.");
245     }
246     if (isMultiSim(ms))
247     {
248         gmx_fatal(FARGS, "Multiple simulations not supported by rerun.");
249     }
250     if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc,
251                     [](int i) { return i != eannNO; }))
252     {
253         gmx_fatal(FARGS, "Simulated annealing not supported by rerun.");
254     }
255
256     /* Rerun can't work if an output file name is the same as the input file name.
257      * If this is the case, the user will get an error telling them what the issue is.
258      */
259     if (strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-o", nfile, fnm)) == 0
260         || strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-x", nfile, fnm)) == 0)
261     {
262         gmx_fatal(FARGS,
263                   "When using mdrun -rerun, the name of the input trajectory file "
264                   "%s cannot be identical to the name of an output file (whether "
265                   "given explicitly with -o or -x, or by default)",
266                   opt2fn("-rerun", nfile, fnm));
267     }
268
269     /* Settings for rerun */
270     ir->nstlist              = 1;
271     ir->nstcalcenergy        = 1;
272     int        nstglobalcomm = 1;
273     const bool bNS           = true;
274
275     ir->nstxout_compressed         = 0;
276     const SimulationGroups* groups = &top_global->groups;
277     if (ir->eI == eiMimic)
278     {
279         auto nonConstGlobalTopology                          = const_cast<gmx_mtop_t*>(top_global);
280         nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(*top_global);
281     }
282     int*                fep_state = MASTER(cr) ? &state_global->fep_state : nullptr;
283     gmx::ArrayRef<real> lambda    = MASTER(cr) ? state_global->lambda : gmx::ArrayRef<real>();
284     initialize_lambdas(fplog, *ir, MASTER(cr), fep_state, lambda);
285     const bool        simulationsShareState = false;
286     gmx_mdoutf*       outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider,
287                                    mdModulesNotifier, ir, top_global, oenv, wcycle,
288                                    StartingBehavior::NewSimulation, simulationsShareState, ms);
289     gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, ir, pull_work,
290                                    mdoutf_get_fp_dhdl(outf), true, StartingBehavior::NewSimulation,
291                                    mdModulesNotifier);
292
293     gstat = global_stat_init(ir);
294
295     /* Check for polarizable models and flexible constraints */
296     shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0,
297                                  ir->nstcalcenergy, DOMAINDECOMP(cr));
298
299     {
300         double io = compute_io(ir, top_global->natoms, *groups, energyOutput.numEnergyTerms(), 1);
301         if ((io > 2000) && MASTER(cr))
302         {
303             fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
304         }
305     }
306
307     // Local state only becomes valid now.
308     std::unique_ptr<t_state> stateInstance;
309     t_state*                 state;
310
311     if (DOMAINDECOMP(cr))
312     {
313         stateInstance = std::make_unique<t_state>();
314         state         = stateInstance.get();
315         dd_init_local_state(cr->dd, state_global, state);
316
317         /* Distribute the charge groups over the nodes from the master node */
318         dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, *top_global, ir,
319                             imdSession, pull_work, state, &f, mdAtoms, &top, fr, vsite, constr,
320                             nrnb, nullptr, FALSE);
321         shouldCheckNumberOfBondedInteractions = true;
322     }
323     else
324     {
325         state_change_natoms(state_global, state_global->natoms);
326         /* Copy the pointer to the global state */
327         state = state_global;
328
329         mdAlgorithmsSetupAtomData(cr, ir, *top_global, &top, fr, &f, mdAtoms, constr, vsite, shellfc);
330     }
331
332     auto mdatoms = mdAtoms->mdatoms();
333
334     // NOTE: The global state is no longer used at this point.
335     // But state_global is still used as temporary storage space for writing
336     // the global state to file and potentially for replica exchange.
337     // (Global topology should persist.)
338
339     update_mdatoms(mdatoms, state->lambda[efptMASS]);
340
341     if (ir->efep != efepNO && ir->fepvals->nstdhdl != 0)
342     {
343         doFreeEnergyPerturbation = true;
344     }
345
346     {
347         int cglo_flags =
348                 (CGLO_GSTAT
349                  | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0));
350         bool   bSumEkinhOld = false;
351         t_vcm* vcm          = nullptr;
352         compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x),
353                         makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, nullptr, enerd,
354                         force_vir, shake_vir, total_vir, pres, constr, &nullSignaller, state->box,
355                         &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags);
356     }
357     checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, &top,
358                                     makeConstArrayRef(state->x), state->box,
359                                     &shouldCheckNumberOfBondedInteractions);
360
361     if (MASTER(cr))
362     {
363         fprintf(stderr,
364                 "starting md rerun '%s', reading coordinates from"
365                 " input trajectory '%s'\n\n",
366                 *(top_global->name), opt2fn("-rerun", nfile, fnm));
367         if (mdrunOptions.verbose)
368         {
369             fprintf(stderr,
370                     "Calculated time to finish depends on nsteps from "
371                     "run input file,\nwhich may not correspond to the time "
372                     "needed to process input trajectory.\n\n");
373         }
374         fprintf(fplog, "\n");
375     }
376
377     walltime_accounting_start_time(walltime_accounting);
378     wallcycle_start(wcycle, ewcRUN);
379     print_start(fplog, cr, walltime_accounting, "mdrun");
380
381     /***********************************************************
382      *
383      *             Loop over MD steps
384      *
385      ************************************************************/
386
387     if (constr)
388     {
389         GMX_LOG(mdlog.info)
390                 .asParagraph()
391                 .appendText("Simulations has constraints. Rerun does not recalculate constraints.");
392     }
393
394     rerun_fr.natoms = 0;
395     if (MASTER(cr))
396     {
397         isLastStep = !read_first_frame(oenv, &status, opt2fn("-rerun", nfile, fnm), &rerun_fr, TRX_NEED_X);
398         if (rerun_fr.natoms != top_global->natoms)
399         {
400             gmx_fatal(FARGS,
401                       "Number of atoms in trajectory (%d) does not match the "
402                       "run input file (%d)\n",
403                       rerun_fr.natoms, top_global->natoms);
404         }
405
406         if (ir->pbcType != PbcType::No)
407         {
408             if (!rerun_fr.bBox)
409             {
410                 gmx_fatal(FARGS,
411                           "Rerun trajectory frame step %" PRId64
412                           " time %f "
413                           "does not contain a box, while pbc is used",
414                           rerun_fr.step, rerun_fr.time);
415             }
416             if (max_cutoff2(ir->pbcType, rerun_fr.box) < gmx::square(fr->rlist))
417             {
418                 gmx_fatal(FARGS,
419                           "Rerun trajectory frame step %" PRId64
420                           " time %f "
421                           "has too small box dimensions",
422                           rerun_fr.step, rerun_fr.time);
423             }
424         }
425     }
426
427     GMX_LOG(mdlog.info)
428             .asParagraph()
429             .appendText(
430                     "Rerun does not report kinetic energy, total energy, temperature, virial and "
431                     "pressure.");
432
433     if (PAR(cr))
434     {
435         rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
436     }
437
438     if (ir->pbcType != PbcType::No)
439     {
440         /* Set the shift vectors.
441          * Necessary here when have a static box different from the tpr box.
442          */
443         calc_shifts(rerun_fr.box, fr->shift_vec);
444     }
445
446     step     = ir->init_step;
447     step_rel = 0;
448
449     auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
450             compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]), false, MASTER(cr),
451             ir->nstlist, mdrunOptions.reproducible, nstglobalcomm, mdrunOptions.maximumHoursToRun,
452             ir->nstlist == 0, fplog, step, bNS, walltime_accounting);
453
454     // we don't do counter resetting in rerun - finish will always be valid
455     walltime_accounting_set_valid_finish(walltime_accounting);
456
457     const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
458
459     /* and stop now if we should */
460     isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
461     while (!isLastStep)
462     {
463         wallcycle_start(wcycle, ewcSTEP);
464
465         if (rerun_fr.bStep)
466         {
467             step     = rerun_fr.step;
468             step_rel = step - ir->init_step;
469         }
470         if (rerun_fr.bTime)
471         {
472             t = rerun_fr.time;
473         }
474         else
475         {
476             t = step;
477         }
478
479         if (ir->efep != efepNO && MASTER(cr))
480         {
481             if (rerun_fr.bLambda)
482             {
483                 ir->fepvals->init_lambda = rerun_fr.lambda;
484             }
485             else
486             {
487                 if (rerun_fr.bFepState)
488                 {
489                     state->fep_state = rerun_fr.fep_state;
490                 }
491             }
492
493             state_global->lambda = currentLambdas(step, *(ir->fepvals), state->fep_state);
494         }
495
496         if (MASTER(cr))
497         {
498             const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
499             if (constructVsites && DOMAINDECOMP(cr))
500             {
501                 gmx_fatal(FARGS,
502                           "Vsite recalculation with -rerun is not implemented with domain "
503                           "decomposition, "
504                           "use a single rank");
505             }
506             prepareRerunState(rerun_fr, state_global, constructVsites, vsite, ir->delta_t);
507         }
508
509         isLastStep = isLastStep || stopHandler->stoppingAfterCurrentStep(bNS);
510
511         if (DOMAINDECOMP(cr))
512         {
513             /* Repartition the domain decomposition */
514             const bool bMasterState = true;
515             dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global,
516                                 *top_global, ir, imdSession, pull_work, state, &f, mdAtoms, &top,
517                                 fr, vsite, constr, nrnb, wcycle, mdrunOptions.verbose);
518             shouldCheckNumberOfBondedInteractions = true;
519         }
520
521         if (MASTER(cr))
522         {
523             EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */
524         }
525
526         if (ir->efep != efepNO)
527         {
528             update_mdatoms(mdatoms, state->lambda[efptMASS]);
529         }
530
531         force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
532                        | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 and #3400 are solved
533                        GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
534
535         if (shellfc)
536         {
537             /* Now is the time to relax the shells */
538             relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir,
539                                 imdSession, pull_work, bNS, force_flags, &top, constr, enerd,
540                                 state->natoms, state->x.arrayRefWithPadding(),
541                                 state->v.arrayRefWithPadding(), state->box, state->lambda,
542                                 &state->hist, &f.view(), force_vir, mdatoms, nrnb, wcycle, shellfc,
543                                 fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler);
544         }
545         else
546         {
547             /* The coordinates (x) are shifted (to get whole molecules)
548              * in do_force.
549              * This is parallellized as well, and does communication too.
550              * Check comments in sim_util.c
551              */
552             Awh*       awh = nullptr;
553             gmx_edsam* ed  = nullptr;
554             do_force(fplog, cr, ms, ir, awh, enforcedRotation, imdSession, pull_work, step, nrnb,
555                      wcycle, &top, state->box, state->x.arrayRefWithPadding(), &state->hist,
556                      &f.view(), force_vir, mdatoms, enerd, state->lambda, fr, runScheduleWork,
557                      vsite, mu_tot, t, ed, GMX_FORCE_NS | force_flags, ddBalanceRegionHandler);
558         }
559
560         /* Now we have the energies and forces corresponding to the
561          * coordinates at time t.
562          */
563         {
564             const bool isCheckpointingStep = false;
565             const bool doRerun             = true;
566             const bool bSumEkinhOld        = false;
567             do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state,
568                                      state_global, observablesHistory, top_global, fr, outf,
569                                      energyOutput, ekind, f.view().force(), isCheckpointingStep,
570                                      doRerun, isLastStep, mdrunOptions.writeConfout, bSumEkinhOld);
571         }
572
573         stopHandler->setSignal();
574
575         if (vsite != nullptr)
576         {
577             wallcycle_start(wcycle, ewcVSITECONSTR);
578             vsite->construct(state->x, ir->delta_t, state->v, state->box);
579             wallcycle_stop(wcycle, ewcVSITECONSTR);
580         }
581
582         {
583             const bool          doInterSimSignal = false;
584             const bool          doIntraSimSignal = true;
585             bool                bSumEkinhOld     = false;
586             t_vcm*              vcm              = nullptr;
587             SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
588
589             compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x),
590                             makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle,
591                             enerd, force_vir, shake_vir, total_vir, pres, constr, &signaller,
592                             state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld,
593                             CGLO_GSTAT | CGLO_ENERGY
594                                     | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS
595                                                                              : 0));
596             checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global,
597                                             &top, makeConstArrayRef(state->x), state->box,
598                                             &shouldCheckNumberOfBondedInteractions);
599         }
600
601         /* Note: this is OK, but there are some numerical precision issues with using the convergence of
602            the virial that should probably be addressed eventually. state->veta has better properies,
603            but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
604            generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
605
606         /* Output stuff */
607         if (MASTER(cr))
608         {
609             const bool bCalcEnerStep = true;
610             energyOutput.addDataAtEnergyStep(
611                     doFreeEnergyPerturbation, bCalcEnerStep, t, mdatoms->tmass, enerd, ir->fepvals,
612                     ir->expandedvals, state->box,
613                     PTCouplingArrays({ state->boxv, state->nosehoover_xi, state->nosehoover_vxi,
614                                        state->nhpres_xi, state->nhpres_vxi }),
615                     state->fep_state, shake_vir, force_vir, total_vir, pres, ekind, mu_tot, constr);
616
617             const bool do_ene = true;
618             const bool do_log = true;
619             Awh*       awh    = nullptr;
620             const bool do_dr  = ir->nstdisreout != 0;
621             const bool do_or  = ir->nstorireout != 0;
622
623             EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
624             energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or,
625                                                do_log ? fplog : nullptr, step, t, fr->fcdata.get(), awh);
626
627             if (do_per_step(step, ir->nstlog))
628             {
629                 if (fflush(fplog) != 0)
630                 {
631                     gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
632                 }
633             }
634         }
635
636         /* Print the remaining wall clock time for the run */
637         if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
638         {
639             if (shellfc)
640             {
641                 fprintf(stderr, "\n");
642             }
643             print_time(stderr, walltime_accounting, step, ir, cr);
644         }
645
646         /* Ion/water position swapping.
647          * Not done in last step since trajectory writing happens before this call
648          * in the MD loop and exchanges would be lost anyway. */
649         if ((ir->eSwapCoords != eswapNO) && (step > 0) && !isLastStep && do_per_step(step, ir->swap->nstswap))
650         {
651             const bool doRerun = true;
652             do_swapcoords(cr, step, t, ir, swap, wcycle, rerun_fr.x, rerun_fr.box,
653                           MASTER(cr) && mdrunOptions.verbose, doRerun);
654         }
655
656         if (MASTER(cr))
657         {
658             /* read next frame from input trajectory */
659             isLastStep = !read_next_frame(oenv, status, &rerun_fr);
660         }
661
662         if (PAR(cr))
663         {
664             rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
665         }
666
667         cycles = wallcycle_stop(wcycle, ewcSTEP);
668         if (DOMAINDECOMP(cr) && wcycle)
669         {
670             dd_cycles_add(cr->dd, cycles, ddCyclStep);
671         }
672
673         if (!rerun_fr.bStep)
674         {
675             /* increase the MD step number */
676             step++;
677             step_rel++;
678         }
679     }
680     /* End of main MD loop */
681
682     /* Closing TNG files can include compressing data. Therefore it is good to do that
683      * before stopping the time measurements. */
684     mdoutf_tng_close(outf);
685
686     /* Stop measuring walltime */
687     walltime_accounting_end_time(walltime_accounting);
688
689     if (MASTER(cr))
690     {
691         close_trx(status);
692     }
693
694     if (!thisRankHasDuty(cr, DUTY_PME))
695     {
696         /* Tell the PME only node to finish */
697         gmx_pme_send_finish(cr);
698     }
699
700     done_mdoutf(outf);
701
702     done_shellfc(fplog, shellfc, step_rel);
703
704     walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
705 }