dac41fe3a564d8f0520c692375f41b17ddb69089
[alexxy/gromacs.git] / src / gromacs / mdlib / constr.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,2019, 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 /*! \libinternal \file
38  * \brief Declares interface to constraint code.
39  *
40  * \author Berk Hess <hess@kth.se>
41  * \author Mark Abraham <mark.j.abraham@gmail.com>
42  * \ingroup module_mdlib
43  * \inlibraryapi
44  */
45
46 #ifndef GMX_MDLIB_CONSTR_H
47 #define GMX_MDLIB_CONSTR_H
48
49 #include <cstdio>
50
51 #include "gromacs/math/vectypes.h"
52 #include "gromacs/topology/idef.h"
53 #include "gromacs/utility/arrayref.h"
54 #include "gromacs/utility/basedefinitions.h"
55 #include "gromacs/utility/classhelpers.h"
56 #include "gromacs/utility/gmxassert.h"
57 #include "gromacs/utility/real.h"
58
59 struct gmx_edsam;
60 struct gmx_localtop_t;
61 struct gmx_moltype_t;
62 struct gmx_mtop_t;
63 struct gmx_multisim_t;
64 struct gmx_wallcycle;
65 struct pull_t;
66 struct t_blocka;
67 struct t_commrec;
68 struct t_ilist;
69 struct t_inputrec;
70 struct t_mdatoms;
71 struct t_nrnb;
72 struct t_pbc;
73 class t_state;
74
75 namespace gmx
76 {
77
78 //! Describes supported flavours of constrained updates.
79 enum class ConstraintVariable : int
80 {
81     Positions,         /* Constrain positions (mass weighted)             */
82     Velocities,        /* Constrain velocities (mass weighted)            */
83     Derivative,        /* Constrain a derivative (mass weighted),         *
84                         * for instance velocity or acceleration,          *
85                         * constraint virial can not be calculated.        */
86     Deriv_FlexCon,     /* As Derivative, but only output flex. con.       */
87     Force,             /* Constrain forces (non mass-weighted)            */
88     // TODO What does this do? Improve the comment.
89     ForceDispl         /* Like Force, but free particles will have mass
90                         * 1 and frozen particles mass 0                   */
91 };
92
93 /*! \libinternal
94  * \brief Handles constraints */
95 class Constraints
96 {
97     private:
98         /*! \brief Constructor
99          *
100          * Private to enforce use of makeConstraints() factory
101          * function. */
102         Constraints(const gmx_mtop_t     &mtop,
103                     const t_inputrec     &ir,
104                     pull_t               *pull_work,
105                     FILE                 *log,
106                     const t_mdatoms      &md,
107                     const t_commrec      *cr,
108                     const gmx_multisim_t *ms,
109                     t_nrnb               *nrnb,
110                     gmx_wallcycle        *wcycle,
111                     bool                  pbcHandlingRequired,
112                     int                   numConstraints,
113                     int                   numSettles);
114     public:
115         /*! \brief This member type helps implement a factory
116          * function, because its objects can access the private
117          * constructor. */
118         struct CreationHelper;
119
120         ~Constraints();
121
122         /*! \brief Returns the total number of flexible constraints in the system. */
123         int numFlexibleConstraints() const;
124
125         /*! \brief Returns whether the system contains perturbed constraints */
126         bool havePerturbedConstraints() const;
127
128         /*! \brief Set up all the local constraints for the domain.
129          *
130          * \todo Make this a callback that is called automatically
131          * once a new domain has been made. */
132         void setConstraints(const gmx_localtop_t &top,
133                             const t_mdatoms      &md);
134
135         /*! \brief Applies constraints to coordinates.
136          *
137          * When econq=ConstraintVariable::Positions constrains
138          * coordinates xprime using th directions in x, min_proj is
139          * not used.
140          *
141          * When econq=ConstraintVariable::Derivative, calculates the
142          * components xprime in the constraint directions and
143          * subtracts these components from min_proj.  So when
144          * min_proj=xprime, the constraint components are projected
145          * out.
146          *
147          * When econq=ConstraintVariable::Deriv_FlexCon, the same is
148          * done as with ConstraintVariable::Derivative, but only the
149          * components of the flexible constraints are stored.
150          *
151          * delta_step is used for determining the constraint reference lengths
152          * when lenA != lenB or will the pull code with a pulling rate.
153          * step + delta_step is the step at which the final configuration
154          * is meant to be; for update delta_step = 1.
155          *
156          * step_scaling can be used to update coordinates based on the time
157          * step multiplied by this factor. Thus, normally 1.0 is passed. The
158          * SD1 integrator uses 0.5 in one of its calls, to correct positions
159          * for half a step of changed velocities.
160          *
161          * If v!=NULL also constrain v by adding the constraint corrections / dt.
162          *
163          * If vir!=NULL calculate the constraint virial.
164          *
165          * Return whether the application of constraints succeeded without error.
166          */
167         bool apply(bool                  bLog,
168                    bool                  bEner,
169                    int64_t               step,
170                    int                   delta_step,
171                    real                  step_scaling,
172                    rvec                 *x,
173                    rvec                 *xprime,
174                    rvec                 *min_proj,
175                    matrix                box,
176                    real                  lambda,
177                    real                 *dvdlambda,
178                    rvec                 *v,
179                    tensor               *vir,
180                    ConstraintVariable    econq);
181         //! Links the essentialdynamics and constraint code.
182         void saveEdsamPointer(gmx_edsam *ed);
183         //! Getter for use by domain decomposition.
184         const ArrayRef<const t_blocka> atom2constraints_moltype() const;
185         //! Getter for use by domain decomposition.
186         ArrayRef < const std::vector < int>> atom2settle_moltype() const;
187
188         /*! \brief Return the data for reduction for determining
189          * constraint RMS relative deviations, or an empty ArrayRef
190          * when not supported for any active constraints. */
191         ArrayRef<real> rmsdData() const;
192         /*! \brief Return the RMSD of the constraints when available. */
193         real rmsd() const;
194
195     private:
196         //! Implementation type.
197         class Impl;
198         //! Implementation object.
199         PrivateImplPointer<Impl> impl_;
200 };
201
202 /*! \brief Generate a fatal error because of too many LINCS/SETTLE warnings. */
203 [[ noreturn ]] void too_many_constraint_warnings(int eConstrAlg, int warncount);
204
205 /*! \brief Returns whether constraint with parameter \p iparamsIndex is a flexible constraint */
206 static inline bool isConstraintFlexible(const t_iparams *iparams,
207                                         int              iparamsIndex)
208 {
209     GMX_ASSERT(iparams != nullptr, "Need a valid iparams array");
210
211     return (iparams[iparamsIndex].constr.dA == 0 &&
212             iparams[iparamsIndex].constr.dB == 0);
213 };
214
215 /* The at2con t_blocka struct returned by the routines below
216  * contains a list of constraints per atom.
217  * The F_CONSTRNC constraints in this structure number consecutively
218  * after the F_CONSTR constraints.
219  */
220
221 /*! \brief Tells make_at2con how to treat flexible constraints */
222 enum class FlexibleConstraintTreatment
223 {
224     Include, //!< Include all flexible constraints
225     Exclude  //!< Exclude all flexible constraints
226 };
227
228 /*! \brief Returns the flexible constraint treatment depending on whether the integrator is dynamic */
229 FlexibleConstraintTreatment
230 flexibleConstraintTreatment(bool haveDynamicsIntegrator);
231
232 /*! \brief Returns a block struct to go from atoms to constraints
233  *
234  * The block struct will contain constraint indices with lower indices
235  * directly matching the order in F_CONSTR and higher indices matching
236  * the order in F_CONSTRNC offset by the number of constraints in F_CONSTR.
237  *
238  * \param[in]  moltype   The molecule data
239  * \param[in]  iparams   Interaction parameters, can be null when flexibleConstraintTreatment=Include
240  * \param[in]  flexibleConstraintTreatment  The flexible constraint treatment, see enum above
241  * \returns a block struct with all constraints for each atom
242  */
243 t_blocka make_at2con(const gmx_moltype_t            &moltype,
244                      gmx::ArrayRef<const t_iparams>  iparams,
245                      FlexibleConstraintTreatment     flexibleConstraintTreatment);
246
247 /*! \brief Returns a block struct to go from atoms to constraints
248  *
249  * The block struct will contain constraint indices with lower indices
250  * directly matching the order in F_CONSTR and higher indices matching
251  * the order in F_CONSTRNC offset by the number of constraints in F_CONSTR.
252  *
253  * \param[in]  numAtoms  The number of atoms to construct the list for
254  * \param[in]  ilist     Interaction list, size F_NRE
255  * \param[in]  iparams   Interaction parameters, can be null when flexibleConstraintTreatment=Include
256  * \param[in]  flexibleConstraintTreatment  The flexible constraint treatment, see enum above
257  * \returns a block struct with all constraints for each atom
258  */
259 t_blocka make_at2con(int                          numAtoms,
260                      const t_ilist               *ilist,
261                      const t_iparams             *iparams,
262                      FlexibleConstraintTreatment  flexibleConstraintTreatment);
263
264 /*! \brief Returns an array of atom to constraints lists for the moltypes */
265 const t_blocka *atom2constraints_moltype(const Constraints *constr);
266
267 //! Return the number of flexible constraints in the \c ilist and \c iparams.
268 int countFlexibleConstraints(const t_ilist   *ilist,
269                              const t_iparams *iparams);
270
271 /*! \brief Returns the constraint iatoms for a constraint number con
272  * which comes from a list where F_CONSTR and F_CONSTRNC constraints
273  * are concatenated. */
274 inline const int *
275 constr_iatomptr(gmx::ArrayRef<const int> iatom_constr,
276                 gmx::ArrayRef<const int> iatom_constrnc,
277                 int                      con)
278 {
279     if (con*3 < iatom_constr.ssize())
280     {
281         return iatom_constr.data() + con*3;
282     }
283     else
284     {
285         return iatom_constrnc.data() + con*3 - iatom_constr.size();
286     }
287 };
288
289 /*! \brief Returns whether there are inter charge group constraints */
290 bool inter_charge_group_constraints(const gmx_mtop_t &mtop);
291
292 /*! \brief Returns whether there are inter charge group settles */
293 bool inter_charge_group_settles(const gmx_mtop_t &mtop);
294
295 /*! \brief Constrain the initial coordinates and velocities */
296 void do_constrain_first(FILE *log, gmx::Constraints *constr,
297                         const t_inputrec *inputrec, const t_mdatoms *md,
298                         t_state *state);
299
300 }  // namespace gmx
301
302 #endif