d35d731a15388b9b0683ea880fb63d4d7472e4f1
[alexxy/gromacs.git] / src / gromacs / modularsimulator / energyelement.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2019, 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 /*! \libinternal
36  * \brief Defines the microstate 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 "energyelement.h"
45
46 #include "gromacs/math/vec.h"
47 #include "gromacs/mdlib/compute_io.h"
48 #include "gromacs/mdlib/energyoutput.h"
49 #include "gromacs/mdlib/mdatoms.h"
50 #include "gromacs/mdlib/mdoutf.h"
51 #include "gromacs/mdlib/stat.h"
52 #include "gromacs/mdtypes/enerdata.h"
53 #include "gromacs/mdtypes/inputrec.h"
54 #include "gromacs/topology/topology.h"
55 #include "gromacs/utility/fatalerror.h"
56
57 #include "statepropagatordata.h"
58
59 struct pull_t;
60 class t_state;
61
62 namespace gmx
63 {
64 class Awh;
65
66 EnergyElement::EnergyElement(
67         StatePropagatorData *statePropagatorData,
68         const gmx_mtop_t    *globalTopology,
69         const t_inputrec    *inputrec,
70         const MDAtoms       *mdAtoms,
71         gmx_enerdata_t      *enerd,
72         gmx_ekindata_t      *ekind,
73         const Constraints   *constr,
74         FILE                *fplog,
75         t_fcdata            *fcd,
76         bool                 isMaster) :
77     isMaster_(isMaster),
78     energyWritingStep_(-1),
79     energyCalculationStep_(-1),
80     freeEnergyCalculationStep_(-1),
81     logWritingStep_(-1),
82     forceVirialStep_(-1),
83     shakeVirialStep_(-1),
84 #ifndef NDEBUG
85     totalVirialStep_(-1),
86     pressureStep_(-1),
87 #endif
88     statePropagatorData_(statePropagatorData),
89     inputrec_(inputrec),
90     top_global_(globalTopology),
91     mdAtoms_(mdAtoms),
92     enerd_(enerd),
93     ekind_(ekind),
94     constr_(constr),
95     fplog_(fplog),
96     fcd_(fcd),
97     groups_(&globalTopology->groups)
98 {
99     clear_mat(forceVirial_);
100     clear_mat(shakeVirial_);
101     clear_mat(totalVirial_);
102     clear_mat(pressure_);
103     clear_rvec(muTot_);
104
105     // TODO: If energy history is re-introduced, it should probably be initialized here.
106 }
107
108 void EnergyElement::scheduleTask(
109         Step step, Time time, const RegisterRunFunctionPtr &registerRunFunction)
110 {
111     if (!isMaster_)
112     {
113         return;
114     }
115     auto writeEnergy                 = energyWritingStep_ == step;
116     auto isEnergyCalculationStep     = energyCalculationStep_ == step;
117     auto isFreeEnergyCalculationStep = freeEnergyCalculationStep_ == step;
118     if (isEnergyCalculationStep || writeEnergy)
119     {
120         (*registerRunFunction)(
121                 std::make_unique<SimulatorRunFunction>(
122                         [this, time, isEnergyCalculationStep, isFreeEnergyCalculationStep]() {
123                             doStep(time, isEnergyCalculationStep, isFreeEnergyCalculationStep);
124                         }));
125     }
126     else
127     {
128         (*registerRunFunction)(
129                 std::make_unique<SimulatorRunFunction>(
130                         [this]() { energyOutput_->recordNonEnergyStep(); }));
131     }
132 }
133
134 void EnergyElement::elementTeardown()
135 {
136     if (inputrec_->nstcalcenergy > 0 && isMaster_)
137     {
138         energyOutput_->printAverages(fplog_, groups_);
139     }
140 }
141
142 void EnergyElement::trajectoryWriterSetup(gmx_mdoutf *outf)
143 {
144     pull_t *pull_work = nullptr;
145     energyOutput_ = std::make_unique<EnergyOutput>(
146                 mdoutf_get_fp_ene(outf), top_global_,
147                 inputrec_, pull_work, mdoutf_get_fp_dhdl(outf), false);
148
149     if (!isMaster_)
150     {
151         return;
152     }
153
154     // TODO: This probably doesn't really belong here...
155     //       but we have all we need in this element,
156     //       so we'll leave it here for now!
157     double io = compute_io(inputrec_, top_global_->natoms, *groups_,
158                            energyOutput_->numEnergyTerms(), 1);
159     if ((io > 2000) && isMaster_)
160     {
161         fprintf(stderr,
162                 "\nWARNING: This run will generate roughly %.0f Mb of data\n\n",
163                 io);
164     }
165     if (!inputrec_->bContinuation)
166     {
167         real temp = enerd_->term[F_TEMP];
168         if (inputrec_->eI != eiVV)
169         {
170             /* Result of Ekin averaged over velocities of -half
171              * and +half step, while we only have -half step here.
172              */
173             temp *= 2;
174         }
175         fprintf(fplog_, "Initial temperature: %g K\n", temp);
176     }
177 }
178
179 ITrajectoryWriterCallbackPtr EnergyElement::registerTrajectoryWriterCallback(TrajectoryEvent event)
180 {
181     if (event == TrajectoryEvent::energyWritingStep && isMaster_)
182     {
183         return std::make_unique<ITrajectoryWriterCallback>(
184                 [this](gmx_mdoutf *mdoutf, Step step, Time time)
185                 {write(mdoutf, step, time); });
186     }
187     return nullptr;
188 }
189
190 SignallerCallbackPtr EnergyElement::registerTrajectorySignallerCallback(gmx::TrajectoryEvent event)
191 {
192     if (event == TrajectoryEvent::energyWritingStep)
193     {
194         return std::make_unique<SignallerCallback>(
195                 [this](Step step, Time){energyWritingStep_ = step; });
196     }
197     return nullptr;
198 }
199
200 SignallerCallbackPtr EnergyElement::registerEnergyCallback(EnergySignallerEvent event)
201 {
202     if (event == EnergySignallerEvent::energyCalculationStep)
203     {
204         return std::make_unique<SignallerCallback>(
205                 [this](Step step, Time) {energyCalculationStep_ = step; });
206     }
207     if (event == EnergySignallerEvent::freeEnergyCalculationStep)
208     {
209         return std::make_unique<SignallerCallback>(
210                 [this](Step step, Time){freeEnergyCalculationStep_ = step; });
211     }
212     return nullptr;
213
214 }
215
216 SignallerCallbackPtr EnergyElement::registerLoggingCallback()
217 {
218     return std::make_unique<SignallerCallback>(
219             [this](Step step, Time){logWritingStep_ = step; });
220 }
221
222 void EnergyElement::doStep(
223         Time time,
224         bool isEnergyCalculationStep,
225         bool isFreeEnergyCalculationStep)
226 {
227     enerd_->term[F_ETOT] = enerd_->term[F_EPOT] + enerd_->term[F_EKIN];
228     // All the state is used for is turned off for now (free energy, temperature / pressure coupling)
229     t_state *localState = nullptr;
230     energyOutput_->addDataAtEnergyStep(
231             isFreeEnergyCalculationStep, isEnergyCalculationStep,
232             time, mdAtoms_->mdatoms()->tmass, enerd_, localState,
233             inputrec_->fepvals, inputrec_->expandedvals,
234             statePropagatorData_->previousBox(),
235             shakeVirial_, forceVirial_, totalVirial_, pressure_,
236             ekind_, muTot_, constr_);
237 }
238
239 void EnergyElement::write(gmx_mdoutf *outf, Step step, Time time)
240 {
241     // This gets called by the trajectory writer, which means that
242     // we only write to log when writing energy.
243     // TODO: Think if we need to change that, i.e. writing to log without
244     //       writing to file.
245
246     auto writeLog = logWritingStep_ == step;
247     if (writeLog)
248     {
249         energyOutput_->printHeader(fplog_, step, time);
250     }
251
252     bool do_dr  = do_per_step(step, inputrec_->nstdisreout);
253     bool do_or  = do_per_step(step, inputrec_->nstorireout);
254
255     // energyOutput_->printAnnealingTemperatures(writeLog ? fplog_ : nullptr, groups_, &(inputrec_->opts));
256     Awh *awh = nullptr;
257     energyOutput_->printStepToEnergyFile(
258             mdoutf_get_fp_ene(outf), true, do_dr, do_or,
259             writeLog ? fplog_ : nullptr, step, time, fcd_, awh);
260 }
261
262 void EnergyElement::addToForceVirial(const tensor virial, Step step)
263 {
264     if (step > forceVirialStep_)
265     {
266         forceVirialStep_ = step;
267         clear_mat(forceVirial_);
268     }
269     m_add(forceVirial_, virial, forceVirial_);
270 }
271
272 void EnergyElement::addToConstraintVirial(const tensor virial, Step step)
273 {
274     if (step > shakeVirialStep_)
275     {
276         shakeVirialStep_ = step;
277         clear_mat(shakeVirial_);
278     }
279     m_add(shakeVirial_, virial, shakeVirial_);
280 }
281
282 rvec* EnergyElement::forceVirial(Step gmx_unused step)
283 {
284     GMX_ASSERT(step >= forceVirialStep_ || forceVirialStep_ == -1,
285                "Asked for force virial of previous step.");
286     return forceVirial_;
287 }
288
289 rvec* EnergyElement::constraintVirial(Step gmx_unused step)
290 {
291     GMX_ASSERT(step >= shakeVirialStep_ || shakeVirialStep_ == -1,
292                "Asked for constraint virial of previous step.");
293     return shakeVirial_;
294 }
295
296 rvec* EnergyElement::totalVirial(Step gmx_unused step)
297 {
298     GMX_ASSERT(step >= totalVirialStep_ || totalVirialStep_ == -1,
299                "Asked for total virial of previous step.");
300     return totalVirial_;
301 }
302
303 rvec* EnergyElement::pressure(Step gmx_unused step)
304 {
305     GMX_ASSERT(step >= pressureStep_ || pressureStep_ == -1,
306                "Asked for pressure of previous step.");
307     return pressure_;
308 }
309
310 real* EnergyElement::muTot()
311 {
312     return muTot_;
313 }
314
315 gmx_enerdata_t* EnergyElement::enerdata()
316 {
317     return enerd_;
318 }
319
320 gmx_ekindata_t* EnergyElement::ekindata()
321 {
322     return ekind_;
323 }
324
325 } // namespace gmx