2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
38 * \brief Declares the loop for MiMiC QM/MM
40 * \author Viacheslav Bolnykh <v.bolnykh@hpc-leap.eu>
41 * \ingroup module_mdrun
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"
138 #include "legacysimulator.h"
139 #include "replicaexchange.h"
142 using gmx::SimulationSignaller;
144 void gmx::LegacySimulator::do_mimic()
146 const t_inputrec* ir = inputrec;
148 bool isLastStep = false;
149 bool doFreeEnergyPerturbation = false;
150 unsigned int force_flags;
151 tensor force_vir, shake_vir, total_vir, pres;
154 gmx_global_stat_t gstat;
155 gmx_shellfc_t* shellfc;
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);
166 gmx_fatal(FARGS, "Expanded ensemble not supported by MiMiC.");
170 gmx_fatal(FARGS, "Simulated tempering not supported by MiMiC.");
174 gmx_fatal(FARGS, "AWH not supported by MiMiC.");
176 if (replExParams.exchangeInterval > 0)
178 gmx_fatal(FARGS, "Replica exchange not supported by MiMiC.");
180 if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr)
182 gmx_fatal(FARGS, "Essential dynamics not supported by MiMiC.");
186 gmx_fatal(FARGS, "Interactive MD not supported by MiMiC.");
190 gmx_fatal(FARGS, "Multiple simulations not supported by MiMiC.");
192 if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](SimulatedAnnealing i) {
193 return i != SimulatedAnnealing::No;
196 gmx_fatal(FARGS, "Simulated annealing not supported by MiMiC.");
199 /* Settings for rerun */
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;
207 int nstglobalcomm = 1;
208 const bool bNS = true;
210 ObservablesReducer observablesReducer = observablesReducerBuilder->build();
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();
221 if (haveDDAtomOrdering(*cr))
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);
228 const SimulationGroups* groups = &top_global.groups;
230 auto* nonConstGlobalTopology = const_cast<gmx_mtop_t*>(&top_global);
231 nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(top_global);
234 initialize_lambdas(fplog,
238 ir->simtempvals->temperatures,
239 gmx::arrayRefFromArray(ir->opts.ref_t, ir->opts.ngtc),
241 &state_global->fep_state,
242 state_global->lambda);
244 const bool simulationsShareState = false;
245 gmx_mdoutf* outf = init_mdoutf(fplog,
256 StartingBehavior::NewSimulation,
257 simulationsShareState,
259 gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf),
263 mdoutf_get_fp_dhdl(outf),
265 StartingBehavior::NewSimulation,
266 simulationsShareState,
269 gstat = global_stat_init(ir);
271 /* Check for polarizable models and flexible constraints */
272 shellfc = init_shell_flexcon(fplog,
274 constr ? constr->numFlexibleConstraints() : 0,
276 haveDDAtomOrdering(*cr),
277 runScheduleWork->simulationWork.useGpuPme);
280 double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1);
281 if ((io > 2000) && MASTER(cr))
283 fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io);
287 if (haveDDAtomOrdering(*cr))
289 // Local state only becomes valid now.
290 dd_init_local_state(*cr->dd, state_global, state);
292 /* Distribute the charge groups over the nodes from the master node */
293 dd_partition_system(fplog,
317 state_change_natoms(state_global, state_global->natoms);
318 mdAlgorithmsSetupAtomData(cr, *ir, top_global, top, fr, &f, mdAtoms, constr, vsite, shellfc);
321 auto* mdatoms = mdAtoms->mdatoms();
323 // NOTE: The global state is no longer used at this point.
324 // But state_global is still used as temporary storage space for writing
325 // the global state to file and potentially for replica exchange.
326 // (Global topology should persist.)
328 update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
329 fr->longRangeNonbondeds->updateAfterPartition(*mdatoms);
331 if (ir->efep != FreeEnergyPerturbationType::No && ir->fepvals->nstdhdl != 0)
333 doFreeEnergyPerturbation = true;
336 int64_t step = ir->init_step;
337 int64_t step_rel = 0;
340 int cglo_flags = CGLO_GSTAT;
341 bool bSumEkinhOld = false;
342 t_vcm* vcm = nullptr;
343 compute_globals(gstat,
348 makeConstArrayRef(state->x),
349 makeConstArrayRef(state->v),
365 &observablesReducer);
366 // Clean up after pre-step use of compute_globals()
367 observablesReducer.markAsReadyToReduce();
372 fprintf(stderr, "starting MiMiC MD run '%s'\n\n", *(top_global.name));
373 if (mdrunOptions.verbose)
376 "Calculated time to finish depends on nsteps from "
377 "run input file,\nwhich may not correspond to the time "
378 "needed to process input trajectory.\n\n");
380 fprintf(fplog, "\n");
383 walltime_accounting_start_time(walltime_accounting);
384 wallcycle_start(wcycle, WallCycleCounter::Run);
385 print_start(fplog, cr, walltime_accounting, "mdrun");
387 /***********************************************************
391 ************************************************************/
398 "Simulations has constraints. Constraints will "
399 "be handled by CPMD.");
405 "MiMiC does not report kinetic energy, total energy, temperature, virial and "
408 auto stopHandler = stopHandlerBuilder->getStopHandlerMD(
409 compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]),
413 mdrunOptions.reproducible,
415 mdrunOptions.maximumHoursToRun,
420 walltime_accounting);
422 // we don't do counter resetting in rerun - finish will always be valid
423 walltime_accounting_set_valid_finish(walltime_accounting);
425 const DDBalanceRegionHandler ddBalanceRegionHandler(cr);
427 /* and stop now if we should */
428 isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps));
431 isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel == ir->nsteps));
432 wallcycle_start(wcycle, WallCycleCounter::Step);
438 MimicCommunicator::getCoords(state_global->x, state_global->natoms);
441 if (ir->efep != FreeEnergyPerturbationType::No)
443 state->lambda = currentLambdas(step, *(ir->fepvals), state_global->fep_state);
448 const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites);
449 if (constructVsites && haveDDAtomOrdering(*cr))
452 "Vsite recalculation with -rerun is not implemented with domain "
454 "use a single rank");
458 wallcycle_start(wcycle, WallCycleCounter::VsiteConstr);
459 vsite->construct(state->x, state->v, state->box, VSiteOperation::PositionsAndVelocities);
460 wallcycle_stop(wcycle, WallCycleCounter::VsiteConstr);
464 if (haveDDAtomOrdering(*cr))
466 /* Repartition the domain decomposition */
467 const bool bMasterState = true;
468 dd_partition_system(fplog,
488 mdrunOptions.verbose);
493 EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */
496 if (ir->efep != FreeEnergyPerturbationType::No)
498 update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]);
501 fr->longRangeNonbondeds->updateAfterPartition(*mdatoms);
503 force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES
504 | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 is solved
505 GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0));
509 /* Now is the time to relax the shells */
510 relax_shell_flexcon(fplog,
513 mdrunOptions.verbose,
525 state->x.arrayRefWithPadding(),
526 state->v.arrayRefWithPadding(),
533 fr->longRangeNonbondeds.get(),
542 ddBalanceRegionHandler);
546 /* The coordinates (x) are shifted (to get whole molecules)
548 * This is parallellized as well, and does communication too.
549 * Check comments in sim_util.c
552 gmx_edsam* ed = nullptr;
566 state->x.arrayRefWithPadding(),
579 fr->longRangeNonbondeds.get(),
580 GMX_FORCE_NS | force_flags,
581 ddBalanceRegionHandler);
584 /* Now we have the energies and forces corresponding to the
585 * coordinates at time t.
588 const bool isCheckpointingStep = false;
589 const bool doRerun = false;
590 const bool bSumEkinhOld = false;
591 do_md_trajectory_writing(fplog,
611 mdrunOptions.writeConfout,
615 stopHandler->setSignal();
618 const bool doInterSimSignal = false;
619 const bool doIntraSimSignal = true;
620 bool bSumEkinhOld = false;
621 t_vcm* vcm = nullptr;
622 SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal);
624 int cglo_flags = CGLO_GSTAT | CGLO_ENERGY;
625 compute_globals(gstat,
630 makeConstArrayRef(state->x),
631 makeConstArrayRef(state->v),
647 &observablesReducer);
651 gmx::HostVector<gmx::RVec> fglobal(top_global.natoms);
652 gmx::ArrayRef<gmx::RVec> ftemp;
653 gmx::ArrayRef<const gmx::RVec> flocal = f.view().force();
654 if (haveDDAtomOrdering(*cr))
656 ftemp = gmx::makeArrayRef(fglobal);
657 dd_collect_vec(cr->dd, state->ddp_count, state->ddp_count_cg_gl, state->cg_gl, flocal, ftemp);
661 ftemp = f.view().force();
666 MimicCommunicator::sendEnergies(enerd->term[F_EPOT]);
667 MimicCommunicator::sendForces(ftemp, state_global->natoms);
672 /* Note: this is OK, but there are some numerical precision issues with using the convergence of
673 the virial that should probably be addressed eventually. state->veta has better properies,
674 but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could
675 generate the new shake_vir, but test the veta value for convergence. This will take some thought. */
677 if (ir->efep != FreeEnergyPerturbationType::No)
679 /* Sum up the foreign energy and dhdl terms for md and sd.
680 Currently done every step so that dhdl is correct in the .edr */
681 accumulateKineticLambdaComponents(enerd, state->lambda, *ir->fepvals);
687 const bool bCalcEnerStep = true;
688 energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation,
695 PTCouplingArrays({ state->boxv,
696 state->nosehoover_xi,
697 state->nosehoover_vxi,
699 state->nhpres_vxi }),
707 const bool do_ene = true;
708 const bool do_log = true;
710 const bool do_dr = ir->nstdisreout != 0;
711 const bool do_or = ir->nstorireout != 0;
713 EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts));
714 energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf),
718 do_log ? fplog : nullptr,
724 if (do_per_step(step, ir->nstlog))
726 if (fflush(fplog) != 0)
728 gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?");
733 /* Print the remaining wall clock time for the run */
734 if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal()))
738 fprintf(stderr, "\n");
740 print_time(stderr, walltime_accounting, step, ir, cr);
743 cycles = wallcycle_stop(wcycle, WallCycleCounter::Step);
744 if (haveDDAtomOrdering(*cr) && wcycle)
746 dd_cycles_add(cr->dd, cycles, ddCyclStep);
749 /* increase the MD step number */
752 observablesReducer.markAsReadyToReduce();
754 /* End of main MD loop */
756 /* Closing TNG files can include compressing data. Therefore it is good to do that
757 * before stopping the time measurements. */
758 mdoutf_tng_close(outf);
760 /* Stop measuring walltime */
761 walltime_accounting_end_time(walltime_accounting);
765 MimicCommunicator::finalize();
768 if (!thisRankHasDuty(cr, DUTY_PME))
770 /* Tell the PME only node to finish */
771 gmx_pme_send_finish(cr);
776 done_shellfc(fplog, shellfc, step_rel);
778 walltime_accounting_set_nsteps_done(walltime_accounting, step_rel);