Move the code of what will later implement LocalTopologyChecker
[alexxy/gromacs.git] / src / gromacs / mdrun / mimic.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
36 /*! \internal \file
37  *
38  * \brief Declares the loop for MiMiC QM/MM
39  *
40  * \author Viacheslav Bolnykh <v.bolnykh@hpc-leap.eu>
41  * \ingroup module_mdrun
42  */
43 #include "gmxpre.h"
44
45 #include <cinttypes>
46 #include <cmath>
47 #include <cstdio>
48 #include <cstdlib>
49
50 #include <algorithm>
51 #include <memory>
52
53 #include "gromacs/applied_forces/awh/awh.h"
54 #include "gromacs/commandline/filenm.h"
55 #include "gromacs/domdec/collect.h"
56 #include "gromacs/domdec/dlbtiming.h"
57 #include "gromacs/domdec/domdec.h"
58 #include "gromacs/domdec/domdec_network.h"
59 #include "gromacs/domdec/domdec_struct.h"
60 #include "gromacs/domdec/localtopologychecker.h"
61 #include "gromacs/domdec/mdsetup.h"
62 #include "gromacs/domdec/partition.h"
63 #include "gromacs/essentialdynamics/edsam.h"
64 #include "gromacs/ewald/pme_load_balancing.h"
65 #include "gromacs/ewald/pme_pp.h"
66 #include "gromacs/fileio/trxio.h"
67 #include "gromacs/gmxlib/network.h"
68 #include "gromacs/gmxlib/nrnb.h"
69 #include "gromacs/gpu_utils/gpu_utils.h"
70 #include "gromacs/listed_forces/listed_forces.h"
71 #include "gromacs/math/functions.h"
72 #include "gromacs/math/utilities.h"
73 #include "gromacs/math/vec.h"
74 #include "gromacs/math/vectypes.h"
75 #include "gromacs/mdlib/checkpointhandler.h"
76 #include "gromacs/mdlib/compute_io.h"
77 #include "gromacs/mdlib/constr.h"
78 #include "gromacs/mdlib/ebin.h"
79 #include "gromacs/mdlib/enerdata_utils.h"
80 #include "gromacs/mdlib/energyoutput.h"
81 #include "gromacs/mdlib/expanded.h"
82 #include "gromacs/mdlib/force.h"
83 #include "gromacs/mdlib/force_flags.h"
84 #include "gromacs/mdlib/forcerec.h"
85 #include "gromacs/mdlib/freeenergyparameters.h"
86 #include "gromacs/mdlib/md_support.h"
87 #include "gromacs/mdlib/mdatoms.h"
88 #include "gromacs/mdlib/mdoutf.h"
89 #include "gromacs/mdlib/membed.h"
90 #include "gromacs/mdlib/resethandler.h"
91 #include "gromacs/mdlib/sighandler.h"
92 #include "gromacs/mdlib/simulationsignal.h"
93 #include "gromacs/mdlib/stat.h"
94 #include "gromacs/mdlib/stophandler.h"
95 #include "gromacs/mdlib/tgroup.h"
96 #include "gromacs/mdlib/trajectory_writing.h"
97 #include "gromacs/mdlib/update.h"
98 #include "gromacs/mdlib/vcm.h"
99 #include "gromacs/mdlib/vsite.h"
100 #include "gromacs/mdrunutility/handlerestart.h"
101 #include "gromacs/mdrunutility/multisim.h"
102 #include "gromacs/mdrunutility/printtime.h"
103 #include "gromacs/mdtypes/awh_history.h"
104 #include "gromacs/mdtypes/awh_params.h"
105 #include "gromacs/mdtypes/commrec.h"
106 #include "gromacs/mdtypes/df_history.h"
107 #include "gromacs/mdtypes/enerdata.h"
108 #include "gromacs/mdtypes/energyhistory.h"
109 #include "gromacs/mdtypes/forcebuffers.h"
110 #include "gromacs/mdtypes/forcerec.h"
111 #include "gromacs/mdtypes/group.h"
112 #include "gromacs/mdtypes/inputrec.h"
113 #include "gromacs/mdtypes/interaction_const.h"
114 #include "gromacs/mdtypes/md_enums.h"
115 #include "gromacs/mdtypes/mdatom.h"
116 #include "gromacs/mdtypes/mdrunoptions.h"
117 #include "gromacs/mdtypes/observableshistory.h"
118 #include "gromacs/mdtypes/simulation_workload.h"
119 #include "gromacs/mdtypes/state.h"
120 #include "gromacs/mimic/communicator.h"
121 #include "gromacs/mimic/utilities.h"
122 #include "gromacs/pbcutil/pbc.h"
123 #include "gromacs/pulling/pull.h"
124 #include "gromacs/timing/wallcycle.h"
125 #include "gromacs/timing/walltime_accounting.h"
126 #include "gromacs/topology/atoms.h"
127 #include "gromacs/topology/idef.h"
128 #include "gromacs/topology/mtop_util.h"
129 #include "gromacs/topology/topology.h"
130 #include "gromacs/trajectory/trajectoryframe.h"
131 #include "gromacs/utility/basedefinitions.h"
132 #include "gromacs/utility/cstringutil.h"
133 #include "gromacs/utility/fatalerror.h"
134 #include "gromacs/utility/logger.h"
135 #include "gromacs/utility/real.h"
136
137 #include "legacysimulator.h"
138 #include "replicaexchange.h"
139 #include "shellfc.h"
140
141 using gmx::SimulationSignaller;
142
143 void gmx::LegacySimulator::do_mimic()
144 {
145     const t_inputrec* ir = inputrec;
146     int64_t           step, step_rel;
147     double            t;
148     bool              isLastStep               = false;
149     bool              doFreeEnergyPerturbation = false;
150     unsigned int      force_flags;
151     tensor            force_vir, shake_vir, total_vir, pres;
152     rvec              mu_tot;
153     ForceBuffers      f;
154     gmx_global_stat_t gstat;
155     gmx_shellfc_t*    shellfc;
156
157     double cycles;
158
159     SimulationSignals signals;
160     // Most global communnication stages don't propagate mdrun
161     // signals, and will use this object to achieve that.
162     SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false);
163
164     if (ir->bExpanded)
165     {
166         gmx_fatal(FARGS, "Expanded ensemble not supported by MiMiC.");
167     }
168     if (ir->bSimTemp)
169     {
170         gmx_fatal(FARGS, "Simulated tempering not supported by MiMiC.");
171     }
172     if (ir->bDoAwh)
173     {
174         gmx_fatal(FARGS, "AWH not supported by MiMiC.");
175     }
176     if (replExParams.exchangeInterval > 0)
177     {
178         gmx_fatal(FARGS, "Replica exchange not supported by MiMiC.");
179     }
180     if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
181     {
182         gmx_fatal(FARGS, "Essential dynamics not supported by MiMiC.");
183     }
184     if (ir->bIMD)
185     {
186         gmx_fatal(FARGS, "Interactive MD not supported by MiMiC.");
187     }
188     if (isMultiSim(ms))
189     {
190         gmx_fatal(FARGS, "Multiple simulations not supported by MiMiC.");
191     }
192     if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](SimulatedAnnealing i) {
193             return i != SimulatedAnnealing::No;
194         }))
195     {
196         gmx_fatal(FARGS, "Simulated annealing not supported by MiMiC.");
197     }
198
199     /* Settings for rerun */
200     {
201         // TODO: Avoid changing inputrec (#3854)
202         auto* nonConstInputrec               = const_cast<t_inputrec*>(inputrec);
203         nonConstInputrec->nstlist            = 1;
204         nonConstInputrec->nstcalcenergy      = 1;
205         nonConstInputrec->nstxout_compressed = 0;
206     }
207     int        nstglobalcomm = 1;
208     const bool bNS           = true;
209
210     if (MASTER(cr))
211     {
212         MimicCommunicator::init();
213         auto* nonConstGlobalTopology = const_cast<gmx_mtop_t*>(&top_global);
214         MimicCommunicator::sendInitData(nonConstGlobalTopology, state_global->x);
215         // TODO: Avoid changing inputrec (#3854)
216         auto* nonConstInputrec   = const_cast<t_inputrec*>(inputrec);
217         nonConstInputrec->nsteps = MimicCommunicator::getStepNumber();
218     }
219     if (DOMAINDECOMP(cr))
220     {
221         // TODO: Avoid changing inputrec (#3854)
222         auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec);
223         gmx_bcast(sizeof(ir->nsteps), &nonConstInputrec->nsteps, cr->mpi_comm_mygroup);
224     }
225
226     const SimulationGroups* groups = &top_global.groups;
227     {
228         auto* nonConstGlobalTopology                         = const_cast<gmx_mtop_t*>(&top_global);
229         nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(top_global);
230     }
231
232     initialize_lambdas(fplog,
233                        ir->efep,
234                        ir->bSimTemp,
235                        *ir->fepvals,
236                        ir->simtempvals->temperatures,
237                        gmx::arrayRefFromArray(ir->opts.ref_t, ir->opts.ngtc),
238                        MASTER(cr),
239                        &state_global->fep_state,
240                        state_global->lambda);
241
242     const bool        simulationsShareState = false;
243     gmx_mdoutf*       outf                  = init_mdoutf(fplog,
244                                    nfile,
245                                    fnm,
246                                    mdrunOptions,
247                                    cr,
248                                    outputProvider,
249                                    mdModulesNotifiers,
250                                    ir,
251                                    top_global,
252                                    oenv,
253                                    wcycle,
254                                    StartingBehavior::NewSimulation,
255                                    simulationsShareState,
256                                    ms);
257     gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf),
258                                    top_global,
259                                    *ir,
260                                    pull_work,
261                                    mdoutf_get_fp_dhdl(outf),
262                                    true,
263                                    StartingBehavior::NewSimulation,
264                                    simulationsShareState,
265                                    mdModulesNotifiers);
266
267     gstat = global_stat_init(ir);
268
269     /* Check for polarizable models and flexible constraints */
270     shellfc = init_shell_flexcon(fplog,
271                                  top_global,
272                                  constr ? constr->numFlexibleConstraints() : 0,
273                                  ir->nstcalcenergy,
274                                  DOMAINDECOMP(cr),
275                                  runScheduleWork->simulationWork.useGpuPme);
276
277     {
278         double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1);
279         if ((io > 2000) && MASTER(cr))
280         {
281             fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
282         }
283     }
284
285     // Local state only becomes valid now.
286     std::unique_ptr<t_state> stateInstance;
287     t_state*                 state;
288
289     gmx_localtop_t top(top_global.ffparams);
290
291     if (DOMAINDECOMP(cr))
292     {
293         stateInstance = std::make_unique<t_state>();
294         state         = stateInstance.get();
295         dd_init_local_state(*cr->dd, state_global, state);
296
297         /* Distribute the charge groups over the nodes from the master node */
298         dd_partition_system(fplog,
299                             mdlog,
300                             ir->init_step,
301                             cr,
302                             TRUE,
303                             1,
304                             state_global,
305                             top_global,
306                             *ir,
307                             imdSession,
308                             pull_work,
309                             state,
310                             &f,
311                             mdAtoms,
312                             &top,
313                             fr,
314                             vsite,
315                             constr,
316                             nrnb,
317                             nullptr,
318                             FALSE);
319     }
320     else
321     {
322         state_change_natoms(state_global, state_global->natoms);
323         /* Copy the pointer to the global state */
324         state = state_global;
325
326         mdAlgorithmsSetupAtomData(cr, *ir, top_global, &top, fr, &f, mdAtoms, constr, vsite, shellfc);
327     }
328
329     auto* mdatoms = mdAtoms->mdatoms();
330
331     // NOTE: The global state is no longer used at this point.
332     // But state_global is still used as temporary storage space for writing
333     // the global state to file and potentially for replica exchange.
334     // (Global topology should persist.)
335
336     update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
337
338     if (ir->efep != FreeEnergyPerturbationType::No && ir->fepvals->nstdhdl != 0)
339     {
340         doFreeEnergyPerturbation = true;
341     }
342
343     {
344         int cglo_flags = CGLO_GSTAT;
345         if (DOMAINDECOMP(cr) && shouldCheckNumberOfBondedInteractions(*cr->dd))
346         {
347             cglo_flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
348         }
349         bool   bSumEkinhOld = false;
350         t_vcm* vcm          = nullptr;
351         compute_globals(gstat,
352                         cr,
353                         ir,
354                         fr,
355                         ekind,
356                         makeConstArrayRef(state->x),
357                         makeConstArrayRef(state->v),
358                         state->box,
359                         mdatoms,
360                         nrnb,
361                         vcm,
362                         nullptr,
363                         enerd,
364                         force_vir,
365                         shake_vir,
366                         total_vir,
367                         pres,
368                         gmx::ArrayRef<real>{},
369                         &nullSignaller,
370                         state->box,
371                         &bSumEkinhOld,
372                         cglo_flags);
373         if (DOMAINDECOMP(cr))
374         {
375             checkNumberOfBondedInteractions(
376                     mdlog, cr, top_global, &top, makeConstArrayRef(state->x), state->box);
377         }
378     }
379
380     if (MASTER(cr))
381     {
382         fprintf(stderr, "starting MiMiC MD run '%s'\n\n", *(top_global.name));
383         if (mdrunOptions.verbose)
384         {
385             fprintf(stderr,
386                     "Calculated time to finish depends on nsteps from "
387                     "run input file,\nwhich may not correspond to the time "
388                     "needed to process input trajectory.\n\n");
389         }
390         fprintf(fplog, "\n");
391     }
392
393     walltime_accounting_start_time(walltime_accounting);
394     wallcycle_start(wcycle, WallCycleCounter::Run);
395     print_start(fplog, cr, walltime_accounting, "mdrun");
396
397     /***********************************************************
398      *
399      *             Loop over MD steps
400      *
401      ************************************************************/
402
403     if (constr)
404     {
405         GMX_LOG(mdlog.info)
406                 .asParagraph()
407                 .appendText(
408                         "Simulations has constraints. Constraints will "
409                         "be handled by CPMD.");
410     }
411
412     GMX_LOG(mdlog.info)
413             .asParagraph()
414             .appendText(
415                     "MiMiC does not report kinetic energy, total energy, temperature, virial and "
416                     "pressure.");
417
418     step     = ir->init_step;
419     step_rel = 0;
420
421     auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
422             compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]),
423             false,
424             MASTER(cr),
425             ir->nstlist,
426             mdrunOptions.reproducible,
427             nstglobalcomm,
428             mdrunOptions.maximumHoursToRun,
429             ir->nstlist == 0,
430             fplog,
431             step,
432             bNS,
433             walltime_accounting);
434
435     // we don't do counter resetting in rerun - finish will always be valid
436     walltime_accounting_set_valid_finish(walltime_accounting);
437
438     const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
439
440     /* and stop now if we should */
441     isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
442     while (!isLastStep)
443     {
444         isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel == ir->nsteps));
445         wallcycle_start(wcycle, WallCycleCounter::Step);
446
447         t = step;
448
449         if (MASTER(cr))
450         {
451             MimicCommunicator::getCoords(&state_global->x, state_global->natoms);
452         }
453
454         if (ir->efep != FreeEnergyPerturbationType::No)
455         {
456             state->lambda = currentLambdas(step, *(ir->fepvals), state_global->fep_state);
457         }
458
459         if (MASTER(cr))
460         {
461             const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
462             if (constructVsites && DOMAINDECOMP(cr))
463             {
464                 gmx_fatal(FARGS,
465                           "Vsite recalculation with -rerun is not implemented with domain "
466                           "decomposition, "
467                           "use a single rank");
468             }
469             if (constructVsites)
470             {
471                 wallcycle_start(wcycle, WallCycleCounter::VsiteConstr);
472                 vsite->construct(state->x, state->v, state->box, VSiteOperation::PositionsAndVelocities);
473                 wallcycle_stop(wcycle, WallCycleCounter::VsiteConstr);
474             }
475         }
476
477         if (DOMAINDECOMP(cr))
478         {
479             /* Repartition the domain decomposition */
480             const bool bMasterState = true;
481             dd_partition_system(fplog,
482                                 mdlog,
483                                 step,
484                                 cr,
485                                 bMasterState,
486                                 nstglobalcomm,
487                                 state_global,
488                                 top_global,
489                                 *ir,
490                                 imdSession,
491                                 pull_work,
492                                 state,
493                                 &f,
494                                 mdAtoms,
495                                 &top,
496                                 fr,
497                                 vsite,
498                                 constr,
499                                 nrnb,
500                                 wcycle,
501                                 mdrunOptions.verbose);
502         }
503
504         if (MASTER(cr))
505         {
506             EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */
507         }
508
509         if (ir->efep != FreeEnergyPerturbationType::No)
510         {
511             update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
512         }
513
514         force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
515                        | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 is solved
516                        GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
517
518         if (shellfc)
519         {
520             /* Now is the time to relax the shells */
521             relax_shell_flexcon(fplog,
522                                 cr,
523                                 ms,
524                                 mdrunOptions.verbose,
525                                 enforcedRotation,
526                                 step,
527                                 ir,
528                                 imdSession,
529                                 pull_work,
530                                 bNS,
531                                 force_flags,
532                                 &top,
533                                 constr,
534                                 enerd,
535                                 state->natoms,
536                                 state->x.arrayRefWithPadding(),
537                                 state->v.arrayRefWithPadding(),
538                                 state->box,
539                                 state->lambda,
540                                 &state->hist,
541                                 &f.view(),
542                                 force_vir,
543                                 *mdatoms,
544                                 nrnb,
545                                 wcycle,
546                                 shellfc,
547                                 fr,
548                                 runScheduleWork,
549                                 t,
550                                 mu_tot,
551                                 vsite,
552                                 ddBalanceRegionHandler);
553         }
554         else
555         {
556             /* The coordinates (x) are shifted (to get whole molecules)
557              * in do_force.
558              * This is parallellized as well, and does communication too.
559              * Check comments in sim_util.c
560              */
561             Awh*       awh = nullptr;
562             gmx_edsam* ed  = nullptr;
563             do_force(fplog,
564                      cr,
565                      ms,
566                      *ir,
567                      awh,
568                      enforcedRotation,
569                      imdSession,
570                      pull_work,
571                      step,
572                      nrnb,
573                      wcycle,
574                      &top,
575                      state->box,
576                      state->x.arrayRefWithPadding(),
577                      &state->hist,
578                      &f.view(),
579                      force_vir,
580                      mdatoms,
581                      enerd,
582                      state->lambda,
583                      fr,
584                      runScheduleWork,
585                      vsite,
586                      mu_tot,
587                      t,
588                      ed,
589                      GMX_FORCE_NS | force_flags,
590                      ddBalanceRegionHandler);
591         }
592
593         /* Now we have the energies and forces corresponding to the
594          * coordinates at time t.
595          */
596         {
597             const bool isCheckpointingStep = false;
598             const bool doRerun             = false;
599             const bool bSumEkinhOld        = false;
600             do_md_trajectory_writing(fplog,
601                                      cr,
602                                      nfile,
603                                      fnm,
604                                      step,
605                                      step_rel,
606                                      t,
607                                      ir,
608                                      state,
609                                      state_global,
610                                      observablesHistory,
611                                      top_global,
612                                      fr,
613                                      outf,
614                                      energyOutput,
615                                      ekind,
616                                      f.view().force(),
617                                      isCheckpointingStep,
618                                      doRerun,
619                                      isLastStep,
620                                      mdrunOptions.writeConfout,
621                                      bSumEkinhOld);
622         }
623
624         stopHandler->setSignal();
625
626         {
627             const bool          doInterSimSignal = false;
628             const bool          doIntraSimSignal = true;
629             bool                bSumEkinhOld     = false;
630             t_vcm*              vcm              = nullptr;
631             SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
632
633             int cglo_flags = CGLO_GSTAT | CGLO_ENERGY;
634             if (DOMAINDECOMP(cr) && shouldCheckNumberOfBondedInteractions(*cr->dd))
635             {
636                 cglo_flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
637             }
638             compute_globals(gstat,
639                             cr,
640                             ir,
641                             fr,
642                             ekind,
643                             makeConstArrayRef(state->x),
644                             makeConstArrayRef(state->v),
645                             state->box,
646                             mdatoms,
647                             nrnb,
648                             vcm,
649                             wcycle,
650                             enerd,
651                             nullptr,
652                             nullptr,
653                             nullptr,
654                             nullptr,
655                             constr != nullptr ? constr->rmsdData() : gmx::ArrayRef<real>{},
656                             &signaller,
657                             state->box,
658                             &bSumEkinhOld,
659                             cglo_flags);
660             if (DOMAINDECOMP(cr))
661             {
662                 checkNumberOfBondedInteractions(
663                         mdlog, cr, top_global, &top, makeConstArrayRef(state->x), state->box);
664             }
665         }
666
667         {
668             gmx::HostVector<gmx::RVec>     fglobal(top_global.natoms);
669             gmx::ArrayRef<gmx::RVec>       ftemp;
670             gmx::ArrayRef<const gmx::RVec> flocal = f.view().force();
671             if (DOMAINDECOMP(cr))
672             {
673                 ftemp = gmx::makeArrayRef(fglobal);
674                 dd_collect_vec(cr->dd, state->ddp_count, state->ddp_count_cg_gl, state->cg_gl, flocal, ftemp);
675             }
676             else
677             {
678                 ftemp = f.view().force();
679             }
680
681             if (MASTER(cr))
682             {
683                 MimicCommunicator::sendEnergies(enerd->term[F_EPOT]);
684                 MimicCommunicator::sendForces(ftemp, state_global->natoms);
685             }
686         }
687
688
689         /* Note: this is OK, but there are some numerical precision issues with using the convergence of
690            the virial that should probably be addressed eventually. state->veta has better properies,
691            but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
692            generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
693
694         if (ir->efep != FreeEnergyPerturbationType::No)
695         {
696             /* Sum up the foreign energy and dhdl terms for md and sd.
697                Currently done every step so that dhdl is correct in the .edr */
698             accumulateKineticLambdaComponents(enerd, state->lambda, *ir->fepvals);
699         }
700
701         /* Output stuff */
702         if (MASTER(cr))
703         {
704             const bool bCalcEnerStep = true;
705             energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation,
706                                              bCalcEnerStep,
707                                              t,
708                                              mdatoms->tmass,
709                                              enerd,
710                                              ir->fepvals.get(),
711                                              ir->expandedvals.get(),
712                                              state->box,
713                                              PTCouplingArrays({ state->boxv,
714                                                                 state->nosehoover_xi,
715                                                                 state->nosehoover_vxi,
716                                                                 state->nhpres_xi,
717                                                                 state->nhpres_vxi }),
718                                              state->fep_state,
719                                              total_vir,
720                                              pres,
721                                              ekind,
722                                              mu_tot,
723                                              constr);
724
725             const bool do_ene = true;
726             const bool do_log = true;
727             Awh*       awh    = nullptr;
728             const bool do_dr  = ir->nstdisreout != 0;
729             const bool do_or  = ir->nstorireout != 0;
730
731             EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
732             energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf),
733                                                do_ene,
734                                                do_dr,
735                                                do_or,
736                                                do_log ? fplog : nullptr,
737                                                step,
738                                                t,
739                                                fr->fcdata.get(),
740                                                awh);
741
742             if (do_per_step(step, ir->nstlog))
743             {
744                 if (fflush(fplog) != 0)
745                 {
746                     gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
747                 }
748             }
749         }
750
751         /* Print the remaining wall clock time for the run */
752         if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
753         {
754             if (shellfc)
755             {
756                 fprintf(stderr, "\n");
757             }
758             print_time(stderr, walltime_accounting, step, ir, cr);
759         }
760
761         cycles = wallcycle_stop(wcycle, WallCycleCounter::Step);
762         if (DOMAINDECOMP(cr) && wcycle)
763         {
764             dd_cycles_add(cr->dd, cycles, ddCyclStep);
765         }
766
767         /* increase the MD step number */
768         step++;
769         step_rel++;
770     }
771     /* End of main MD loop */
772
773     /* Closing TNG files can include compressing data. Therefore it is good to do that
774      * before stopping the time measurements. */
775     mdoutf_tng_close(outf);
776
777     /* Stop measuring walltime */
778     walltime_accounting_end_time(walltime_accounting);
779
780     if (MASTER(cr))
781     {
782         MimicCommunicator::finalize();
783     }
784
785     if (!thisRankHasDuty(cr, DUTY_PME))
786     {
787         /* Tell the PME only node to finish */
788         gmx_pme_send_finish(cr);
789     }
790
791     done_mdoutf(outf);
792
793     done_shellfc(fplog, shellfc, step_rel);
794
795     walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
796 }