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