Apply re-formatting to C++ in src/ tree.
[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>(
115                     -1, UseFullStepKE::No, 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,
137                 RegisterWithThermostat::False,
138                 RegisterWithBarostat::True);
139         if (legacySimulatorData_->constr)
140         {
141             builder->add<ConstraintsElement<ConstraintVariable::Velocities>>();
142         }
143         builder->add<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>>();
144         builder->add<StatePropagatorData::Element>();
145         if (legacySimulatorData_->inputrec->etc == etcVRESCALE
146             || legacySimulatorData_->inputrec->etc == etcBERENDSEN)
147         {
148             builder->add<VelocityScalingTemperatureCoupling>(
149                     0, UseFullStepKE::Yes, ReportPreviousStepConservedEnergy::Yes);
150         }
151         builder->add<Propagator<IntegrationStep::VelocityVerletPositionsAndVelocities>>(
152                 legacySimulatorData_->inputrec->delta_t,
153                 RegisterWithThermostat::True,
154                 RegisterWithBarostat::False);
155         if (legacySimulatorData_->constr)
156         {
157             builder->add<ConstraintsElement<ConstraintVariable::Positions>>();
158         }
159         builder->add<ComputeGlobalsElement<ComputeGlobalsAlgorithm::VelocityVerlet>>();
160         builder->add<EnergyData::Element>();
161         if (legacySimulatorData_->inputrec->epc == epcPARRINELLORAHMAN)
162         {
163             builder->add<ParrinelloRahmanBarostat>(-1);
164         }
165     }
166     else
167     {
168         gmx_fatal(FARGS, "Integrator not implemented for the modular simulator.");
169     }
170 }
171
172 bool ModularSimulator::isInputCompatible(bool                             exitOnFailure,
173                                          const t_inputrec*                inputrec,
174                                          bool                             doRerun,
175                                          const gmx_mtop_t&                globalTopology,
176                                          const gmx_multisim_t*            ms,
177                                          const ReplicaExchangeParameters& replExParams,
178                                          const t_fcdata*                  fcd,
179                                          bool                             doEssentialDynamics,
180                                          bool                             doMembed)
181 {
182     auto conditionalAssert = [exitOnFailure](bool condition, const char* message) {
183         if (exitOnFailure)
184         {
185             GMX_RELEASE_ASSERT(condition, message);
186         }
187         return condition;
188     };
189
190     // GMX_USE_MODULAR_SIMULATOR allows to use modular simulator also for non-standard uses,
191     // such as the leap-frog integrator
192     const auto modularSimulatorExplicitlyTurnedOn = (getenv("GMX_USE_MODULAR_SIMULATOR") != nullptr);
193     // GMX_USE_MODULAR_SIMULATOR allows to use disable modular simulator for all uses,
194     // including the velocity-verlet integrator used by default
195     const auto modularSimulatorExplicitlyTurnedOff = (getenv("GMX_DISABLE_MODULAR_SIMULATOR") != nullptr);
196
197     GMX_RELEASE_ASSERT(
198             !(modularSimulatorExplicitlyTurnedOn && modularSimulatorExplicitlyTurnedOff),
199             "Cannot have both GMX_USE_MODULAR_SIMULATOR=ON and GMX_DISABLE_MODULAR_SIMULATOR=ON. "
200             "Unset one of the two environment variables to explicitly chose which simulator to "
201             "use, "
202             "or unset both to recover default behavior.");
203
204     GMX_RELEASE_ASSERT(
205             !(modularSimulatorExplicitlyTurnedOff && inputrec->eI == eiVV
206               && inputrec->epc == epcPARRINELLORAHMAN),
207             "Cannot use a Parrinello-Rahman barostat with md-vv and "
208             "GMX_DISABLE_MODULAR_SIMULATOR=ON, "
209             "as the Parrinello-Rahman barostat is not implemented in the legacy simulator. Unset "
210             "GMX_DISABLE_MODULAR_SIMULATOR or use a different pressure control algorithm.");
211
212     bool isInputCompatible = conditionalAssert(
213             inputrec->eI == eiMD || inputrec->eI == eiVV,
214             "Only integrators md and md-vv are supported by the modular simulator.");
215     isInputCompatible = isInputCompatible
216                         && conditionalAssert(inputrec->eI != eiMD || modularSimulatorExplicitlyTurnedOn,
217                                              "Set GMX_USE_MODULAR_SIMULATOR=ON to use the modular "
218                                              "simulator with integrator md.");
219     isInputCompatible =
220             isInputCompatible
221             && conditionalAssert(!doRerun, "Rerun is not supported by the modular simulator.");
222     isInputCompatible = isInputCompatible
223                         && conditionalAssert(inputrec->etc == etcNO || inputrec->etc == etcVRESCALE
224                                                      || inputrec->etc == etcBERENDSEN,
225                                              "Only v-rescale and Berendsen thermostat are "
226                                              "supported by the modular simulator.");
227     isInputCompatible =
228             isInputCompatible
229             && conditionalAssert(
230                        inputrec->epc == epcNO || inputrec->epc == epcPARRINELLORAHMAN,
231                        "Only Parrinello-Rahman barostat is supported by the modular simulator.");
232     isInputCompatible =
233             isInputCompatible
234             && conditionalAssert(
235                        !(inputrecNptTrotter(inputrec) || inputrecNphTrotter(inputrec)
236                          || inputrecNvtTrotter(inputrec)),
237                        "Legacy Trotter decomposition is not supported by the modular simulator.");
238     isInputCompatible = isInputCompatible
239                         && conditionalAssert(inputrec->efep == efepNO || inputrec->efep == efepYES
240                                                      || inputrec->efep == efepSLOWGROWTH,
241                                              "Expanded ensemble free energy calculation is not "
242                                              "supported by the modular simulator.");
243     isInputCompatible = isInputCompatible
244                         && conditionalAssert(!inputrec->bPull,
245                                              "Pulling is not supported by the modular simulator.");
246     isInputCompatible =
247             isInputCompatible
248             && conditionalAssert(inputrec->opts.ngacc == 1 && inputrec->opts.acc[0][XX] == 0.0
249                                          && inputrec->opts.acc[0][YY] == 0.0
250                                          && inputrec->opts.acc[0][ZZ] == 0.0 && inputrec->cos_accel == 0.0,
251                                  "Acceleration is not supported by the modular simulator.");
252     isInputCompatible =
253             isInputCompatible
254             && conditionalAssert(inputrec->opts.ngfrz == 1 && inputrec->opts.nFreeze[0][XX] == 0
255                                          && inputrec->opts.nFreeze[0][YY] == 0
256                                          && inputrec->opts.nFreeze[0][ZZ] == 0,
257                                  "Freeze groups are not supported by the modular simulator.");
258     isInputCompatible =
259             isInputCompatible
260             && conditionalAssert(
261                        inputrec->deform[XX][XX] == 0.0 && inputrec->deform[XX][YY] == 0.0
262                                && inputrec->deform[XX][ZZ] == 0.0 && inputrec->deform[YY][XX] == 0.0
263                                && inputrec->deform[YY][YY] == 0.0 && inputrec->deform[YY][ZZ] == 0.0
264                                && inputrec->deform[ZZ][XX] == 0.0 && inputrec->deform[ZZ][YY] == 0.0
265                                && inputrec->deform[ZZ][ZZ] == 0.0,
266                        "Deformation is not supported by the modular simulator.");
267     isInputCompatible =
268             isInputCompatible
269             && conditionalAssert(gmx_mtop_interaction_count(globalTopology, IF_VSITE) == 0,
270                                  "Virtual sites are not supported by the modular simulator.");
271     isInputCompatible = isInputCompatible
272                         && conditionalAssert(!inputrec->bDoAwh,
273                                              "AWH is not supported by the modular simulator.");
274     isInputCompatible =
275             isInputCompatible
276             && conditionalAssert(gmx_mtop_ftype_count(globalTopology, F_DISRES) == 0,
277                                  "Distance restraints are not supported by the modular simulator.");
278     isInputCompatible =
279             isInputCompatible
280             && conditionalAssert(
281                        gmx_mtop_ftype_count(globalTopology, F_ORIRES) == 0,
282                        "Orientation restraints are not supported by the modular simulator.");
283     isInputCompatible =
284             isInputCompatible
285             && conditionalAssert(ms == nullptr,
286                                  "Multi-sim are not supported by the modular simulator.");
287     isInputCompatible =
288             isInputCompatible
289             && conditionalAssert(replExParams.exchangeInterval == 0,
290                                  "Replica exchange is not supported by the modular simulator.");
291
292     int numEnsembleRestraintSystems;
293     if (fcd)
294     {
295         numEnsembleRestraintSystems = fcd->disres->nsystems;
296     }
297     else
298     {
299         auto distantRestraintEnsembleEnvVar = getenv("GMX_DISRE_ENSEMBLE_SIZE");
300         numEnsembleRestraintSystems =
301                 (ms != nullptr && distantRestraintEnsembleEnvVar != nullptr)
302                         ? static_cast<int>(strtol(distantRestraintEnsembleEnvVar, nullptr, 10))
303                         : 0;
304     }
305     isInputCompatible =
306             isInputCompatible
307             && conditionalAssert(numEnsembleRestraintSystems <= 1,
308                                  "Ensemble restraints are not supported by the modular simulator.");
309     isInputCompatible =
310             isInputCompatible
311             && conditionalAssert(!doSimulatedAnnealing(inputrec),
312                                  "Simulated annealing is not supported by the modular simulator.");
313     isInputCompatible =
314             isInputCompatible
315             && conditionalAssert(!inputrec->bSimTemp,
316                                  "Simulated tempering is not supported by the modular simulator.");
317     isInputCompatible = isInputCompatible
318                         && conditionalAssert(!inputrec->bExpanded,
319                                              "Expanded ensemble simulations are not supported by "
320                                              "the modular simulator.");
321     isInputCompatible =
322             isInputCompatible
323             && conditionalAssert(!doEssentialDynamics,
324                                  "Essential dynamics is not supported by the modular simulator.");
325     isInputCompatible = isInputCompatible
326                         && conditionalAssert(inputrec->eSwapCoords == eswapNO,
327                                              "Ion / water position swapping is not supported by "
328                                              "the modular simulator.");
329     isInputCompatible =
330             isInputCompatible
331             && conditionalAssert(!inputrec->bIMD,
332                                  "Interactive MD is not supported by the modular simulator.");
333     isInputCompatible =
334             isInputCompatible
335             && conditionalAssert(!doMembed,
336                                  "Membrane embedding is not supported by the modular simulator.");
337     // TODO: Change this to the boolean passed when we merge the user interface change for the GPU update.
338     isInputCompatible =
339             isInputCompatible
340             && conditionalAssert(
341                        getenv("GMX_FORCE_UPDATE_DEFAULT_GPU") == nullptr,
342                        "Integration on the GPU is not supported by the modular simulator.");
343     // Modular simulator is centered around NS updates
344     // TODO: think how to handle nstlist == 0
345     isInputCompatible = isInputCompatible
346                         && conditionalAssert(inputrec->nstlist != 0,
347                                              "Simulations without neighbor list update are not "
348                                              "supported by the modular simulator.");
349     isInputCompatible = isInputCompatible
350                         && conditionalAssert(!GMX_FAHCORE,
351                                              "GMX_FAHCORE not supported by the modular simulator.");
352
353     return isInputCompatible;
354 }
355
356 ModularSimulator::ModularSimulator(std::unique_ptr<LegacySimulatorData>      legacySimulatorData,
357                                    std::unique_ptr<ReadCheckpointDataHolder> checkpointDataHolder) :
358     legacySimulatorData_(std::move(legacySimulatorData)),
359     checkpointDataHolder_(std::move(checkpointDataHolder))
360 {
361     checkInputForDisabledFunctionality();
362 }
363
364 void ModularSimulator::checkInputForDisabledFunctionality()
365 {
366     isInputCompatible(true,
367                       legacySimulatorData_->inputrec,
368                       legacySimulatorData_->mdrunOptions.rerun,
369                       *legacySimulatorData_->top_global,
370                       legacySimulatorData_->ms,
371                       legacySimulatorData_->replExParams,
372                       legacySimulatorData_->fr->fcdata.get(),
373                       opt2bSet("-ei", legacySimulatorData_->nfile, legacySimulatorData_->fnm),
374                       legacySimulatorData_->membed != nullptr);
375     if (legacySimulatorData_->observablesHistory->edsamHistory)
376     {
377         gmx_fatal(FARGS,
378                   "The checkpoint is from a run with essential dynamics sampling, "
379                   "but the current run did not specify the -ei option. "
380                   "Either specify the -ei option to mdrun, or do not use this checkpoint file.");
381     }
382 }
383
384 } // namespace gmx