Merge branch 'origin/release-2020' into merge-2020-into-2021
[alexxy/gromacs.git] / src / gromacs / modularsimulator / modularsimulator.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2019,2020, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief Defines the modular simulator
37  *
38  * \author Pascal Merz <pascal.merz@me.com>
39  * \ingroup module_modularsimulator
40  */
41
42 #include "gmxpre.h"
43
44 #include "modularsimulator.h"
45
46 #include "gromacs/commandline/filenm.h"
47 #include "gromacs/domdec/domdec.h"
48 #include "gromacs/ewald/pme.h"
49 #include "gromacs/ewald/pme_load_balancing.h"
50 #include "gromacs/ewald/pme_pp.h"
51 #include "gromacs/gmxlib/nrnb.h"
52 #include "gromacs/listed_forces/listed_forces.h"
53 #include "gromacs/mdlib/checkpointhandler.h"
54 #include "gromacs/mdlib/constr.h"
55 #include "gromacs/mdlib/coupling.h"
56 #include "gromacs/mdlib/energyoutput.h"
57 #include "gromacs/mdlib/mdatoms.h"
58 #include "gromacs/mdlib/resethandler.h"
59 #include "gromacs/mdlib/update.h"
60 #include "gromacs/mdrun/replicaexchange.h"
61 #include "gromacs/mdrun/shellfc.h"
62 #include "gromacs/mdrunutility/handlerestart.h"
63 #include "gromacs/mdrunutility/printtime.h"
64 #include "gromacs/mdtypes/commrec.h"
65 #include "gromacs/mdtypes/fcdata.h"
66 #include "gromacs/mdtypes/forcerec.h"
67 #include "gromacs/mdtypes/inputrec.h"
68 #include "gromacs/mdtypes/mdatom.h"
69 #include "gromacs/mdtypes/mdrunoptions.h"
70 #include "gromacs/mdtypes/observableshistory.h"
71 #include "gromacs/nbnxm/nbnxm.h"
72 #include "gromacs/topology/mtop_util.h"
73 #include "gromacs/topology/topology.h"
74 #include "gromacs/utility/fatalerror.h"
75
76 #include "computeglobalselement.h"
77 #include "constraintelement.h"
78 #include "forceelement.h"
79 #include "parrinellorahmanbarostat.h"
80 #include "simulatoralgorithm.h"
81 #include "statepropagatordata.h"
82 #include "velocityscalingtemperaturecoupling.h"
83
84 namespace gmx
85 {
86 void ModularSimulator::run()
87 {
88     GMX_LOG(legacySimulatorData_->mdlog.info)
89             .asParagraph()
90             .appendText("Using the modular simulator.");
91
92     ModularSimulatorAlgorithmBuilder algorithmBuilder(compat::make_not_null(legacySimulatorData_),
93                                                       std::move(checkpointDataHolder_));
94     addIntegrationElements(&algorithmBuilder);
95     auto algorithm = algorithmBuilder.build();
96
97     while (const auto* task = algorithm.getNextTask())
98     {
99         // execute task
100         (*task)();
101     }
102 }
103
104 void ModularSimulator::addIntegrationElements(ModularSimulatorAlgorithmBuilder* builder)
105 {
106     if (legacySimulatorData_->inputrec->eI == eiMD)
107     {
108         // The leap frog integration algorithm
109         builder->add<ForceElement>();
110         builder->add<StatePropagatorData::Element>();
111         if (legacySimulatorData_->inputrec->etc == etcVRESCALE
112             || legacySimulatorData_->inputrec->etc == etcBERENDSEN)
113         {
114             builder->add<VelocityScalingTemperatureCoupling>(-1, UseFullStepKE::No,
115                                                              ReportPreviousStepConservedEnergy::No);
116         }
117         builder->add<Propagator<IntegrationStep::LeapFrog>>(legacySimulatorData_->inputrec->delta_t,
118                                                             RegisterWithThermostat::True,
119                                                             RegisterWithBarostat::True);
120         if (legacySimulatorData_->constr)
121         {
122             builder->add<ConstraintsElement<ConstraintVariable::Positions>>();
123         }
124         builder->add<ComputeGlobalsElement<ComputeGlobalsAlgorithm::LeapFrog>>();
125         builder->add<EnergyData::Element>();
126         if (legacySimulatorData_->inputrec->epc == epcPARRINELLORAHMAN)
127         {
128             builder->add<ParrinelloRahmanBarostat>(-1);
129         }
130     }
131     else if (legacySimulatorData_->inputrec->eI == eiVV)
132     {
133         // The velocity verlet integration algorithm
134         builder->add<ForceElement>();
135         builder->add<Propagator<IntegrationStep::VelocitiesOnly>>(
136                 0.5 * legacySimulatorData_->inputrec->delta_t, RegisterWithThermostat::False,
137                 RegisterWithBarostat::True);
138         if (legacySimulatorData_->constr)
139         {
140             builder->add<ConstraintsElement<ConstraintVariable::Velocities>>();
141         }
142         builder->add<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>>();
143         builder->add<StatePropagatorData::Element>();
144         if (legacySimulatorData_->inputrec->etc == etcVRESCALE
145             || legacySimulatorData_->inputrec->etc == etcBERENDSEN)
146         {
147             builder->add<VelocityScalingTemperatureCoupling>(
148                     0, UseFullStepKE::Yes, ReportPreviousStepConservedEnergy::Yes);
149         }
150         builder->add<Propagator<IntegrationStep::VelocityVerletPositionsAndVelocities>>(
151                 legacySimulatorData_->inputrec->delta_t, RegisterWithThermostat::True,
152                 RegisterWithBarostat::False);
153         if (legacySimulatorData_->constr)
154         {
155             builder->add<ConstraintsElement<ConstraintVariable::Positions>>();
156         }
157         builder->add<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>>();
158         builder->add<EnergyData::Element>();
159         if (legacySimulatorData_->inputrec->epc == epcPARRINELLORAHMAN)
160         {
161             builder->add<ParrinelloRahmanBarostat>(-1);
162         }
163     }
164     else
165     {
166         gmx_fatal(FARGS, "Integrator not implemented for the modular simulator.");
167     }
168 }
169
170 bool ModularSimulator::isInputCompatible(bool                             exitOnFailure,
171                                          const t_inputrec*                inputrec,
172                                          bool                             doRerun,
173                                          const gmx_mtop_t&                globalTopology,
174                                          const gmx_multisim_t*            ms,
175                                          const ReplicaExchangeParameters& replExParams,
176                                          const t_fcdata*                  fcd,
177                                          bool                             doEssentialDynamics,
178                                          bool                             doMembed)
179 {
180     auto conditionalAssert = [exitOnFailure](bool condition, const char* message) {
181         if (exitOnFailure)
182         {
183             GMX_RELEASE_ASSERT(condition, message);
184         }
185         return condition;
186     };
187
188     // GMX_USE_MODULAR_SIMULATOR allows to use modular simulator also for non-standard uses,
189     // such as the leap-frog integrator
190     const auto modularSimulatorExplicitlyTurnedOn = (getenv("GMX_USE_MODULAR_SIMULATOR") != nullptr);
191     // GMX_USE_MODULAR_SIMULATOR allows to use disable modular simulator for all uses,
192     // including the velocity-verlet integrator used by default
193     const auto modularSimulatorExplicitlyTurnedOff = (getenv("GMX_DISABLE_MODULAR_SIMULATOR") != nullptr);
194
195     GMX_RELEASE_ASSERT(
196             !(modularSimulatorExplicitlyTurnedOn && modularSimulatorExplicitlyTurnedOff),
197             "Cannot have both GMX_USE_MODULAR_SIMULATOR=ON and GMX_DISABLE_MODULAR_SIMULATOR=ON. "
198             "Unset one of the two environment variables to explicitly chose which simulator to "
199             "use, "
200             "or unset both to recover default behavior.");
201
202     GMX_RELEASE_ASSERT(
203             !(modularSimulatorExplicitlyTurnedOff && inputrec->eI == eiVV
204               && inputrec->epc == epcPARRINELLORAHMAN),
205             "Cannot use a Parrinello-Rahman barostat with md-vv and "
206             "GMX_DISABLE_MODULAR_SIMULATOR=ON, "
207             "as the Parrinello-Rahman barostat is not implemented in the legacy simulator. Unset "
208             "GMX_DISABLE_MODULAR_SIMULATOR or use a different pressure control algorithm.");
209
210     bool isInputCompatible = conditionalAssert(
211             inputrec->eI == eiMD || inputrec->eI == eiVV,
212             "Only integrators md and md-vv are supported by the modular simulator.");
213     isInputCompatible = isInputCompatible
214                         && conditionalAssert(inputrec->eI != eiMD || modularSimulatorExplicitlyTurnedOn,
215                                              "Set GMX_USE_MODULAR_SIMULATOR=ON to use the modular "
216                                              "simulator with integrator md.");
217     isInputCompatible =
218             isInputCompatible
219             && conditionalAssert(!doRerun, "Rerun is not supported by the modular simulator.");
220     isInputCompatible = isInputCompatible
221                         && conditionalAssert(inputrec->etc == etcNO || inputrec->etc == etcVRESCALE
222                                                      || inputrec->etc == etcBERENDSEN,
223                                              "Only v-rescale and Berendsen thermostat are "
224                                              "supported by the modular simulator.");
225     isInputCompatible =
226             isInputCompatible
227             && conditionalAssert(
228                        inputrec->epc == epcNO || inputrec->epc == epcPARRINELLORAHMAN,
229                        "Only Parrinello-Rahman barostat is supported by the modular simulator.");
230     isInputCompatible =
231             isInputCompatible
232             && conditionalAssert(
233                        !(inputrecNptTrotter(inputrec) || inputrecNphTrotter(inputrec)
234                          || inputrecNvtTrotter(inputrec)),
235                        "Legacy Trotter decomposition is not supported by the modular simulator.");
236     isInputCompatible = isInputCompatible
237                         && conditionalAssert(inputrec->efep == efepNO || inputrec->efep == efepYES
238                                                      || inputrec->efep == efepSLOWGROWTH,
239                                              "Expanded ensemble free energy calculation is not "
240                                              "supported by the modular simulator.");
241     isInputCompatible = isInputCompatible
242                         && conditionalAssert(!inputrec->bPull,
243                                              "Pulling is not supported by the modular simulator.");
244     isInputCompatible =
245             isInputCompatible
246             && conditionalAssert(inputrec->opts.ngacc == 1 && inputrec->opts.acc[0][XX] == 0.0
247                                          && inputrec->opts.acc[0][YY] == 0.0
248                                          && inputrec->opts.acc[0][ZZ] == 0.0 && inputrec->cos_accel == 0.0,
249                                  "Acceleration is not supported by the modular simulator.");
250     isInputCompatible =
251             isInputCompatible
252             && conditionalAssert(inputrec->opts.ngfrz == 1 && inputrec->opts.nFreeze[0][XX] == 0
253                                          && inputrec->opts.nFreeze[0][YY] == 0
254                                          && inputrec->opts.nFreeze[0][ZZ] == 0,
255                                  "Freeze groups are not supported by the modular simulator.");
256     isInputCompatible =
257             isInputCompatible
258             && conditionalAssert(
259                        inputrec->deform[XX][XX] == 0.0 && inputrec->deform[XX][YY] == 0.0
260                                && inputrec->deform[XX][ZZ] == 0.0 && inputrec->deform[YY][XX] == 0.0
261                                && inputrec->deform[YY][YY] == 0.0 && inputrec->deform[YY][ZZ] == 0.0
262                                && inputrec->deform[ZZ][XX] == 0.0 && inputrec->deform[ZZ][YY] == 0.0
263                                && inputrec->deform[ZZ][ZZ] == 0.0,
264                        "Deformation is not supported by the modular simulator.");
265     isInputCompatible =
266             isInputCompatible
267             && conditionalAssert(gmx_mtop_interaction_count(globalTopology, IF_VSITE) == 0,
268                                  "Virtual sites are not supported by the modular simulator.");
269     isInputCompatible = isInputCompatible
270                         && conditionalAssert(!inputrec->bDoAwh,
271                                              "AWH is not supported by the modular simulator.");
272     isInputCompatible =
273             isInputCompatible
274             && conditionalAssert(gmx_mtop_ftype_count(globalTopology, F_DISRES) == 0,
275                                  "Distance restraints are not supported by the modular simulator.");
276     isInputCompatible =
277             isInputCompatible
278             && conditionalAssert(
279                        gmx_mtop_ftype_count(globalTopology, F_ORIRES) == 0,
280                        "Orientation restraints are not supported by the modular simulator.");
281     isInputCompatible =
282             isInputCompatible
283             && conditionalAssert(ms == nullptr,
284                                  "Multi-sim are not supported by the modular simulator.");
285     isInputCompatible =
286             isInputCompatible
287             && conditionalAssert(replExParams.exchangeInterval == 0,
288                                  "Replica exchange is not supported by the modular simulator.");
289
290     int numEnsembleRestraintSystems;
291     if (fcd)
292     {
293         numEnsembleRestraintSystems = fcd->disres->nsystems;
294     }
295     else
296     {
297         auto distantRestraintEnsembleEnvVar = getenv("GMX_DISRE_ENSEMBLE_SIZE");
298         numEnsembleRestraintSystems =
299                 (ms != nullptr && distantRestraintEnsembleEnvVar != nullptr)
300                         ? static_cast<int>(strtol(distantRestraintEnsembleEnvVar, nullptr, 10))
301                         : 0;
302     }
303     isInputCompatible =
304             isInputCompatible
305             && conditionalAssert(numEnsembleRestraintSystems <= 1,
306                                  "Ensemble restraints are not supported by the modular simulator.");
307     isInputCompatible =
308             isInputCompatible
309             && conditionalAssert(!doSimulatedAnnealing(inputrec),
310                                  "Simulated annealing is not supported by the modular simulator.");
311     isInputCompatible =
312             isInputCompatible
313             && conditionalAssert(!inputrec->bSimTemp,
314                                  "Simulated tempering is not supported by the modular simulator.");
315     isInputCompatible = isInputCompatible
316                         && conditionalAssert(!inputrec->bExpanded,
317                                              "Expanded ensemble simulations are not supported by "
318                                              "the modular simulator.");
319     isInputCompatible =
320             isInputCompatible
321             && conditionalAssert(!doEssentialDynamics,
322                                  "Essential dynamics is not supported by the modular simulator.");
323     isInputCompatible = isInputCompatible
324                         && conditionalAssert(inputrec->eSwapCoords == eswapNO,
325                                              "Ion / water position swapping is not supported by "
326                                              "the modular simulator.");
327     isInputCompatible =
328             isInputCompatible
329             && conditionalAssert(!inputrec->bIMD,
330                                  "Interactive MD is not supported by the modular simulator.");
331     isInputCompatible =
332             isInputCompatible
333             && conditionalAssert(!doMembed,
334                                  "Membrane embedding is not supported by the modular simulator.");
335     // TODO: Change this to the boolean passed when we merge the user interface change for the GPU update.
336     isInputCompatible =
337             isInputCompatible
338             && conditionalAssert(
339                        getenv("GMX_FORCE_UPDATE_DEFAULT_GPU") == nullptr,
340                        "Integration on the GPU is not supported by the modular simulator.");
341     // Modular simulator is centered around NS updates
342     // TODO: think how to handle nstlist == 0
343     isInputCompatible = isInputCompatible
344                         && conditionalAssert(inputrec->nstlist != 0,
345                                              "Simulations without neighbor list update are not "
346                                              "supported by the modular simulator.");
347     isInputCompatible = isInputCompatible
348                         && conditionalAssert(!GMX_FAHCORE,
349                                              "GMX_FAHCORE not supported by the modular simulator.");
350
351     return isInputCompatible;
352 }
353
354 ModularSimulator::ModularSimulator(std::unique_ptr<LegacySimulatorData>      legacySimulatorData,
355                                    std::unique_ptr<ReadCheckpointDataHolder> checkpointDataHolder) :
356     legacySimulatorData_(std::move(legacySimulatorData)),
357     checkpointDataHolder_(std::move(checkpointDataHolder))
358 {
359     checkInputForDisabledFunctionality();
360 }
361
362 void ModularSimulator::checkInputForDisabledFunctionality()
363 {
364     isInputCompatible(true, legacySimulatorData_->inputrec, legacySimulatorData_->mdrunOptions.rerun,
365                       *legacySimulatorData_->top_global, legacySimulatorData_->ms,
366                       legacySimulatorData_->replExParams, legacySimulatorData_->fr->fcdata.get(),
367                       opt2bSet("-ei", legacySimulatorData_->nfile, legacySimulatorData_->fnm),
368                       legacySimulatorData_->membed != nullptr);
369     if (legacySimulatorData_->observablesHistory->edsamHistory)
370     {
371         gmx_fatal(FARGS,
372                   "The checkpoint is from a run with essential dynamics sampling, "
373                   "but the current run did not specify the -ei option. "
374                   "Either specify the -ei option to mdrun, or do not use this checkpoint file.");
375     }
376 }
377
378 } // namespace gmx