2 * This file is part of the GROMACS molecular simulation package.
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 by the GROMACS development team.
7 * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9 * and including many others, as listed in the AUTHORS file in the
10 * top-level source directory and at http://www.gromacs.org.
12 * GROMACS is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU Lesser General Public License
14 * as published by the Free Software Foundation; either version 2.1
15 * of the License, or (at your option) any later version.
17 * GROMACS is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * Lesser General Public License for more details.
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with GROMACS; if not, see
24 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * If you want to redistribute modifications to GROMACS, please
28 * consider that scientific software is very special. Version
29 * control is crucial - bugs must be traceable. We will be happy to
30 * consider code for inclusion in the official distribution, but
31 * derived work must not be called official GROMACS. Details are found
32 * in the README & COPYING files - if they are missing, get the
33 * official version at http://www.gromacs.org.
35 * To help us fund GROMACS development, we humbly ask that you cite
36 * the research papers on the package. Check out http://www.gromacs.org.
39 * \brief Defines the high-level constraint code.
41 * \author Berk Hess <hess@kth.se>
42 * \author Mark Abraham <mark.j.abraham@gmail.com>
43 * \ingroup module_mdlib
55 #include "gromacs/domdec/domdec.h"
56 #include "gromacs/domdec/domdec_struct.h"
57 #include "gromacs/essentialdynamics/edsam.h"
58 #include "gromacs/fileio/confio.h"
59 #include "gromacs/fileio/gmxfio.h"
60 #include "gromacs/fileio/pdbio.h"
61 #include "gromacs/gmxlib/nrnb.h"
62 #include "gromacs/math/utilities.h"
63 #include "gromacs/math/vec.h"
64 #include "gromacs/mdlib/gmx_omp_nthreads.h"
65 #include "gromacs/mdlib/lincs.h"
66 #include "gromacs/mdlib/settle.h"
67 #include "gromacs/mdlib/shake.h"
68 #include "gromacs/mdtypes/commrec.h"
69 #include "gromacs/mdtypes/inputrec.h"
70 #include "gromacs/mdtypes/md_enums.h"
71 #include "gromacs/mdtypes/state.h"
72 #include "gromacs/pbcutil/pbc.h"
73 #include "gromacs/pulling/pull.h"
74 #include "gromacs/timing/wallcycle.h"
75 #include "gromacs/topology/ifunc.h"
76 #include "gromacs/topology/mtop_lookup.h"
77 #include "gromacs/topology/mtop_util.h"
78 #include "gromacs/utility/exceptions.h"
79 #include "gromacs/utility/fatalerror.h"
80 #include "gromacs/utility/gmxassert.h"
81 #include "gromacs/utility/listoflists.h"
82 #include "gromacs/utility/pleasecite.h"
83 #include "gromacs/utility/txtdump.h"
88 /* \brief Impl class for Constraints
90 * \todo Members like md, idef are valid only for the lifetime of a
91 * domain, which would be good to make clearer in the structure of the
92 * code. It should not be possible to call apply() if setConstraints()
93 * has not been called. For example, this could be achieved if
94 * setConstraints returned a valid object with such a method. That
95 * still requires that we manage the lifetime of that object
96 * correctly, however. */
97 class Constraints::Impl
100 Impl(const gmx_mtop_t& mtop_p,
101 const t_inputrec& ir_p,
104 const t_commrec* cr_p,
105 const gmx_multisim_t* ms,
107 gmx_wallcycle* wcycle_p,
108 bool pbcHandlingRequired,
112 void setConstraints(gmx_localtop_t* top,
117 bool hasMassPerturbedAtoms,
119 unsigned short* cFREEZE);
120 bool apply(bool bLog,
125 ArrayRefWithPadding<RVec> x,
126 ArrayRefWithPadding<RVec> xprime,
127 ArrayRef<RVec> min_proj,
131 ArrayRefWithPadding<RVec> v,
133 tensor constraintsVirial,
134 ConstraintVariable econq);
135 //! The total number of constraints.
137 //! The number of flexible constraints.
139 //! A list of atoms to constraints for each moleculetype.
140 std::vector<ListOfLists<int>> at2con_mt;
141 //! A list of atoms to settles for each moleculetype
142 std::vector<std::vector<int>> at2settle_mt;
144 Lincs* lincsd = nullptr; // TODO this should become a unique_ptr
146 std::unique_ptr<shakedata> shaked;
148 std::unique_ptr<SettleData> settled;
149 //! The maximum number of warnings.
151 //! The number of warnings for LINCS.
152 int warncount_lincs = 0;
153 //! The number of warnings for SETTLE.
154 int warncount_settle = 0;
155 //! The essential dynamics data.
156 gmx_edsam* ed = nullptr;
158 //! Thread-local virial contribution.
159 tensor* threadConstraintsVirial = { nullptr };
160 //! Did a settle error occur?
161 bool* bSettleErrorHasOccurred = nullptr;
163 //! Pointer to the global topology - only used for printing warnings.
164 const gmx_mtop_t& mtop;
165 //! Parameters for the interactions in this domain.
166 const InteractionDefinitions* idef = nullptr;
167 //! Total number of atoms.
169 //! Number of local atoms.
170 int numHomeAtoms_ = 0;
174 real* inverseMasses_;
175 //! If there are atoms with perturbed mass (for FEP).
176 bool hasMassPerturbedAtoms_;
177 //! FEP lambda value.
179 //! Freeze groups data
180 unsigned short* cFREEZE_;
181 //! Whether we need to do pbc for handling bonds.
182 bool pbcHandlingRequired_ = false;
186 //! Communication support.
187 const t_commrec* cr = nullptr;
188 //! Multi-sim support.
189 const gmx_multisim_t* ms = nullptr;
190 //! Pulling code object, if any.
191 pull_t* pull_work = nullptr;
192 /*!\brief Input options.
194 * \todo Replace with IMdpOptions */
195 const t_inputrec& ir;
196 //! Flop counting support.
197 t_nrnb* nrnb = nullptr;
198 //! Tracks wallcycle usage.
199 gmx_wallcycle* wcycle;
202 Constraints::~Constraints() = default;
204 int Constraints::numFlexibleConstraints() const
206 return impl_->nflexcon;
209 bool Constraints::havePerturbedConstraints() const
211 const gmx_ffparams_t& ffparams = impl_->mtop.ffparams;
213 for (size_t i = 0; i < ffparams.functype.size(); i++)
215 if ((ffparams.functype[i] == F_CONSTR || ffparams.functype[i] == F_CONSTRNC)
216 && ffparams.iparams[i].constr.dA != ffparams.iparams[i].constr.dB)
225 //! Clears constraint quantities for atoms in nonlocal region.
226 static void clear_constraint_quantity_nonlocal(gmx_domdec_t* dd, ArrayRef<RVec> q)
228 int nonlocal_at_start, nonlocal_at_end, at;
230 dd_get_constraint_range(dd, &nonlocal_at_start, &nonlocal_at_end);
232 for (at = nonlocal_at_start; at < nonlocal_at_end; at++)
238 void too_many_constraint_warnings(int eConstrAlg, int warncount)
242 "Too many %s warnings (%d)\n"
243 "If you know what you are doing you can %s"
244 "set the environment variable GMX_MAXCONSTRWARN to -1,\n"
245 "but normally it is better to fix the problem",
246 (eConstrAlg == econtLINCS) ? "LINCS" : "SETTLE",
248 (eConstrAlg == econtLINCS) ? "adjust the lincs warning threshold in your mdp file\nor " : "\n");
251 //! Writes out coordinates.
252 static void write_constr_pdb(const char* fn,
254 const gmx_mtop_t& mtop,
258 ArrayRef<const RVec> x,
263 int dd_ac0 = 0, dd_ac1 = 0, i, ii, resnr;
265 const char * anm, *resnm;
268 if (DOMAINDECOMP(cr))
271 dd_get_constraint_range(dd, &dd_ac0, &dd_ac1);
278 sprintf(fname, "%s_n%d.pdb", fn, cr->sim_nodeid);
282 sprintf(fname, "%s.pdb", fn);
285 out = gmx_fio_fopen(fname, "w");
287 fprintf(out, "TITLE %s\n", title);
288 gmx_write_pdb_box(out, PbcType::Unset, box);
290 for (i = start; i < start + homenr; i++)
294 if (i >= dd_numHomeAtoms(*dd) && i < dd_ac0)
298 ii = dd->globalAtomIndices[i];
304 mtopGetAtomAndResidueName(mtop, ii, &molb, &anm, &resnr, &resnm, nullptr);
305 gmx_fprintf_pdb_atomline(out,
321 fprintf(out, "TER\n");
326 //! Writes out domain contents to help diagnose crashes.
327 static void dump_confs(FILE* log,
329 const gmx_mtop_t& mtop,
333 ArrayRef<const RVec> x,
334 ArrayRef<const RVec> xprime,
337 char buf[STRLEN], buf2[22];
339 char* env = getenv("GMX_SUPPRESS_DUMP");
345 sprintf(buf, "step%sb", gmx_step_str(step, buf2));
346 write_constr_pdb(buf, "initial coordinates", mtop, start, homenr, cr, x, box);
347 sprintf(buf, "step%sc", gmx_step_str(step, buf2));
348 write_constr_pdb(buf, "coordinates after constraining", mtop, start, homenr, cr, xprime, box);
351 fprintf(log, "Wrote pdb files with previous and current coordinates\n");
353 fprintf(stderr, "Wrote pdb files with previous and current coordinates\n");
356 bool Constraints::apply(bool bLog,
361 ArrayRefWithPadding<RVec> x,
362 ArrayRefWithPadding<RVec> xprime,
363 ArrayRef<RVec> min_proj,
367 ArrayRefWithPadding<RVec> v,
369 tensor constraintsVirial,
370 ConstraintVariable econq)
372 return impl_->apply(bLog,
389 bool Constraints::Impl::apply(bool bLog,
394 ArrayRefWithPadding<RVec> x,
395 ArrayRefWithPadding<RVec> xprime,
396 ArrayRef<RVec> min_proj,
400 ArrayRefWithPadding<RVec> v,
402 tensor constraintsVirial,
403 ConstraintVariable econq)
408 real invdt, vir_fac = 0, t;
410 t_pbc pbc, *pbc_null;
414 wallcycle_start(wcycle, ewcCONSTR);
416 if (econq == ConstraintVariable::ForceDispl && !EI_ENERGY_MINIMIZATION(ir.eI))
419 "constrain called for forces displacements while not doing energy minimization, "
420 "can not do this while the LINCS and SETTLE constraint connection matrices are "
429 scaled_delta_t = step_scaling * ir.delta_t;
431 /* Prepare time step for use in constraint implementations, and
432 avoid generating inf when ir.delta_t = 0. */
439 invdt = 1.0 / scaled_delta_t;
442 if (ir.efep != efepNO && EI_DYNAMICS(ir.eI))
444 /* Set the constraint lengths for the step at which this configuration
445 * is meant to be. The invmasses should not be changed.
447 lambda += delta_step * ir.fepvals->delta_lambda;
452 clear_mat(constraintsVirial);
454 const InteractionList& settle = idef->il[F_SETTLE];
455 nsettle = settle.size() / (1 + NRAL(F_SETTLE));
459 nth = gmx_omp_nthreads_get(emntSETTLE);
466 /* We do not need full pbc when constraints do not cross update groups
467 * i.e. when dd->constraint_comm==NULL.
468 * Note that PBC for constraints is different from PBC for bondeds.
469 * For constraints there is both forward and backward communication.
471 if (ir.pbcType != PbcType::No && (cr->dd || pbcHandlingRequired_)
472 && !(cr->dd && cr->dd->constraint_comm == nullptr))
474 /* With pbc=screw the screw has been changed to a shift
475 * by the constraint coordinate communication routine,
476 * so that here we can use normal pbc.
478 pbc_null = set_pbc_dd(&pbc, ir.pbcType, DOMAINDECOMP(cr) ? cr->dd->numCells : nullptr, FALSE, box);
485 /* Communicate the coordinates required for the non-local constraints
486 * for LINCS and/or SETTLE.
490 dd_move_x_constraints(cr->dd,
492 x.unpaddedArrayRef(),
493 xprime.unpaddedArrayRef(),
494 econq == ConstraintVariable::Positions);
498 /* We need to initialize the non-local components of v.
499 * We never actually use these values, but we do increment them,
500 * so we should avoid uninitialized variables and overflows.
502 clear_constraint_quantity_nonlocal(cr->dd, v.unpaddedArrayRef());
506 if (lincsd != nullptr)
508 bOK = constrain_lincs(bLog || bEner,
520 hasMassPerturbedAtoms_,
524 v.unpaddedArrayRef(),
531 if (!bOK && maxwarn < INT_MAX)
536 "Constraint error in algorithm %s at step %s\n",
537 econstr_names[econtLINCS],
538 gmx_step_str(step, buf));
544 if (shaked != nullptr)
546 bOK = constrain_shake(log,
551 x.unpaddedArrayRef(),
552 xprime.unpaddedArrayRef(),
559 v.unpaddedArrayRef(),
565 if (!bOK && maxwarn < INT_MAX)
570 "Constraint error in algorithm %s at step %s\n",
571 econstr_names[econtSHAKE],
572 gmx_step_str(step, buf));
580 bool bSettleErrorHasOccurred0 = false;
584 case ConstraintVariable::Positions:
585 #pragma omp parallel for num_threads(nth) schedule(static)
586 for (int th = 0; th < nth; th++)
592 clear_mat(threadConstraintsVirial[th]);
604 th == 0 ? constraintsVirial : threadConstraintsVirial[th],
605 th == 0 ? &bSettleErrorHasOccurred0 : &bSettleErrorHasOccurred[th]);
607 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
609 inc_nrnb(nrnb, eNR_SETTLE, nsettle);
612 inc_nrnb(nrnb, eNR_CONSTR_V, nsettle * 3);
616 inc_nrnb(nrnb, eNR_CONSTR_VIR, nsettle * 3);
619 case ConstraintVariable::Velocities:
620 case ConstraintVariable::Derivative:
621 case ConstraintVariable::Force:
622 case ConstraintVariable::ForceDispl:
623 #pragma omp parallel for num_threads(nth) schedule(static)
624 for (int th = 0; th < nth; th++)
628 int calcvir_atom_end;
632 calcvir_atom_end = 0;
636 calcvir_atom_end = numHomeAtoms_;
641 clear_mat(threadConstraintsVirial[th]);
644 int start_th = (nsettle * th) / nth;
645 int end_th = (nsettle * (th + 1)) / nth;
647 if (start_th >= 0 && end_th - start_th > 0)
649 settle_proj(*settled,
652 settle.iatoms.data() + start_th * (1 + NRAL(F_SETTLE)),
654 x.unpaddedArrayRef(),
655 xprime.unpaddedArrayRef(),
658 th == 0 ? constraintsVirial : threadConstraintsVirial[th]);
661 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
663 /* This is an overestimate */
664 inc_nrnb(nrnb, eNR_SETTLE, nsettle);
666 case ConstraintVariable::Deriv_FlexCon:
667 /* Nothing to do, since the are no flexible constraints in settles */
669 default: gmx_incons("Unknown constraint quantity for settle");
674 /* Reduce the virial contributions over the threads */
675 for (int th = 1; th < nth; th++)
677 m_add(constraintsVirial, threadConstraintsVirial[th], constraintsVirial);
681 if (econq == ConstraintVariable::Positions)
683 for (int th = 1; th < nth; th++)
685 bSettleErrorHasOccurred0 = bSettleErrorHasOccurred0 || bSettleErrorHasOccurred[th];
688 if (bSettleErrorHasOccurred0)
694 ": One or more water molecules can not be settled.\n"
695 "Check for bad contacts and/or reduce the timestep if appropriate.\n",
699 fprintf(log, "%s", buf);
701 fprintf(stderr, "%s", buf);
703 if (warncount_settle > maxwarn)
705 too_many_constraint_warnings(-1, warncount_settle);
716 /* The normal uses of constrain() pass step_scaling = 1.0.
717 * The call to constrain() for SD1 that passes step_scaling =
718 * 0.5 also passes vir = NULL, so cannot reach this
719 * assertion. This assertion should remain until someone knows
720 * that this path works for their intended purpose, and then
721 * they can use scaled_delta_t instead of ir.delta_t
723 assert(gmx_within_tol(step_scaling, 1.0, GMX_REAL_EPS));
726 case ConstraintVariable::Positions: vir_fac = 0.5 / (ir.delta_t * ir.delta_t); break;
727 case ConstraintVariable::Velocities: vir_fac = 0.5 / ir.delta_t; break;
728 case ConstraintVariable::Force:
729 case ConstraintVariable::ForceDispl: vir_fac = 0.5; break;
730 default: gmx_incons("Unsupported constraint quantity for virial");
735 vir_fac *= 2; /* only constraining over half the distance here */
737 for (int i = 0; i < DIM; i++)
739 for (int j = 0; j < DIM; j++)
741 constraintsVirial[i][j] *= vir_fac;
748 dump_confs(log, step, mtop, start, numHomeAtoms_, cr, x.unpaddedArrayRef(), xprime.unpaddedArrayRef(), box);
751 if (econq == ConstraintVariable::Positions)
753 if (ir.bPull && pull_have_constraint(*pull_work))
755 if (EI_DYNAMICS(ir.eI))
757 t = ir.init_t + (step + delta_step) * ir.delta_t;
763 set_pbc(&pbc, ir.pbcType, box);
764 pull_constraint(pull_work,
770 as_rvec_array(x.unpaddedArrayRef().data()),
771 as_rvec_array(xprime.unpaddedArrayRef().data()),
772 as_rvec_array(v.unpaddedArrayRef().data()),
775 if (ed && delta_step > 0)
777 /* apply the essential dynamics constraints here */
781 as_rvec_array(xprime.unpaddedArrayRef().data()),
782 as_rvec_array(v.unpaddedArrayRef().data()),
787 wallcycle_stop(wcycle, ewcCONSTR);
789 if (!v.empty() && cFREEZE_)
791 /* Set the velocities of frozen dimensions to zero */
792 ArrayRef<RVec> vRef = v.unpaddedArrayRef();
794 int gmx_unused numThreads = gmx_omp_nthreads_get(emntUpdate);
796 #pragma omp parallel for num_threads(numThreads) schedule(static)
797 for (int i = 0; i < numHomeAtoms_; i++)
799 int freezeGroup = cFREEZE_[i];
801 for (int d = 0; d < DIM; d++)
803 if (ir.opts.nFreeze[freezeGroup][d])
814 ArrayRef<real> Constraints::rmsdData() const
818 return lincs_rmsdData(impl_->lincsd);
826 real Constraints::rmsd() const
830 return lincs_rmsd(impl_->lincsd);
838 int Constraints::numConstraintsTotal()
840 return impl_->ncon_tot;
843 FlexibleConstraintTreatment flexibleConstraintTreatment(bool haveDynamicsIntegrator)
845 if (haveDynamicsIntegrator)
847 return FlexibleConstraintTreatment::Include;
851 return FlexibleConstraintTreatment::Exclude;
855 /*! \brief Returns a block struct to go from atoms to constraints
857 * The block struct will contain constraint indices with lower indices
858 * directly matching the order in F_CONSTR and higher indices matching
859 * the order in F_CONSTRNC offset by the number of constraints in F_CONSTR.
861 * \param[in] numAtoms The number of atoms to construct the list for
862 * \param[in] ilists The interaction lists, size F_NRE
863 * \param[in] iparams Interaction parameters, can be null when
864 * \p flexibleConstraintTreatment==Include
865 * \param[in] flexibleConstraintTreatment The flexible constraint treatment,
868 * \returns a block struct with all constraints for each atom
870 static ListOfLists<int> makeAtomsToConstraintsList(int numAtoms,
871 ArrayRef<const InteractionList> ilists,
872 ArrayRef<const t_iparams> iparams,
873 FlexibleConstraintTreatment flexibleConstraintTreatment)
875 GMX_ASSERT(flexibleConstraintTreatment == FlexibleConstraintTreatment::Include || !iparams.empty(),
876 "With flexible constraint detection we need valid iparams");
878 std::vector<int> count(numAtoms);
880 for (int ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
882 const InteractionList& ilist = ilists[ftype];
883 const int stride = 1 + NRAL(ftype);
884 for (int i = 0; i < ilist.size(); i += stride)
886 if (flexibleConstraintTreatment == FlexibleConstraintTreatment::Include
887 || !isConstraintFlexible(iparams, ilist.iatoms[i]))
889 for (int j = 1; j < 3; j++)
891 int a = ilist.iatoms[i + j];
898 std::vector<int> listRanges(numAtoms + 1);
899 for (int a = 0; a < numAtoms; a++)
901 listRanges[a + 1] = listRanges[a] + count[a];
904 std::vector<int> elements(listRanges[numAtoms]);
906 /* The F_CONSTRNC constraints have constraint numbers
907 * that continue after the last F_CONSTR constraint.
909 int numConstraints = 0;
910 for (int ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
912 const InteractionList& ilist = ilists[ftype];
913 const int stride = 1 + NRAL(ftype);
914 for (int i = 0; i < ilist.size(); i += stride)
916 if (flexibleConstraintTreatment == FlexibleConstraintTreatment::Include
917 || !isConstraintFlexible(iparams, ilist.iatoms[i]))
919 for (int j = 1; j < 3; j++)
921 const int a = ilist.iatoms[i + j];
922 elements[listRanges[a] + count[a]++] = numConstraints;
929 return ListOfLists<int>(std::move(listRanges), std::move(elements));
932 ListOfLists<int> make_at2con(int numAtoms,
933 ArrayRef<const InteractionList> ilist,
934 ArrayRef<const t_iparams> iparams,
935 FlexibleConstraintTreatment flexibleConstraintTreatment)
937 return makeAtomsToConstraintsList(numAtoms, ilist, iparams, flexibleConstraintTreatment);
940 ListOfLists<int> make_at2con(const gmx_moltype_t& moltype,
941 gmx::ArrayRef<const t_iparams> iparams,
942 FlexibleConstraintTreatment flexibleConstraintTreatment)
944 return makeAtomsToConstraintsList(
945 moltype.atoms.nr, makeConstArrayRef(moltype.ilist), iparams, flexibleConstraintTreatment);
948 //! Return the number of flexible constraints in the \c ilist and \c iparams.
949 int countFlexibleConstraints(ArrayRef<const InteractionList> ilist, ArrayRef<const t_iparams> iparams)
952 for (int ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
954 const int numIatomsPerConstraint = 3;
955 for (int i = 0; i < ilist[ftype].size(); i += numIatomsPerConstraint)
957 const int type = ilist[ftype].iatoms[i];
958 if (iparams[type].constr.dA == 0 && iparams[type].constr.dB == 0)
968 //! Returns the index of the settle to which each atom belongs.
969 static std::vector<int> make_at2settle(int natoms, const InteractionList& ilist)
971 /* Set all to no settle */
972 std::vector<int> at2s(natoms, -1);
974 const int stride = 1 + NRAL(F_SETTLE);
976 for (int s = 0; s < ilist.size(); s += stride)
978 at2s[ilist.iatoms[s + 1]] = s / stride;
979 at2s[ilist.iatoms[s + 2]] = s / stride;
980 at2s[ilist.iatoms[s + 3]] = s / stride;
986 void Constraints::Impl::setConstraints(gmx_localtop_t* top,
991 const bool hasMassPerturbedAtoms,
993 unsigned short* cFREEZE)
995 numAtoms_ = numAtoms;
996 numHomeAtoms_ = numHomeAtoms;
998 inverseMasses_ = inverseMasses;
999 hasMassPerturbedAtoms_ = hasMassPerturbedAtoms;
1007 /* With DD we might also need to call LINCS on a domain no constraints for
1008 * communicating coordinates to other nodes that do have constraints.
1010 if (ir.eConstrAlg == econtLINCS)
1012 set_lincs(*idef, numAtoms_, inverseMasses_, lambda_, EI_DYNAMICS(ir.eI), cr, lincsd);
1014 if (ir.eConstrAlg == econtSHAKE)
1018 // We are using the local topology, so there are only
1019 // F_CONSTR constraints.
1020 GMX_RELEASE_ASSERT(idef->il[F_CONSTRNC].empty(),
1021 "Here we should not have no-connect constraints");
1022 make_shake_sblock_dd(shaked.get(), idef->il[F_CONSTR]);
1026 make_shake_sblock_serial(shaked.get(), &top->idef, numAtoms_);
1033 settled->setConstraints(idef->il[F_SETTLE], numHomeAtoms_, masses_, inverseMasses_);
1036 /* Make a selection of the local atoms for essential dynamics */
1039 dd_make_local_ed_indices(cr->dd, ed);
1043 void Constraints::setConstraints(gmx_localtop_t* top,
1045 const int numHomeAtoms,
1047 real* inverseMasses,
1048 const bool hasMassPerturbedAtoms,
1050 unsigned short* cFREEZE)
1052 impl_->setConstraints(
1053 top, numAtoms, numHomeAtoms, masses, inverseMasses, hasMassPerturbedAtoms, lambda, cFREEZE);
1056 /*! \brief Makes a per-moleculetype container of mappings from atom
1057 * indices to constraint indices.
1059 * Note that flexible constraints are only enabled with a dynamical integrator. */
1060 static std::vector<ListOfLists<int>> makeAtomToConstraintMappings(const gmx_mtop_t& mtop,
1061 FlexibleConstraintTreatment flexibleConstraintTreatment)
1063 std::vector<ListOfLists<int>> mapping;
1064 mapping.reserve(mtop.moltype.size());
1065 for (const gmx_moltype_t& moltype : mtop.moltype)
1067 mapping.push_back(make_at2con(moltype, mtop.ffparams.iparams, flexibleConstraintTreatment));
1072 Constraints::Constraints(const gmx_mtop_t& mtop,
1073 const t_inputrec& ir,
1076 const t_commrec* cr,
1077 const gmx_multisim_t* ms,
1079 gmx_wallcycle* wcycle,
1080 bool pbcHandlingRequired,
1083 impl_(new Impl(mtop, ir, pull_work, log, cr, ms, nrnb, wcycle, pbcHandlingRequired, numConstraints, numSettles))
1087 Constraints::Impl::Impl(const gmx_mtop_t& mtop_p,
1088 const t_inputrec& ir_p,
1091 const t_commrec* cr_p,
1092 const gmx_multisim_t* ms_p,
1094 gmx_wallcycle* wcycle_p,
1095 bool pbcHandlingRequired,
1098 ncon_tot(numConstraints),
1100 pbcHandlingRequired_(pbcHandlingRequired),
1104 pull_work(pull_work),
1109 if (numConstraints + numSettles > 0 && ir.epc == epcMTTK)
1111 gmx_fatal(FARGS, "Constraints are not implemented with MTTK pressure control.");
1115 if (numConstraints > 0)
1117 at2con_mt = makeAtomToConstraintMappings(mtop, flexibleConstraintTreatment(EI_DYNAMICS(ir.eI)));
1119 for (const gmx_molblock_t& molblock : mtop.molblock)
1121 int count = countFlexibleConstraints(mtop.moltype[molblock.type].ilist, mtop.ffparams.iparams);
1122 nflexcon += molblock.nmol * count;
1129 fprintf(log, "There are %d flexible constraints\n", nflexcon);
1130 if (ir.fc_stepsize == 0)
1134 "WARNING: step size for flexible constraining = 0\n"
1135 " All flexible constraints will be rigid.\n"
1136 " Will try to keep all flexible constraints at their original "
1138 " but the lengths may exhibit some drift.\n\n");
1144 please_cite(log, "Hess2002");
1148 if (ir.eConstrAlg == econtLINCS)
1150 lincsd = init_lincs(log,
1154 DOMAINDECOMP(cr) && ddHaveSplitConstraints(*cr->dd),
1159 if (ir.eConstrAlg == econtSHAKE)
1161 if (DOMAINDECOMP(cr) && ddHaveSplitConstraints(*cr->dd))
1164 "SHAKE is not supported with domain decomposition and constraint that "
1165 "cross domain boundaries, use LINCS");
1170 "For this system also velocities and/or forces need to be constrained, "
1171 "this can not be done with SHAKE, you should select LINCS");
1173 please_cite(log, "Ryckaert77a");
1176 please_cite(log, "Barth95a");
1179 shaked = std::make_unique<shakedata>();
1185 please_cite(log, "Miyamoto92a");
1187 settled = std::make_unique<SettleData>(mtop);
1189 /* Make an atom to settle index for use in domain decomposition */
1190 for (size_t mt = 0; mt < mtop.moltype.size(); mt++)
1192 at2settle_mt.emplace_back(
1193 make_at2settle(mtop.moltype[mt].atoms.nr, mtop.moltype[mt].ilist[F_SETTLE]));
1196 /* Allocate thread-local work arrays */
1197 int nthreads = gmx_omp_nthreads_get(emntSETTLE);
1198 if (nthreads > 1 && threadConstraintsVirial == nullptr)
1200 snew(threadConstraintsVirial, nthreads);
1201 snew(bSettleErrorHasOccurred, nthreads);
1206 char* env = getenv("GMX_MAXCONSTRWARN");
1210 sscanf(env, "%8d", &maxwarn);
1217 fprintf(log, "Setting the maximum number of constraint warnings to %d\n", maxwarn);
1221 fprintf(stderr, "Setting the maximum number of constraint warnings to %d\n", maxwarn);
1224 warncount_lincs = 0;
1225 warncount_settle = 0;
1228 Constraints::Impl::~Impl()
1230 if (bSettleErrorHasOccurred != nullptr)
1232 sfree(bSettleErrorHasOccurred);
1234 if (threadConstraintsVirial != nullptr)
1236 sfree(threadConstraintsVirial);
1241 void Constraints::saveEdsamPointer(gmx_edsam* ed)
1246 ArrayRef<const ListOfLists<int>> Constraints::atom2constraints_moltype() const
1248 return impl_->at2con_mt;
1251 ArrayRef<const std::vector<int>> Constraints::atom2settle_moltype() const
1253 return impl_->at2settle_mt;
1256 void do_constrain_first(FILE* fplog,
1257 gmx::Constraints* constr,
1258 const t_inputrec* ir,
1261 ArrayRefWithPadding<RVec> x,
1262 ArrayRefWithPadding<RVec> v,
1266 int i, m, start, end;
1268 real dt = ir->delta_t;
1271 PaddedVector<RVec> savex(numAtoms);
1278 fprintf(debug, "vcm: start=%d, homenr=%d, end=%d\n", start, numHomeAtoms, end);
1280 /* Do a first constrain to reset particles... */
1281 step = ir->init_step;
1284 char buf[STEPSTRSIZE];
1285 fprintf(fplog, "\nConstraining the starting coordinates (step %s)\n", gmx_step_str(step, buf));
1289 bool needsLogging = true;
1290 bool computeEnergy = false;
1291 bool computeVirial = false;
1292 /* constrain the current position */
1293 constr->apply(needsLogging,
1307 gmx::ConstraintVariable::Positions);
1310 /* constrain the inital velocity, and save it */
1311 /* also may be useful if we need the ekin from the halfstep for velocity verlet */
1312 constr->apply(needsLogging,
1319 v.unpaddedArrayRef(),
1326 gmx::ConstraintVariable::Velocities);
1328 /* constrain the inital velocities at t-dt/2 */
1329 if (EI_STATE_VELOCITY(ir->eI) && ir->eI != eiVV)
1331 auto subX = x.paddedArrayRef().subArray(start, end);
1332 auto subV = v.paddedArrayRef().subArray(start, end);
1333 for (i = start; (i < end); i++)
1335 for (m = 0; (m < DIM); m++)
1337 /* Reverse the velocity */
1338 subV[i][m] = -subV[i][m];
1339 /* Store the position at t-dt in buf */
1340 savex[i][m] = subX[i][m] + dt * subV[i][m];
1343 /* Shake the positions at t=-dt with the positions at t=0
1344 * as reference coordinates.
1348 char buf[STEPSTRSIZE];
1349 fprintf(fplog, "\nConstraining the coordinates at t0-dt (step %s)\n", gmx_step_str(step, buf));
1352 constr->apply(needsLogging,
1358 savex.arrayRefWithPadding(),
1366 gmx::ConstraintVariable::Positions);
1368 for (i = start; i < end; i++)
1370 for (m = 0; m < DIM; m++)
1372 /* Re-reverse the velocities */
1373 subV[i][m] = -subV[i][m];
1379 void constrain_velocities(gmx::Constraints* constr,
1385 gmx_bool computeVirial,
1386 tensor constraintsVirial)
1388 if (constr != nullptr)
1390 constr->apply(do_log,
1395 state->x.arrayRefWithPadding(),
1396 state->v.arrayRefWithPadding(),
1397 state->v.arrayRefWithPadding().unpaddedArrayRef(),
1399 state->lambda[efptBONDED],
1401 ArrayRefWithPadding<RVec>(),
1404 ConstraintVariable::Velocities);
1408 void constrain_coordinates(gmx::Constraints* constr,
1413 ArrayRefWithPadding<RVec> xp,
1415 gmx_bool computeVirial,
1416 tensor constraintsVirial)
1418 if (constr != nullptr)
1420 constr->apply(do_log,
1425 state->x.arrayRefWithPadding(),
1429 state->lambda[efptBONDED],
1431 state->v.arrayRefWithPadding(),
1434 ConstraintVariable::Positions);