Revert "CUDA nightly fail: Dirty hack"
[alexxy/gromacs.git] / src / gromacs / modularsimulator / forceelement.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 force element for 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 "forceelement.h"
45
46 #include "gromacs/domdec/mdsetup.h"
47 #include "gromacs/math/vectypes.h"
48 #include "gromacs/mdlib/constr.h"
49 #include "gromacs/mdlib/force.h"
50 #include "gromacs/mdlib/force_flags.h"
51 #include "gromacs/mdlib/mdatoms.h"
52 #include "gromacs/mdrun/shellfc.h"
53 #include "gromacs/mdtypes/forcebuffers.h"
54 #include "gromacs/mdtypes/inputrec.h"
55 #include "gromacs/mdtypes/mdatom.h"
56 #include "gromacs/mdtypes/mdrunoptions.h"
57 #include "gromacs/mdtypes/simulation_workload.h"
58 #include "gromacs/pbcutil/pbc.h"
59
60 #include "energydata.h"
61 #include "freeenergyperturbationdata.h"
62 #include "modularsimulator.h"
63 #include "simulatoralgorithm.h"
64 #include "statepropagatordata.h"
65
66 struct gmx_edsam;
67 struct gmx_enfrot;
68 struct gmx_multisim_t;
69 class history_t;
70
71 namespace gmx
72 {
73 ForceElement::ForceElement(StatePropagatorData*        statePropagatorData,
74                            EnergyData*                 energyData,
75                            FreeEnergyPerturbationData* freeEnergyPerturbationData,
76                            bool                        isVerbose,
77                            bool                        isDynamicBox,
78                            FILE*                       fplog,
79                            const t_commrec*            cr,
80                            const t_inputrec*           inputrec,
81                            const MDAtoms*              mdAtoms,
82                            t_nrnb*                     nrnb,
83                            t_forcerec*                 fr,
84
85                            gmx_wallcycle*         wcycle,
86                            MdrunScheduleWorkload* runScheduleWork,
87                            VirtualSitesHandler*   vsite,
88                            ImdSession*            imdSession,
89                            pull_t*                pull_work,
90                            Constraints*           constr,
91                            const gmx_mtop_t*      globalTopology,
92                            gmx_enfrot*            enforcedRotation) :
93     shellfc_(init_shell_flexcon(fplog,
94                                 globalTopology,
95                                 constr ? constr->numFlexibleConstraints() : 0,
96                                 inputrec->nstcalcenergy,
97                                 DOMAINDECOMP(cr),
98                                 runScheduleWork->simulationWork.useGpuPme)),
99     doShellFC_(shellfc_ != nullptr),
100     nextNSStep_(-1),
101     nextEnergyCalculationStep_(-1),
102     nextVirialCalculationStep_(-1),
103     nextFreeEnergyCalculationStep_(-1),
104     statePropagatorData_(statePropagatorData),
105     energyData_(energyData),
106     freeEnergyPerturbationData_(freeEnergyPerturbationData),
107     localTopology_(nullptr),
108     isDynamicBox_(isDynamicBox),
109     isVerbose_(isVerbose),
110     nShellRelaxationSteps_(0),
111     ddBalanceRegionHandler_(cr),
112     lambda_(),
113     fplog_(fplog),
114     cr_(cr),
115     inputrec_(inputrec),
116     mdAtoms_(mdAtoms),
117     nrnb_(nrnb),
118     wcycle_(wcycle),
119     fr_(fr),
120     vsite_(vsite),
121     imdSession_(imdSession),
122     pull_work_(pull_work),
123     runScheduleWork_(runScheduleWork),
124     constr_(constr),
125     enforcedRotation_(enforcedRotation)
126 {
127     lambda_.fill(0);
128
129     if (doShellFC_ && !DOMAINDECOMP(cr))
130     {
131         // This was done in mdAlgorithmsSetupAtomData(), but shellfc
132         // won't be available outside this element.
133         make_local_shells(cr, mdAtoms->mdatoms(), shellfc_);
134     }
135 }
136
137 void ForceElement::scheduleTask(Step step, Time time, const RegisterRunFunction& registerRunFunction)
138 {
139     unsigned int flags =
140             (GMX_FORCE_STATECHANGED | GMX_FORCE_ALLFORCES | (isDynamicBox_ ? GMX_FORCE_DYNAMICBOX : 0)
141              | (nextVirialCalculationStep_ == step ? GMX_FORCE_VIRIAL : 0)
142              | (nextEnergyCalculationStep_ == step ? GMX_FORCE_ENERGY : 0)
143              | (nextFreeEnergyCalculationStep_ == step ? GMX_FORCE_DHDL : 0)
144              | (!doShellFC_ && nextNSStep_ == step ? GMX_FORCE_NS : 0));
145
146     registerRunFunction([this, step, time, flags]() {
147         if (doShellFC_)
148         {
149             run<true>(step, time, flags);
150         }
151         else
152         {
153             run<false>(step, time, flags);
154         }
155     });
156 }
157
158 void ForceElement::elementSetup()
159 {
160     GMX_ASSERT(localTopology_, "Setup called before local topology was set.");
161 }
162
163 template<bool doShellFC>
164 void ForceElement::run(Step step, Time time, unsigned int flags)
165 {
166     // Disabled functionality
167     gmx_multisim_t* ms = nullptr;
168
169
170     if (!DOMAINDECOMP(cr_) && (flags & GMX_FORCE_NS) && inputrecDynamicBox(inputrec_))
171     {
172         // TODO: Correcting the box is done in DomDecHelper (if using DD) or here (non-DD simulations).
173         //       Think about unifying this responsibility, could this be done in one place?
174         auto box = statePropagatorData_->box();
175         correct_box(fplog_, step, box);
176     }
177
178     /* The coordinates (x) are shifted (to get whole molecules)
179      * in do_force.
180      * This is parallelized as well, and does communication too.
181      * Check comments in sim_util.c
182      */
183     auto       x      = statePropagatorData_->positionsView();
184     auto&      forces = statePropagatorData_->forcesView();
185     auto       box    = statePropagatorData_->constBox();
186     history_t* hist   = nullptr; // disabled
187
188     tensor force_vir = { { 0 } };
189     // TODO: Make lambda const (needs some adjustments in lower force routines)
190     ArrayRef<real> lambda =
191             freeEnergyPerturbationData_ ? freeEnergyPerturbationData_->lambdaView() : lambda_;
192
193     if (doShellFC)
194     {
195         auto v = statePropagatorData_->velocitiesView();
196
197         relax_shell_flexcon(
198                 fplog_, cr_, ms, isVerbose_, enforcedRotation_, step, inputrec_, imdSession_,
199                 pull_work_, step == nextNSStep_, static_cast<int>(flags), localTopology_, constr_,
200                 energyData_->enerdata(), statePropagatorData_->localNumAtoms(), x, v, box, lambda,
201                 hist, &forces, force_vir, mdAtoms_->mdatoms(), nrnb_, wcycle_, shellfc_, fr_,
202                 runScheduleWork_, time, energyData_->muTot(), vsite_, ddBalanceRegionHandler_);
203         nShellRelaxationSteps_++;
204     }
205     else
206     {
207         // Disabled functionality
208         Awh*       awh = nullptr;
209         gmx_edsam* ed  = nullptr;
210
211         do_force(fplog_, cr_, ms, inputrec_, awh, enforcedRotation_, imdSession_, pull_work_, step,
212                  nrnb_, wcycle_, localTopology_, box, x, hist, &forces, force_vir,
213                  mdAtoms_->mdatoms(), energyData_->enerdata(), lambda, fr_, runScheduleWork_, vsite_,
214                  energyData_->muTot(), time, ed, static_cast<int>(flags), ddBalanceRegionHandler_);
215     }
216     energyData_->addToForceVirial(force_vir, step);
217 }
218
219 void ForceElement::elementTeardown()
220 {
221     if (doShellFC_)
222     {
223         done_shellfc(fplog_, shellfc_, nShellRelaxationSteps_);
224     }
225 }
226
227 void ForceElement::setTopology(const gmx_localtop_t* top)
228 {
229     localTopology_ = top;
230 }
231
232 std::optional<SignallerCallback> ForceElement::registerNSCallback()
233 {
234     return [this](Step step, Time gmx_unused time) { this->nextNSStep_ = step; };
235 }
236
237 std::optional<SignallerCallback> ForceElement::registerEnergyCallback(EnergySignallerEvent event)
238 {
239     if (event == EnergySignallerEvent::EnergyCalculationStep)
240     {
241         return [this](Step step, Time /*unused*/) { nextEnergyCalculationStep_ = step; };
242     }
243     if (event == EnergySignallerEvent::VirialCalculationStep)
244     {
245         return [this](Step step, Time /*unused*/) { nextVirialCalculationStep_ = step; };
246     }
247     if (event == EnergySignallerEvent::FreeEnergyCalculationStep)
248     {
249         return [this](Step step, Time /*unused*/) { nextFreeEnergyCalculationStep_ = step; };
250     }
251     return std::nullopt;
252 }
253
254 ISimulatorElement*
255 ForceElement::getElementPointerImpl(LegacySimulatorData*                    legacySimulatorData,
256                                     ModularSimulatorAlgorithmBuilderHelper* builderHelper,
257                                     StatePropagatorData*                    statePropagatorData,
258                                     EnergyData*                             energyData,
259                                     FreeEnergyPerturbationData* freeEnergyPerturbationData,
260                                     GlobalCommunicationHelper gmx_unused* globalCommunicationHelper)
261 {
262     const bool isVerbose    = legacySimulatorData->mdrunOptions.verbose;
263     const bool isDynamicBox = inputrecDynamicBox(legacySimulatorData->inputrec);
264     return builderHelper->storeElement(std::make_unique<ForceElement>(
265             statePropagatorData, energyData, freeEnergyPerturbationData, isVerbose, isDynamicBox,
266             legacySimulatorData->fplog, legacySimulatorData->cr, legacySimulatorData->inputrec,
267             legacySimulatorData->mdAtoms, legacySimulatorData->nrnb, legacySimulatorData->fr,
268             legacySimulatorData->wcycle, legacySimulatorData->runScheduleWork, legacySimulatorData->vsite,
269             legacySimulatorData->imdSession, legacySimulatorData->pull_work, legacySimulatorData->constr,
270             legacySimulatorData->top_global, legacySimulatorData->enforcedRotation));
271 }
272 } // namespace gmx