Allow using COM of previous step as PBC reference
[alexxy/gromacs.git] / src / gromacs / mdtypes / state.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017,2018, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37
38 /*! \file
39  *
40  * \brief
41  * This file contains the definition of the microstate of the simulated system
42  *
43  * History of observables that needs to be checkpointed should be stored
44  * in ObservablesHistory.
45  * The state of the mdrun machinery that needs to be checkpointed is also
46  * stored elsewhere.
47  *
48  * \author Berk Hess
49  *
50  * \inlibraryapi
51  * \ingroup module_mdtypes
52  */
53
54 #ifndef GMX_MDTYPES_STATE_H
55 #define GMX_MDTYPES_STATE_H
56
57 #include <array>
58 #include <memory>
59 #include <vector>
60
61 #include "gromacs/gpu_utils/hostallocator.h"
62 #include "gromacs/math/paddedvector.h"
63 #include "gromacs/math/vectypes.h"
64 #include "gromacs/mdtypes/md_enums.h"
65 #include "gromacs/utility/arrayref.h"
66 #include "gromacs/utility/basedefinitions.h"
67 #include "gromacs/utility/real.h"
68
69 struct t_inputrec;
70
71 namespace gmx
72 {
73 struct AwhHistory;
74 }
75
76 /*
77  * The t_state struct should contain all the (possibly) non-static
78  * information required to define the state of the system.
79  * Currently the random seeds for SD and BD are missing.
80  */
81
82 /* \brief Enum for all entries in \p t_state
83  *
84  * These enums are used in flags as (1<<est...).
85  * The order of these enums should not be changed,
86  * since that affects the checkpoint (.cpt) file format.
87  */
88 enum {
89     estLAMBDA,
90     estBOX, estBOX_REL, estBOXV, estPRES_PREV, estNH_XI,  estTHERM_INT,
91     estX,   estV,       estSDX_NOTSUPPORTED,  estCGP,
92     estLD_RNG_NOTSUPPORTED, estLD_RNGI_NOTSUPPORTED,
93     estDISRE_INITF, estDISRE_RM3TAV,
94     estORIRE_INITF, estORIRE_DTAV,
95     estSVIR_PREV, estNH_VXI, estVETA, estVOL0, estNHPRES_XI, estNHPRES_VXI, estFVIR_PREV,
96     estFEPSTATE, estMC_RNG_NOTSUPPORTED, estMC_RNGI_NOTSUPPORTED,
97     estBAROS_INT, estPREVSTEPCOM,
98     estNR
99 };
100
101 //! \brief The names of the state entries, defined in src/gmxlib/checkpoint.c
102 extern const char *est_names[estNR];
103
104 /*! \libinternal \brief History information for NMR distance and orientation restraints
105  *
106  * Often this is only used for reporting observables, and thus should not
107  * actually be part of the microstate. But with time-dependent restraining
108  * they are actually part of the (non-Markovian) microstate.
109  * \todo Rename this with a more descriptive name.
110  */
111 class history_t
112 {
113     public:
114         history_t();
115
116         real  disre_initf;  //!< The scaling factor for initializing the time av.
117         int   ndisrepairs;  //!< The number of distance restraints
118         real *disre_rm3tav; //!< The r^-3 time averaged pair distances
119         real  orire_initf;  //!< The scaling factor for initializing the time av.
120         int   norire_Dtav;  //!< The number of matrix element in dtav (npair*5)
121         real *orire_Dtav;   //!< The time averaged orientation tensors
122 };
123
124 /*! \libinternal \brief Struct used for checkpointing only
125  *
126  * This struct would not be required with unlimited precision.
127  * But because of limited precision, the COM motion removal implementation
128  * can cause the kinetic energy in the MD loop to differ by a few bits from
129  * the kinetic energy one would determine from state.v.
130  */
131 class ekinstate_t
132 {
133     public:
134         ekinstate_t();
135
136         gmx_bool             bUpToDate;      //!< Test if all data is up to date
137         int                  ekin_n;         //!< The number of tensors
138         tensor              *ekinh;          //!< Half step Ekin, size \p ekin_n
139         tensor              *ekinf;          //!< Full step Ekin, size \p ekin_n
140         tensor              *ekinh_old;      //!< Half step Ekin of the previous step, size \p ekin_n
141         tensor               ekin_total;     //!< Total kinetic energy
142         std::vector<double>  ekinscalef_nhc; //!< Nose-Hoover Ekin scaling factors for full step Ekin
143         std::vector<double>  ekinscaleh_nhc; //!< Nose-Hoover Ekin scaling factors for half step Ekin
144         std::vector<double>  vscale_nhc;     //!< Nose-Hoover velocity scaling factors
145         real                 dekindl;        //!< dEkin/dlambda, with free-energy
146         real                 mvcos;          //!< Cosine(z) component of the momentum, for viscosity calculations
147 };
148
149 /*! \brief Free-energy sampling history struct
150  *
151  * \todo Split out into microstate and observables history.
152  */
153 typedef struct df_history_t
154 {
155     int      nlambda;        //!< total number of lambda states - for history
156
157     gmx_bool bEquil;         //!< Have we reached equilibration
158     int     *n_at_lam;       //!< number of points observed at each lambda
159     real    *wl_histo;       //!< histogram for WL flatness determination
160     real     wl_delta;       //!< current wang-landau delta
161
162     real    *sum_weights;    //!< weights of the states
163     real    *sum_dg;         //!< free energies of the states -- not actually used for weighting, but informational
164     real    *sum_minvar;     //!< corrections to weights for minimum variance
165     real    *sum_variance;   //!< variances of the states
166
167     real   **accum_p;        //!< accumulated bennett weights for n+1
168     real   **accum_m;        //!< accumulated bennett weights for n-1
169     real   **accum_p2;       //!< accumulated squared bennett weights for n+1
170     real   **accum_m2;       //!< accumulated squared bennett weights for n-1
171
172     real   **Tij;            //!< transition matrix
173     real   **Tij_empirical;  //!< Empirical transition matrix
174
175 } df_history_t;
176
177
178 /*! \brief The microstate of the system
179  *
180  * The global state will contain complete data for all used entries.
181  * The local state with domain decomposition will have partial entries
182  * for which \p stateEntryIsAtomProperty() is true. Some entries that
183  * are used in the global state might not be present in the local state.
184  * \todo Move pure observables history to ObservablesHistory.
185  */
186 class t_state
187 {
188     public:
189         t_state();
190
191         // All things public
192         int                        natoms;         //!< Number of atoms, local + non-local; this is the size of \p x, \p v and \p cg_p, when used
193         int                        ngtc;           //!< The number of temperature coupling groups
194         int                        nnhpres;        //!< The NH-chain length for the MTTK barostat
195         int                        nhchainlength;  //!< The NH-chain length for temperature coupling
196         int                        flags;          //!< Set of bit-flags telling which entries are present, see enum at the top of the file
197         int                        fep_state;      //!< indicates which of the alchemical states we are in
198         std::array<real, efptNR>   lambda;         //!< Free-energy lambda vector
199         matrix                     box;            //!< Matrix of box vectors
200         matrix                     box_rel;        //!< Relative box vectors to preserve box shape
201         matrix                     boxv;           //!< Box velocities for Parrinello-Rahman P-coupling
202         matrix                     pres_prev;      //!< Pressure of the previous step for pcoupl
203         matrix                     svir_prev;      //!< Shake virial for previous step for pcoupl
204         matrix                     fvir_prev;      //!< Force virial of the previous step for pcoupl
205         std::vector<double>        nosehoover_xi;  //!< Nose-Hoover coordinates (ngtc)
206         std::vector<double>        nosehoover_vxi; //!< Nose-Hoover velocities (ngtc)
207         std::vector<double>        nhpres_xi;      //!< Pressure Nose-Hoover coordinates
208         std::vector<double>        nhpres_vxi;     //!< Pressure Nose-Hoover velocities
209         std::vector<double>        therm_integral; //!< Work exterted N-H/V-rescale T-coupling (ngtc)
210         double                     baros_integral; //!< For Berendsen P-coupling conserved quantity
211         real                       veta;           //!< Trotter based isotropic P-coupling
212         real                       vol0;           //!< Initial volume,required for computing MTTK conserved quantity
213         gmx::HostVector<gmx::RVec> x;              //!< The coordinates (natoms)
214         PaddedRVecVector           v;              //!< The velocities (natoms)
215         PaddedRVecVector           cg_p;           //!< p vector for conjugate gradient minimization
216
217         ekinstate_t                ekinstate;      //!< The state of the kinetic energy
218
219         /* History for special algorithms, should be moved to a history struct */
220         history_t                         hist;            //!< Time history for restraints
221         df_history_t                     *dfhist;          //!< Free-energy history for free energy analysis
222         std::shared_ptr<gmx::AwhHistory>  awhHistory;      //!< Accelerated weight histogram history
223
224         int                               ddp_count;       //!< The DD partitioning count for this state
225         int                               ddp_count_cg_gl; //!< The DD partitioning count for index_gl
226         std::vector<int>                  cg_gl;           //!< The global cg number of the local cgs
227
228         std::vector<double>               com_prev_step;   //!< The COM of the previous step of each pull group
229 };
230
231 #ifndef DOXYGEN
232 /* We don't document the structs below, as they don't belong here.
233  * TODO: Move the next two structs out of state.h.
234  */
235
236 typedef struct t_extmass
237 {
238     double *Qinv;  /* inverse mass of thermostat -- computed from inputs, but a good place to store */
239     double *QPinv; /* inverse mass of thermostat for barostat -- computed from inputs, but a good place to store */
240     double  Winv;  /* Pressure mass inverse -- computed, not input, but a good place to store. Need to make a matrix later */
241     tensor  Winvm; /* inverse pressure mass tensor, computed       */
242 } t_extmass;
243
244
245 typedef struct
246 {
247     real    veta;
248     double  rscale;
249     double  vscale;
250     double  rvscale;
251     double  alpha;
252     double *vscale_nhc;
253 } t_vetavars;
254
255 #endif // DOXYGEN
256
257 //! Resizes the T- and P-coupling state variables
258 void init_gtc_state(t_state *state, int ngtc, int nnhpres, int nhchainlength);
259
260 //! Change the number of atoms represented by this state, allocating memory as needed.
261 void state_change_natoms(t_state *state, int natoms);
262
263 //! Allocates memory for free-energy history
264 void init_dfhist_state(t_state *state, int dfhistNumLambda);
265
266 /*! \brief Compares two states, write the differences to stdout */
267 void comp_state(const t_state *st1, const t_state *st2, gmx_bool bRMSD, real ftol, real abstol);
268
269 /*! \brief Allocates an rvec pointer and copy the contents of v to it */
270 rvec *makeRvecArray(gmx::ArrayRef<const gmx::RVec> v,
271                     gmx::index                     n);
272
273 /*! \brief Determine the relative box components
274  *
275  * Set box_rel e.g. used in mdrun state, used to preserve the box shape
276  * \param[in]    ir      Input record
277  * \param[inout] state   State
278  */
279 void set_box_rel(const t_inputrec *ir, t_state *state);
280
281 /*! \brief Make sure the relative box shape remains the same
282  *
283  * This function ensures that the relative box dimensions are
284  * preserved, which otherwise might diffuse away due to rounding
285  * errors in pressure coupling or the deform option.
286  *
287  * \param[in]    ir      Input record
288  * \param[in]    box_rel Relative box dimensions
289  * \param[inout] box     The corrected actual box dimensions
290  */
291 void preserve_box_shape(const t_inputrec *ir, matrix box_rel, matrix box);
292
293 /*! \brief Returns an arrayRef to the positions in \p state when \p state!=null
294  *
295  * When \p state=nullptr, returns an empty arrayRef.
296  *
297  * \note The size returned is the number of atoms, without padding.
298  *
299  * \param[in] state  The state, can be nullptr
300  */
301 static inline gmx::ArrayRef<const gmx::RVec>
302 positionsFromStatePointer(const t_state *state)
303 {
304     if (state)
305     {
306         return gmx::constArrayRefFromArray(state->x.data(), state->natoms);
307     }
308     else
309     {
310         return gmx::EmptyArrayRef();
311     }
312 };
313
314 #endif