Move responsibility for checking bondeds in reverse topology
[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,2021, 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/simulation_workload.h"
116 #include "gromacs/mdtypes/state.h"
117 #include "gromacs/mimic/utilities.h"
118 #include "gromacs/pbcutil/pbc.h"
119 #include "gromacs/pulling/pull.h"
120 #include "gromacs/swap/swapcoords.h"
121 #include "gromacs/timing/wallcycle.h"
122 #include "gromacs/timing/walltime_accounting.h"
123 #include "gromacs/topology/atoms.h"
124 #include "gromacs/topology/idef.h"
125 #include "gromacs/topology/mtop_util.h"
126 #include "gromacs/topology/topology.h"
127 #include "gromacs/trajectory/trajectoryframe.h"
128 #include "gromacs/utility/basedefinitions.h"
129 #include "gromacs/utility/cstringutil.h"
130 #include "gromacs/utility/fatalerror.h"
131 #include "gromacs/utility/logger.h"
132 #include "gromacs/utility/real.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  */
148 static void prepareRerunState(const t_trxframe&          rerunFrame,
149                               t_state*                   globalState,
150                               bool                       constructVsites,
151                               const VirtualSitesHandler* vsite)
152 {
153     auto x      = makeArrayRef(globalState->x);
154     auto rerunX = arrayRefFromArray(reinterpret_cast<gmx::RVec*>(rerunFrame.x), globalState->natoms);
155     std::copy(rerunX.begin(), rerunX.end(), x.begin());
156     copy_mat(rerunFrame.box, globalState->box);
157
158     if (constructVsites)
159     {
160         GMX_ASSERT(vsite, "Need valid vsite for constructing vsites");
161
162         vsite->construct(globalState->x, globalState->v, globalState->box, gmx::VSiteOperation::PositionsAndVelocities);
163     }
164 }
165
166 void gmx::LegacySimulator::do_rerun()
167 {
168     // TODO Historically, the EM and MD "integrators" used different
169     // names for the t_inputrec *parameter, but these must have the
170     // same name, now that it's a member of a struct. We use this ir
171     // alias to avoid a large ripple of nearly useless changes.
172     // t_inputrec is being replaced by IMdpOptionsProvider, so this
173     // will go away eventually.
174     const t_inputrec* ir = inputrec;
175     int64_t           step, step_rel;
176     double            t;
177     bool              isLastStep               = false;
178     bool              doFreeEnergyPerturbation = false;
179     unsigned int      force_flags;
180     tensor            force_vir, shake_vir, total_vir, pres;
181     t_trxstatus*      status = nullptr;
182     rvec              mu_tot;
183     t_trxframe        rerun_fr;
184     gmx_localtop_t    top(top_global.ffparams);
185     ForceBuffers      f;
186     gmx_global_stat_t gstat;
187     gmx_shellfc_t*    shellfc;
188
189     double cycles;
190
191     SimulationSignals signals;
192     // Most global communnication stages don't propagate mdrun
193     // signals, and will use this object to achieve that.
194     SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false);
195
196     GMX_LOG(mdlog.info)
197             .asParagraph()
198             .appendText(
199                     "Note that it is planned that the command gmx mdrun -rerun will "
200                     "be available in a different form in a future version of GROMACS, "
201                     "e.g. gmx rerun -f.");
202
203     if (ir->efep != FreeEnergyPerturbationType::No
204         && (mdAtoms->mdatoms()->nMassPerturbed > 0 || (constr && constr->havePerturbedConstraints())))
205     {
206         gmx_fatal(FARGS,
207                   "Perturbed masses or constraints are not supported by rerun. "
208                   "Either make a .tpr without mass and constraint perturbation, "
209                   "or use GROMACS 2018.4, 2018.5 or later 2018 version.");
210     }
211     if (ir->bExpanded)
212     {
213         gmx_fatal(FARGS, "Expanded ensemble not supported by rerun.");
214     }
215     if (ir->bSimTemp)
216     {
217         gmx_fatal(FARGS, "Simulated tempering not supported by rerun.");
218     }
219     if (ir->bDoAwh)
220     {
221         gmx_fatal(FARGS, "AWH not supported by rerun.");
222     }
223     if (replExParams.exchangeInterval > 0)
224     {
225         gmx_fatal(FARGS, "Replica exchange not supported by rerun.");
226     }
227     if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
228     {
229         gmx_fatal(FARGS, "Essential dynamics not supported by rerun.");
230     }
231     if (ir->bIMD)
232     {
233         gmx_fatal(FARGS, "Interactive MD not supported by rerun.");
234     }
235     if (isMultiSim(ms))
236     {
237         gmx_fatal(FARGS, "Multiple simulations not supported by rerun.");
238     }
239     if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](SimulatedAnnealing i) {
240             return i != SimulatedAnnealing::No;
241         }))
242     {
243         gmx_fatal(FARGS, "Simulated annealing not supported by rerun.");
244     }
245
246     /* Rerun can't work if an output file name is the same as the input file name.
247      * If this is the case, the user will get an error telling them what the issue is.
248      */
249     if (strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-o", nfile, fnm)) == 0
250         || strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-x", nfile, fnm)) == 0)
251     {
252         gmx_fatal(FARGS,
253                   "When using mdrun -rerun, the name of the input trajectory file "
254                   "%s cannot be identical to the name of an output file (whether "
255                   "given explicitly with -o or -x, or by default)",
256                   opt2fn("-rerun", nfile, fnm));
257     }
258
259     /* Settings for rerun */
260     {
261         // TODO: Avoid changing inputrec (#3854)
262         auto* nonConstInputrec               = const_cast<t_inputrec*>(inputrec);
263         nonConstInputrec->nstlist            = 1;
264         nonConstInputrec->nstcalcenergy      = 1;
265         nonConstInputrec->nstxout_compressed = 0;
266     }
267     int        nstglobalcomm = 1;
268     const bool bNS           = true;
269
270     const SimulationGroups* groups = &top_global.groups;
271     if (ir->eI == IntegrationAlgorithm::Mimic)
272     {
273         auto nonConstGlobalTopology                          = const_cast<gmx_mtop_t*>(&top_global);
274         nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(top_global);
275     }
276     int*                fep_state = MASTER(cr) ? &state_global->fep_state : nullptr;
277     gmx::ArrayRef<real> lambda    = MASTER(cr) ? state_global->lambda : gmx::ArrayRef<real>();
278     initialize_lambdas(fplog, *ir, MASTER(cr), fep_state, lambda);
279     const bool        simulationsShareState = false;
280     gmx_mdoutf*       outf                  = init_mdoutf(fplog,
281                                    nfile,
282                                    fnm,
283                                    mdrunOptions,
284                                    cr,
285                                    outputProvider,
286                                    mdModulesNotifier,
287                                    ir,
288                                    top_global,
289                                    oenv,
290                                    wcycle,
291                                    StartingBehavior::NewSimulation,
292                                    simulationsShareState,
293                                    ms);
294     gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf),
295                                    top_global,
296                                    *ir,
297                                    pull_work,
298                                    mdoutf_get_fp_dhdl(outf),
299                                    true,
300                                    StartingBehavior::NewSimulation,
301                                    simulationsShareState,
302                                    mdModulesNotifier);
303
304     gstat = global_stat_init(ir);
305
306     /* Check for polarizable models and flexible constraints */
307     shellfc = init_shell_flexcon(fplog,
308                                  top_global,
309                                  constr ? constr->numFlexibleConstraints() : 0,
310                                  ir->nstcalcenergy,
311                                  DOMAINDECOMP(cr),
312                                  runScheduleWork->simulationWork.useGpuPme);
313
314     {
315         double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1);
316         if ((io > 2000) && MASTER(cr))
317         {
318             fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
319         }
320     }
321
322     // Local state only becomes valid now.
323     std::unique_ptr<t_state> stateInstance;
324     t_state*                 state;
325
326     if (DOMAINDECOMP(cr))
327     {
328         stateInstance = std::make_unique<t_state>();
329         state         = stateInstance.get();
330         dd_init_local_state(*cr->dd, state_global, state);
331
332         /* Distribute the charge groups over the nodes from the master node */
333         dd_partition_system(fplog,
334                             mdlog,
335                             ir->init_step,
336                             cr,
337                             TRUE,
338                             1,
339                             state_global,
340                             top_global,
341                             *ir,
342                             imdSession,
343                             pull_work,
344                             state,
345                             &f,
346                             mdAtoms,
347                             &top,
348                             fr,
349                             vsite,
350                             constr,
351                             nrnb,
352                             nullptr,
353                             FALSE);
354     }
355     else
356     {
357         state_change_natoms(state_global, state_global->natoms);
358         /* Copy the pointer to the global state */
359         state = state_global;
360
361         mdAlgorithmsSetupAtomData(cr, *ir, top_global, &top, fr, &f, mdAtoms, constr, vsite, shellfc);
362     }
363
364     auto mdatoms = mdAtoms->mdatoms();
365
366     // NOTE: The global state is no longer used at this point.
367     // But state_global is still used as temporary storage space for writing
368     // the global state to file and potentially for replica exchange.
369     // (Global topology should persist.)
370
371     update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
372
373     if (ir->efep != FreeEnergyPerturbationType::No && ir->fepvals->nstdhdl != 0)
374     {
375         doFreeEnergyPerturbation = true;
376     }
377
378     {
379         int cglo_flags = CGLO_GSTAT;
380         if (DOMAINDECOMP(cr) && shouldCheckNumberOfBondedInteractions(*cr->dd))
381         {
382             cglo_flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
383         }
384         bool   bSumEkinhOld = false;
385         t_vcm* vcm          = nullptr;
386         compute_globals(gstat,
387                         cr,
388                         ir,
389                         fr,
390                         ekind,
391                         makeConstArrayRef(state->x),
392                         makeConstArrayRef(state->v),
393                         state->box,
394                         mdatoms,
395                         nrnb,
396                         vcm,
397                         nullptr,
398                         enerd,
399                         force_vir,
400                         shake_vir,
401                         total_vir,
402                         pres,
403                         gmx::ArrayRef<real>{},
404                         &nullSignaller,
405                         state->box,
406                         &bSumEkinhOld,
407                         cglo_flags);
408         if (DOMAINDECOMP(cr))
409         {
410             checkNumberOfBondedInteractions(
411                     mdlog, cr, top_global, &top, makeConstArrayRef(state->x), state->box);
412         }
413     }
414
415     if (MASTER(cr))
416     {
417         fprintf(stderr,
418                 "starting md rerun '%s', reading coordinates from"
419                 " input trajectory '%s'\n\n",
420                 *(top_global.name),
421                 opt2fn("-rerun", nfile, fnm));
422         if (mdrunOptions.verbose)
423         {
424             fprintf(stderr,
425                     "Calculated time to finish depends on nsteps from "
426                     "run input file,\nwhich may not correspond to the time "
427                     "needed to process input trajectory.\n\n");
428         }
429         fprintf(fplog, "\n");
430     }
431
432     walltime_accounting_start_time(walltime_accounting);
433     wallcycle_start(wcycle, ewcRUN);
434     print_start(fplog, cr, walltime_accounting, "mdrun");
435
436     /***********************************************************
437      *
438      *             Loop over MD steps
439      *
440      ************************************************************/
441
442     if (constr)
443     {
444         GMX_LOG(mdlog.info)
445                 .asParagraph()
446                 .appendText("Simulations has constraints. Rerun does not recalculate constraints.");
447     }
448
449     rerun_fr.natoms = 0;
450     if (MASTER(cr))
451     {
452         isLastStep = !read_first_frame(oenv, &status, opt2fn("-rerun", nfile, fnm), &rerun_fr, TRX_NEED_X);
453         if (rerun_fr.natoms != top_global.natoms)
454         {
455             gmx_fatal(FARGS,
456                       "Number of atoms in trajectory (%d) does not match the "
457                       "run input file (%d)\n",
458                       rerun_fr.natoms,
459                       top_global.natoms);
460         }
461
462         if (ir->pbcType != PbcType::No)
463         {
464             if (!rerun_fr.bBox)
465             {
466                 gmx_fatal(FARGS,
467                           "Rerun trajectory frame step %" PRId64
468                           " time %f "
469                           "does not contain a box, while pbc is used",
470                           rerun_fr.step,
471                           rerun_fr.time);
472             }
473             if (max_cutoff2(ir->pbcType, rerun_fr.box) < gmx::square(fr->rlist))
474             {
475                 gmx_fatal(FARGS,
476                           "Rerun trajectory frame step %" PRId64
477                           " time %f "
478                           "has too small box dimensions",
479                           rerun_fr.step,
480                           rerun_fr.time);
481             }
482         }
483     }
484
485     GMX_LOG(mdlog.info)
486             .asParagraph()
487             .appendText(
488                     "Rerun does not report kinetic energy, total energy, temperature, virial and "
489                     "pressure.");
490
491     if (PAR(cr))
492     {
493         rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
494     }
495
496     if (ir->pbcType != PbcType::No)
497     {
498         /* Set the shift vectors.
499          * Necessary here when have a static box different from the tpr box.
500          */
501         calc_shifts(rerun_fr.box, fr->shift_vec);
502     }
503
504     step     = ir->init_step;
505     step_rel = 0;
506
507     auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
508             compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]),
509             false,
510             MASTER(cr),
511             ir->nstlist,
512             mdrunOptions.reproducible,
513             nstglobalcomm,
514             mdrunOptions.maximumHoursToRun,
515             ir->nstlist == 0,
516             fplog,
517             step,
518             bNS,
519             walltime_accounting);
520
521     // we don't do counter resetting in rerun - finish will always be valid
522     walltime_accounting_set_valid_finish(walltime_accounting);
523
524     const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
525
526     /* and stop now if we should */
527     isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
528     while (!isLastStep)
529     {
530         wallcycle_start(wcycle, ewcSTEP);
531
532         if (rerun_fr.bStep)
533         {
534             step     = rerun_fr.step;
535             step_rel = step - ir->init_step;
536         }
537         if (rerun_fr.bTime)
538         {
539             t = rerun_fr.time;
540         }
541         else
542         {
543             t = step;
544         }
545
546         if (ir->efep != FreeEnergyPerturbationType::No && MASTER(cr))
547         {
548             if (rerun_fr.bLambda)
549             {
550                 ir->fepvals->init_lambda = rerun_fr.lambda;
551             }
552             else
553             {
554                 if (rerun_fr.bFepState)
555                 {
556                     state->fep_state = rerun_fr.fep_state;
557                 }
558             }
559
560             state_global->lambda = currentLambdas(step, *(ir->fepvals), state->fep_state);
561         }
562
563         if (MASTER(cr))
564         {
565             const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
566             if (constructVsites && DOMAINDECOMP(cr))
567             {
568                 gmx_fatal(FARGS,
569                           "Vsite recalculation with -rerun is not implemented with domain "
570                           "decomposition, "
571                           "use a single rank");
572             }
573             prepareRerunState(rerun_fr, state_global, constructVsites, vsite);
574         }
575
576         isLastStep = isLastStep || stopHandler->stoppingAfterCurrentStep(bNS);
577
578         if (DOMAINDECOMP(cr))
579         {
580             /* Repartition the domain decomposition */
581             const bool bMasterState = true;
582             dd_partition_system(fplog,
583                                 mdlog,
584                                 step,
585                                 cr,
586                                 bMasterState,
587                                 nstglobalcomm,
588                                 state_global,
589                                 top_global,
590                                 *ir,
591                                 imdSession,
592                                 pull_work,
593                                 state,
594                                 &f,
595                                 mdAtoms,
596                                 &top,
597                                 fr,
598                                 vsite,
599                                 constr,
600                                 nrnb,
601                                 wcycle,
602                                 mdrunOptions.verbose);
603         }
604
605         if (MASTER(cr))
606         {
607             EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */
608         }
609
610         if (ir->efep != FreeEnergyPerturbationType::No)
611         {
612             update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
613         }
614
615         force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
616                        | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 and #3400 are solved
617                        GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
618
619         if (shellfc)
620         {
621             /* Now is the time to relax the shells */
622             relax_shell_flexcon(fplog,
623                                 cr,
624                                 ms,
625                                 mdrunOptions.verbose,
626                                 enforcedRotation,
627                                 step,
628                                 ir,
629                                 imdSession,
630                                 pull_work,
631                                 bNS,
632                                 force_flags,
633                                 &top,
634                                 constr,
635                                 enerd,
636                                 state->natoms,
637                                 state->x.arrayRefWithPadding(),
638                                 state->v.arrayRefWithPadding(),
639                                 state->box,
640                                 state->lambda,
641                                 &state->hist,
642                                 &f.view(),
643                                 force_vir,
644                                 *mdatoms,
645                                 nrnb,
646                                 wcycle,
647                                 shellfc,
648                                 fr,
649                                 runScheduleWork,
650                                 t,
651                                 mu_tot,
652                                 vsite,
653                                 ddBalanceRegionHandler);
654         }
655         else
656         {
657             /* The coordinates (x) are shifted (to get whole molecules)
658              * in do_force.
659              * This is parallellized as well, and does communication too.
660              * Check comments in sim_util.c
661              */
662             Awh*       awh = nullptr;
663             gmx_edsam* ed  = nullptr;
664             do_force(fplog,
665                      cr,
666                      ms,
667                      *ir,
668                      awh,
669                      enforcedRotation,
670                      imdSession,
671                      pull_work,
672                      step,
673                      nrnb,
674                      wcycle,
675                      &top,
676                      state->box,
677                      state->x.arrayRefWithPadding(),
678                      &state->hist,
679                      &f.view(),
680                      force_vir,
681                      mdatoms,
682                      enerd,
683                      state->lambda,
684                      fr,
685                      runScheduleWork,
686                      vsite,
687                      mu_tot,
688                      t,
689                      ed,
690                      GMX_FORCE_NS | force_flags,
691                      ddBalanceRegionHandler);
692         }
693
694         /* Now we have the energies and forces corresponding to the
695          * coordinates at time t.
696          */
697         {
698             const bool isCheckpointingStep = false;
699             const bool doRerun             = true;
700             const bool bSumEkinhOld        = false;
701             do_md_trajectory_writing(fplog,
702                                      cr,
703                                      nfile,
704                                      fnm,
705                                      step,
706                                      step_rel,
707                                      t,
708                                      ir,
709                                      state,
710                                      state_global,
711                                      observablesHistory,
712                                      top_global,
713                                      fr,
714                                      outf,
715                                      energyOutput,
716                                      ekind,
717                                      f.view().force(),
718                                      isCheckpointingStep,
719                                      doRerun,
720                                      isLastStep,
721                                      mdrunOptions.writeConfout,
722                                      bSumEkinhOld);
723         }
724
725         stopHandler->setSignal();
726
727         {
728             const bool          doInterSimSignal = false;
729             const bool          doIntraSimSignal = true;
730             bool                bSumEkinhOld     = false;
731             t_vcm*              vcm              = nullptr;
732             SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
733
734             int cglo_flags = CGLO_GSTAT | CGLO_ENERGY;
735             if (DOMAINDECOMP(cr) && shouldCheckNumberOfBondedInteractions(*cr->dd))
736             {
737                 cglo_flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
738             }
739             compute_globals(gstat,
740                             cr,
741                             ir,
742                             fr,
743                             ekind,
744                             makeConstArrayRef(state->x),
745                             makeConstArrayRef(state->v),
746                             state->box,
747                             mdatoms,
748                             nrnb,
749                             vcm,
750                             wcycle,
751                             enerd,
752                             force_vir,
753                             shake_vir,
754                             total_vir,
755                             pres,
756                             constr != nullptr ? constr->rmsdData() : gmx::ArrayRef<real>{},
757                             &signaller,
758                             state->box,
759                             &bSumEkinhOld,
760                             cglo_flags);
761             if (DOMAINDECOMP(cr))
762             {
763                 checkNumberOfBondedInteractions(
764                         mdlog, cr, top_global, &top, makeConstArrayRef(state->x), state->box);
765             }
766         }
767
768         /* Note: this is OK, but there are some numerical precision issues with using the convergence of
769            the virial that should probably be addressed eventually. state->veta has better properies,
770            but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
771            generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
772
773         /* Output stuff */
774         if (MASTER(cr))
775         {
776             const bool bCalcEnerStep = true;
777             energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation,
778                                              bCalcEnerStep,
779                                              t,
780                                              mdatoms->tmass,
781                                              enerd,
782                                              ir->fepvals.get(),
783                                              ir->expandedvals.get(),
784                                              state->box,
785                                              PTCouplingArrays({ state->boxv,
786                                                                 state->nosehoover_xi,
787                                                                 state->nosehoover_vxi,
788                                                                 state->nhpres_xi,
789                                                                 state->nhpres_vxi }),
790                                              state->fep_state,
791                                              shake_vir,
792                                              force_vir,
793                                              total_vir,
794                                              pres,
795                                              ekind,
796                                              mu_tot,
797                                              constr);
798
799             const bool do_ene = true;
800             const bool do_log = true;
801             Awh*       awh    = nullptr;
802             const bool do_dr  = ir->nstdisreout != 0;
803             const bool do_or  = ir->nstorireout != 0;
804
805             EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
806             energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf),
807                                                do_ene,
808                                                do_dr,
809                                                do_or,
810                                                do_log ? fplog : nullptr,
811                                                step,
812                                                t,
813                                                fr->fcdata.get(),
814                                                awh);
815
816             if (do_per_step(step, ir->nstlog))
817             {
818                 if (fflush(fplog) != 0)
819                 {
820                     gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
821                 }
822             }
823         }
824
825         /* Print the remaining wall clock time for the run */
826         if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
827         {
828             if (shellfc)
829             {
830                 fprintf(stderr, "\n");
831             }
832             print_time(stderr, walltime_accounting, step, ir, cr);
833         }
834
835         /* Ion/water position swapping.
836          * Not done in last step since trajectory writing happens before this call
837          * in the MD loop and exchanges would be lost anyway. */
838         if ((ir->eSwapCoords != SwapType::No) && (step > 0) && !isLastStep
839             && do_per_step(step, ir->swap->nstswap))
840         {
841             const bool doRerun = true;
842             do_swapcoords(cr,
843                           step,
844                           t,
845                           ir,
846                           swap,
847                           wcycle,
848                           rerun_fr.x,
849                           rerun_fr.box,
850                           MASTER(cr) && mdrunOptions.verbose,
851                           doRerun);
852         }
853
854         if (MASTER(cr))
855         {
856             /* read next frame from input trajectory */
857             isLastStep = !read_next_frame(oenv, status, &rerun_fr);
858         }
859
860         if (PAR(cr))
861         {
862             rerun_parallel_comm(cr, &rerun_fr, &isLastStep);
863         }
864
865         cycles = wallcycle_stop(wcycle, ewcSTEP);
866         if (DOMAINDECOMP(cr) && wcycle)
867         {
868             dd_cycles_add(cr->dd, cycles, ddCyclStep);
869         }
870
871         if (!rerun_fr.bStep)
872         {
873             /* increase the MD step number */
874             step++;
875             step_rel++;
876         }
877     }
878     /* End of main MD loop */
879
880     /* Closing TNG files can include compressing data. Therefore it is good to do that
881      * before stopping the time measurements. */
882     mdoutf_tng_close(outf);
883
884     /* Stop measuring walltime */
885     walltime_accounting_end_time(walltime_accounting);
886
887     if (MASTER(cr))
888     {
889         close_trx(status);
890     }
891
892     if (!thisRankHasDuty(cr, DUTY_PME))
893     {
894         /* Tell the PME only node to finish */
895         gmx_pme_send_finish(cr);
896     }
897
898     done_mdoutf(outf);
899
900     done_shellfc(fplog, shellfc, step_rel);
901
902     walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
903 }