Make CpuPpLongRangeNonbondeds class
[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/observablesreducer.h"
119 #include "gromacs/mdtypes/simulation_workload.h"
120 #include "gromacs/mdtypes/state.h"
121 #include "gromacs/mimic/communicator.h"
122 #include "gromacs/mimic/utilities.h"
123 #include "gromacs/pbcutil/pbc.h"
124 #include "gromacs/pulling/pull.h"
125 #include "gromacs/timing/wallcycle.h"
126 #include "gromacs/timing/walltime_accounting.h"
127 #include "gromacs/topology/atoms.h"
128 #include "gromacs/topology/idef.h"
129 #include "gromacs/topology/mtop_util.h"
130 #include "gromacs/topology/topology.h"
131 #include "gromacs/trajectory/trajectoryframe.h"
132 #include "gromacs/utility/basedefinitions.h"
133 #include "gromacs/utility/cstringutil.h"
134 #include "gromacs/utility/fatalerror.h"
135 #include "gromacs/utility/logger.h"
136 #include "gromacs/utility/real.h"
137
138 #include "legacysimulator.h"
139 #include "replicaexchange.h"
140 #include "shellfc.h"
141
142 using gmx::SimulationSignaller;
143
144 void gmx::LegacySimulator::do_mimic()
145 {
146     const t_inputrec* ir = inputrec;
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     ObservablesReducer observablesReducer = observablesReducerBuilder->build();
211
212     if (MASTER(cr))
213     {
214         MimicCommunicator::init();
215         auto* nonConstGlobalTopology = const_cast<gmx_mtop_t*>(&top_global);
216         MimicCommunicator::sendInitData(nonConstGlobalTopology, state_global->x);
217         // TODO: Avoid changing inputrec (#3854)
218         auto* nonConstInputrec   = const_cast<t_inputrec*>(inputrec);
219         nonConstInputrec->nsteps = MimicCommunicator::getStepNumber();
220     }
221     if (DOMAINDECOMP(cr))
222     {
223         // TODO: Avoid changing inputrec (#3854)
224         auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec);
225         gmx_bcast(sizeof(ir->nsteps), &nonConstInputrec->nsteps, cr->mpi_comm_mygroup);
226     }
227
228     const SimulationGroups* groups = &top_global.groups;
229     {
230         auto* nonConstGlobalTopology                         = const_cast<gmx_mtop_t*>(&top_global);
231         nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(top_global);
232     }
233
234     initialize_lambdas(fplog,
235                        ir->efep,
236                        ir->bSimTemp,
237                        *ir->fepvals,
238                        ir->simtempvals->temperatures,
239                        gmx::arrayRefFromArray(ir->opts.ref_t, ir->opts.ngtc),
240                        MASTER(cr),
241                        &state_global->fep_state,
242                        state_global->lambda);
243
244     const bool        simulationsShareState = false;
245     gmx_mdoutf*       outf                  = init_mdoutf(fplog,
246                                    nfile,
247                                    fnm,
248                                    mdrunOptions,
249                                    cr,
250                                    outputProvider,
251                                    mdModulesNotifiers,
252                                    ir,
253                                    top_global,
254                                    oenv,
255                                    wcycle,
256                                    StartingBehavior::NewSimulation,
257                                    simulationsShareState,
258                                    ms);
259     gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf),
260                                    top_global,
261                                    *ir,
262                                    pull_work,
263                                    mdoutf_get_fp_dhdl(outf),
264                                    true,
265                                    StartingBehavior::NewSimulation,
266                                    simulationsShareState,
267                                    mdModulesNotifiers);
268
269     gstat = global_stat_init(ir);
270
271     /* Check for polarizable models and flexible constraints */
272     shellfc = init_shell_flexcon(fplog,
273                                  top_global,
274                                  constr ? constr->numFlexibleConstraints() : 0,
275                                  ir->nstcalcenergy,
276                                  DOMAINDECOMP(cr),
277                                  runScheduleWork->simulationWork.useGpuPme);
278
279     {
280         double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1);
281         if ((io > 2000) && MASTER(cr))
282         {
283             fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
284         }
285     }
286
287     // Local state only becomes valid now.
288     std::unique_ptr<t_state> stateInstance;
289     t_state*                 state;
290
291     gmx_localtop_t top(top_global.ffparams);
292
293     if (DOMAINDECOMP(cr))
294     {
295         stateInstance = std::make_unique<t_state>();
296         state         = stateInstance.get();
297         dd_init_local_state(*cr->dd, state_global, state);
298
299         /* Distribute the charge groups over the nodes from the master node */
300         dd_partition_system(fplog,
301                             mdlog,
302                             ir->init_step,
303                             cr,
304                             TRUE,
305                             1,
306                             state_global,
307                             top_global,
308                             *ir,
309                             imdSession,
310                             pull_work,
311                             state,
312                             &f,
313                             mdAtoms,
314                             &top,
315                             fr,
316                             vsite,
317                             constr,
318                             nrnb,
319                             nullptr,
320                             FALSE);
321     }
322     else
323     {
324         state_change_natoms(state_global, state_global->natoms);
325         /* Copy the pointer to the global state */
326         state = state_global;
327
328         mdAlgorithmsSetupAtomData(cr, *ir, top_global, &top, fr, &f, mdAtoms, constr, vsite, shellfc);
329     }
330
331     auto* mdatoms = mdAtoms->mdatoms();
332
333     // NOTE: The global state is no longer used at this point.
334     // But state_global is still used as temporary storage space for writing
335     // the global state to file and potentially for replica exchange.
336     // (Global topology should persist.)
337
338     update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
339     fr->longRangeNonbondeds->updateAfterPartition(*mdatoms);
340
341     if (ir->efep != FreeEnergyPerturbationType::No && ir->fepvals->nstdhdl != 0)
342     {
343         doFreeEnergyPerturbation = true;
344     }
345
346     int64_t step     = ir->init_step;
347     int64_t step_rel = 0;
348
349     {
350         int cglo_flags = CGLO_GSTAT;
351         if (DOMAINDECOMP(cr) && dd_localTopologyChecker(*cr->dd).shouldCheckNumberOfBondedInteractions())
352         {
353             cglo_flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
354         }
355         bool   bSumEkinhOld = false;
356         t_vcm* vcm          = nullptr;
357         compute_globals(gstat,
358                         cr,
359                         ir,
360                         fr,
361                         ekind,
362                         makeConstArrayRef(state->x),
363                         makeConstArrayRef(state->v),
364                         state->box,
365                         mdatoms,
366                         nrnb,
367                         vcm,
368                         nullptr,
369                         enerd,
370                         force_vir,
371                         shake_vir,
372                         total_vir,
373                         pres,
374                         gmx::ArrayRef<real>{},
375                         &nullSignaller,
376                         state->box,
377                         &bSumEkinhOld,
378                         cglo_flags,
379                         step,
380                         &observablesReducer);
381         if (DOMAINDECOMP(cr))
382         {
383             dd_localTopologyChecker(cr->dd)->checkNumberOfBondedInteractions(
384                     &top, makeConstArrayRef(state->x), state->box);
385         }
386     }
387
388     if (MASTER(cr))
389     {
390         fprintf(stderr, "starting MiMiC MD run '%s'\n\n", *(top_global.name));
391         if (mdrunOptions.verbose)
392         {
393             fprintf(stderr,
394                     "Calculated time to finish depends on nsteps from "
395                     "run input file,\nwhich may not correspond to the time "
396                     "needed to process input trajectory.\n\n");
397         }
398         fprintf(fplog, "\n");
399     }
400
401     walltime_accounting_start_time(walltime_accounting);
402     wallcycle_start(wcycle, WallCycleCounter::Run);
403     print_start(fplog, cr, walltime_accounting, "mdrun");
404
405     /***********************************************************
406      *
407      *             Loop over MD steps
408      *
409      ************************************************************/
410
411     if (constr)
412     {
413         GMX_LOG(mdlog.info)
414                 .asParagraph()
415                 .appendText(
416                         "Simulations has constraints. Constraints will "
417                         "be handled by CPMD.");
418     }
419
420     GMX_LOG(mdlog.info)
421             .asParagraph()
422             .appendText(
423                     "MiMiC does not report kinetic energy, total energy, temperature, virial and "
424                     "pressure.");
425
426     auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
427             compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]),
428             false,
429             MASTER(cr),
430             ir->nstlist,
431             mdrunOptions.reproducible,
432             nstglobalcomm,
433             mdrunOptions.maximumHoursToRun,
434             ir->nstlist == 0,
435             fplog,
436             step,
437             bNS,
438             walltime_accounting);
439
440     // we don't do counter resetting in rerun - finish will always be valid
441     walltime_accounting_set_valid_finish(walltime_accounting);
442
443     const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
444
445     /* and stop now if we should */
446     isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
447     while (!isLastStep)
448     {
449         isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel == ir->nsteps));
450         wallcycle_start(wcycle, WallCycleCounter::Step);
451
452         t = step;
453
454         if (MASTER(cr))
455         {
456             MimicCommunicator::getCoords(state_global->x, state_global->natoms);
457         }
458
459         if (ir->efep != FreeEnergyPerturbationType::No)
460         {
461             state->lambda = currentLambdas(step, *(ir->fepvals), state_global->fep_state);
462         }
463
464         if (MASTER(cr))
465         {
466             const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
467             if (constructVsites && DOMAINDECOMP(cr))
468             {
469                 gmx_fatal(FARGS,
470                           "Vsite recalculation with -rerun is not implemented with domain "
471                           "decomposition, "
472                           "use a single rank");
473             }
474             if (constructVsites)
475             {
476                 wallcycle_start(wcycle, WallCycleCounter::VsiteConstr);
477                 vsite->construct(state->x, state->v, state->box, VSiteOperation::PositionsAndVelocities);
478                 wallcycle_stop(wcycle, WallCycleCounter::VsiteConstr);
479             }
480         }
481
482         if (DOMAINDECOMP(cr))
483         {
484             /* Repartition the domain decomposition */
485             const bool bMasterState = true;
486             dd_partition_system(fplog,
487                                 mdlog,
488                                 step,
489                                 cr,
490                                 bMasterState,
491                                 nstglobalcomm,
492                                 state_global,
493                                 top_global,
494                                 *ir,
495                                 imdSession,
496                                 pull_work,
497                                 state,
498                                 &f,
499                                 mdAtoms,
500                                 &top,
501                                 fr,
502                                 vsite,
503                                 constr,
504                                 nrnb,
505                                 wcycle,
506                                 mdrunOptions.verbose);
507         }
508
509         if (MASTER(cr))
510         {
511             EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */
512         }
513
514         if (ir->efep != FreeEnergyPerturbationType::No)
515         {
516             update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
517         }
518
519         fr->longRangeNonbondeds->updateAfterPartition(*mdatoms);
520
521         force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
522                        | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 is solved
523                        GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
524
525         if (shellfc)
526         {
527             /* Now is the time to relax the shells */
528             relax_shell_flexcon(fplog,
529                                 cr,
530                                 ms,
531                                 mdrunOptions.verbose,
532                                 enforcedRotation,
533                                 step,
534                                 ir,
535                                 imdSession,
536                                 pull_work,
537                                 bNS,
538                                 force_flags,
539                                 &top,
540                                 constr,
541                                 enerd,
542                                 state->natoms,
543                                 state->x.arrayRefWithPadding(),
544                                 state->v.arrayRefWithPadding(),
545                                 state->box,
546                                 state->lambda,
547                                 &state->hist,
548                                 &f.view(),
549                                 force_vir,
550                                 *mdatoms,
551                                 fr->longRangeNonbondeds.get(),
552                                 nrnb,
553                                 wcycle,
554                                 shellfc,
555                                 fr,
556                                 runScheduleWork,
557                                 t,
558                                 mu_tot,
559                                 vsite,
560                                 ddBalanceRegionHandler);
561         }
562         else
563         {
564             /* The coordinates (x) are shifted (to get whole molecules)
565              * in do_force.
566              * This is parallellized as well, and does communication too.
567              * Check comments in sim_util.c
568              */
569             Awh*       awh = nullptr;
570             gmx_edsam* ed  = nullptr;
571             do_force(fplog,
572                      cr,
573                      ms,
574                      *ir,
575                      awh,
576                      enforcedRotation,
577                      imdSession,
578                      pull_work,
579                      step,
580                      nrnb,
581                      wcycle,
582                      &top,
583                      state->box,
584                      state->x.arrayRefWithPadding(),
585                      &state->hist,
586                      &f.view(),
587                      force_vir,
588                      mdatoms,
589                      enerd,
590                      state->lambda,
591                      fr,
592                      runScheduleWork,
593                      vsite,
594                      mu_tot,
595                      t,
596                      ed,
597                      fr->longRangeNonbondeds.get(),
598                      GMX_FORCE_NS | force_flags,
599                      ddBalanceRegionHandler);
600         }
601
602         /* Now we have the energies and forces corresponding to the
603          * coordinates at time t.
604          */
605         {
606             const bool isCheckpointingStep = false;
607             const bool doRerun             = false;
608             const bool bSumEkinhOld        = false;
609             do_md_trajectory_writing(fplog,
610                                      cr,
611                                      nfile,
612                                      fnm,
613                                      step,
614                                      step_rel,
615                                      t,
616                                      ir,
617                                      state,
618                                      state_global,
619                                      observablesHistory,
620                                      top_global,
621                                      fr,
622                                      outf,
623                                      energyOutput,
624                                      ekind,
625                                      f.view().force(),
626                                      isCheckpointingStep,
627                                      doRerun,
628                                      isLastStep,
629                                      mdrunOptions.writeConfout,
630                                      bSumEkinhOld);
631         }
632
633         stopHandler->setSignal();
634
635         {
636             const bool          doInterSimSignal = false;
637             const bool          doIntraSimSignal = true;
638             bool                bSumEkinhOld     = false;
639             t_vcm*              vcm              = nullptr;
640             SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
641
642             int cglo_flags = CGLO_GSTAT | CGLO_ENERGY;
643             if (DOMAINDECOMP(cr) && dd_localTopologyChecker(*cr->dd).shouldCheckNumberOfBondedInteractions())
644             {
645                 cglo_flags |= CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS;
646             }
647             compute_globals(gstat,
648                             cr,
649                             ir,
650                             fr,
651                             ekind,
652                             makeConstArrayRef(state->x),
653                             makeConstArrayRef(state->v),
654                             state->box,
655                             mdatoms,
656                             nrnb,
657                             vcm,
658                             wcycle,
659                             enerd,
660                             nullptr,
661                             nullptr,
662                             nullptr,
663                             nullptr,
664                             constr != nullptr ? constr->rmsdData() : gmx::ArrayRef<real>{},
665                             &signaller,
666                             state->box,
667                             &bSumEkinhOld,
668                             cglo_flags,
669                             step,
670                             &observablesReducer);
671             if (DOMAINDECOMP(cr))
672             {
673                 dd_localTopologyChecker(cr->dd)->checkNumberOfBondedInteractions(
674                         &top, makeConstArrayRef(state->x), state->box);
675             }
676         }
677
678         {
679             gmx::HostVector<gmx::RVec>     fglobal(top_global.natoms);
680             gmx::ArrayRef<gmx::RVec>       ftemp;
681             gmx::ArrayRef<const gmx::RVec> flocal = f.view().force();
682             if (DOMAINDECOMP(cr))
683             {
684                 ftemp = gmx::makeArrayRef(fglobal);
685                 dd_collect_vec(cr->dd, state->ddp_count, state->ddp_count_cg_gl, state->cg_gl, flocal, ftemp);
686             }
687             else
688             {
689                 ftemp = f.view().force();
690             }
691
692             if (MASTER(cr))
693             {
694                 MimicCommunicator::sendEnergies(enerd->term[F_EPOT]);
695                 MimicCommunicator::sendForces(ftemp, state_global->natoms);
696             }
697         }
698
699
700         /* Note: this is OK, but there are some numerical precision issues with using the convergence of
701            the virial that should probably be addressed eventually. state->veta has better properies,
702            but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
703            generate the new shake_vir, but test the veta value for convergence.  This will take some thought. */
704
705         if (ir->efep != FreeEnergyPerturbationType::No)
706         {
707             /* Sum up the foreign energy and dhdl terms for md and sd.
708                Currently done every step so that dhdl is correct in the .edr */
709             accumulateKineticLambdaComponents(enerd, state->lambda, *ir->fepvals);
710         }
711
712         /* Output stuff */
713         if (MASTER(cr))
714         {
715             const bool bCalcEnerStep = true;
716             energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation,
717                                              bCalcEnerStep,
718                                              t,
719                                              mdatoms->tmass,
720                                              enerd,
721                                              ir->fepvals.get(),
722                                              ir->expandedvals.get(),
723                                              state->box,
724                                              PTCouplingArrays({ state->boxv,
725                                                                 state->nosehoover_xi,
726                                                                 state->nosehoover_vxi,
727                                                                 state->nhpres_xi,
728                                                                 state->nhpres_vxi }),
729                                              state->fep_state,
730                                              total_vir,
731                                              pres,
732                                              ekind,
733                                              mu_tot,
734                                              constr);
735
736             const bool do_ene = true;
737             const bool do_log = true;
738             Awh*       awh    = nullptr;
739             const bool do_dr  = ir->nstdisreout != 0;
740             const bool do_or  = ir->nstorireout != 0;
741
742             EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
743             energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf),
744                                                do_ene,
745                                                do_dr,
746                                                do_or,
747                                                do_log ? fplog : nullptr,
748                                                step,
749                                                t,
750                                                fr->fcdata.get(),
751                                                awh);
752
753             if (do_per_step(step, ir->nstlog))
754             {
755                 if (fflush(fplog) != 0)
756                 {
757                     gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
758                 }
759             }
760         }
761
762         /* Print the remaining wall clock time for the run */
763         if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
764         {
765             if (shellfc)
766             {
767                 fprintf(stderr, "\n");
768             }
769             print_time(stderr, walltime_accounting, step, ir, cr);
770         }
771
772         cycles = wallcycle_stop(wcycle, WallCycleCounter::Step);
773         if (DOMAINDECOMP(cr) && wcycle)
774         {
775             dd_cycles_add(cr->dd, cycles, ddCyclStep);
776         }
777
778         /* increase the MD step number */
779         step++;
780         step_rel++;
781     }
782     /* End of main MD loop */
783
784     /* Closing TNG files can include compressing data. Therefore it is good to do that
785      * before stopping the time measurements. */
786     mdoutf_tng_close(outf);
787
788     /* Stop measuring walltime */
789     walltime_accounting_end_time(walltime_accounting);
790
791     if (MASTER(cr))
792     {
793         MimicCommunicator::finalize();
794     }
795
796     if (!thisRankHasDuty(cr, DUTY_PME))
797     {
798         /* Tell the PME only node to finish */
799         gmx_pme_send_finish(cr);
800     }
801
802     done_mdoutf(outf);
803
804     done_shellfc(fplog, shellfc, step_rel);
805
806     walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);
807 }