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,2021, 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/arrayrefwithpadding.h"
63 #include "gromacs/math/utilities.h"
64 #include "gromacs/math/vec.h"
65 #include "gromacs/mdlib/gmx_omp_nthreads.h"
66 #include "gromacs/mdlib/lincs.h"
67 #include "gromacs/mdlib/settle.h"
68 #include "gromacs/mdlib/shake.h"
69 #include "gromacs/mdtypes/commrec.h"
70 #include "gromacs/mdtypes/inputrec.h"
71 #include "gromacs/mdtypes/md_enums.h"
72 #include "gromacs/mdtypes/state.h"
73 #include "gromacs/pbcutil/pbc.h"
74 #include "gromacs/pulling/pull.h"
75 #include "gromacs/timing/wallcycle.h"
76 #include "gromacs/topology/ifunc.h"
77 #include "gromacs/topology/mtop_lookup.h"
78 #include "gromacs/topology/mtop_util.h"
79 #include "gromacs/utility/arrayref.h"
80 #include "gromacs/utility/exceptions.h"
81 #include "gromacs/utility/fatalerror.h"
82 #include "gromacs/utility/gmxassert.h"
83 #include "gromacs/utility/listoflists.h"
84 #include "gromacs/utility/pleasecite.h"
85 #include "gromacs/utility/txtdump.h"
90 /* \brief Impl class for Constraints
92 * \todo Members like md, idef are valid only for the lifetime of a
93 * domain, which would be good to make clearer in the structure of the
94 * code. It should not be possible to call apply() if setConstraints()
95 * has not been called. For example, this could be achieved if
96 * setConstraints returned a valid object with such a method. That
97 * still requires that we manage the lifetime of that object
98 * correctly, however. */
99 class Constraints::Impl
102 Impl(const gmx_mtop_t& mtop_p,
103 const t_inputrec& ir_p,
106 const t_commrec* cr_p,
107 const gmx_multisim_t* ms,
109 gmx_wallcycle* wcycle_p,
110 bool pbcHandlingRequired,
114 void setConstraints(gmx_localtop_t* top,
117 gmx::ArrayRef<const real> masses,
118 gmx::ArrayRef<const real> inverseMasses,
119 bool hasMassPerturbedAtoms,
121 gmx::ArrayRef<const unsigned short> cFREEZE);
122 bool apply(bool bLog,
127 ArrayRefWithPadding<RVec> x,
128 ArrayRefWithPadding<RVec> xprime,
129 ArrayRef<RVec> min_proj,
133 ArrayRefWithPadding<RVec> v,
135 tensor constraintsVirial,
136 ConstraintVariable econq);
137 //! The total number of constraints.
139 //! The number of flexible constraints.
141 //! A list of atoms to constraints for each moleculetype.
142 std::vector<ListOfLists<int>> at2con_mt;
143 //! A list of atoms to settles for each moleculetype
144 std::vector<std::vector<int>> at2settle_mt;
146 Lincs* lincsd = nullptr; // TODO this should become a unique_ptr
148 std::unique_ptr<shakedata> shaked;
150 std::unique_ptr<SettleData> settled;
151 //! The maximum number of warnings.
153 //! The number of warnings for LINCS.
154 int warncount_lincs = 0;
155 //! The number of warnings for SETTLE.
156 int warncount_settle = 0;
157 //! The essential dynamics data.
158 gmx_edsam* ed = nullptr;
160 //! Thread-local virial contribution.
161 tensor* threadConstraintsVirial = { nullptr };
162 //! Did a settle error occur?
163 bool* bSettleErrorHasOccurred = nullptr;
165 //! Pointer to the global topology - only used for printing warnings.
166 const gmx_mtop_t& mtop;
167 //! Parameters for the interactions in this domain.
168 const InteractionDefinitions* idef = nullptr;
169 //! Total number of atoms.
171 //! Number of local atoms.
172 int numHomeAtoms_ = 0;
174 gmx::ArrayRef<const real> masses_;
176 gmx::ArrayRef<const real> inverseMasses_;
177 //! If there are atoms with perturbed mass (for FEP).
178 bool hasMassPerturbedAtoms_;
179 //! FEP lambda value.
181 //! Freeze groups data
182 gmx::ArrayRef<const unsigned short> cFREEZE_;
183 //! Whether we need to do pbc for handling bonds.
184 bool pbcHandlingRequired_ = false;
188 //! Communication support.
189 const t_commrec* cr = nullptr;
190 //! Multi-sim support.
191 const gmx_multisim_t* ms = nullptr;
192 //! Pulling code object, if any.
193 pull_t* pull_work = nullptr;
194 /*!\brief Input options.
196 * \todo Replace with IMdpOptions */
197 const t_inputrec& ir;
198 //! Flop counting support.
199 t_nrnb* nrnb = nullptr;
200 //! Tracks wallcycle usage.
201 gmx_wallcycle* wcycle;
204 Constraints::~Constraints() = default;
206 int Constraints::numFlexibleConstraints() const
208 return impl_->nflexcon;
211 bool Constraints::havePerturbedConstraints() const
213 const gmx_ffparams_t& ffparams = impl_->mtop.ffparams;
215 for (size_t i = 0; i < ffparams.functype.size(); i++)
217 if ((ffparams.functype[i] == F_CONSTR || ffparams.functype[i] == F_CONSTRNC)
218 && ffparams.iparams[i].constr.dA != ffparams.iparams[i].constr.dB)
227 //! Clears constraint quantities for atoms in nonlocal region.
228 static void clear_constraint_quantity_nonlocal(const gmx_domdec_t& dd, ArrayRef<RVec> q)
230 int nonlocal_at_start, nonlocal_at_end;
232 dd_get_constraint_range(dd, &nonlocal_at_start, &nonlocal_at_end);
234 for (int at = nonlocal_at_start; at < nonlocal_at_end; at++)
240 void too_many_constraint_warnings(ConstraintAlgorithm eConstrAlg, int warncount)
243 "Too many %s warnings (%d)\n"
244 "If you know what you are doing you can %s"
245 "set the environment variable GMX_MAXCONSTRWARN to -1,\n"
246 "but normally it is better to fix the problem",
247 (eConstrAlg == ConstraintAlgorithm::Lincs) ? "LINCS" : "SETTLE",
249 (eConstrAlg == ConstraintAlgorithm::Lincs)
250 ? "adjust the lincs warning threshold in your mdp file\nor "
254 //! Writes out coordinates.
255 static void write_constr_pdb(const char* fn,
257 const gmx_mtop_t& mtop,
261 ArrayRef<const RVec> x,
266 int dd_ac0 = 0, dd_ac1 = 0, i, ii, resnr;
268 const char * anm, *resnm;
271 if (DOMAINDECOMP(cr))
274 dd_get_constraint_range(*dd, &dd_ac0, &dd_ac1);
281 sprintf(fname, "%s_n%d.pdb", fn, cr->sim_nodeid);
285 sprintf(fname, "%s.pdb", fn);
288 out = gmx_fio_fopen(fname, "w");
290 fprintf(out, "TITLE %s\n", title);
291 gmx_write_pdb_box(out, PbcType::Unset, box);
293 for (i = start; i < start + homenr; i++)
297 if (i >= dd_numHomeAtoms(*dd) && i < dd_ac0)
301 ii = dd->globalAtomIndices[i];
307 mtopGetAtomAndResidueName(mtop, ii, &molb, &anm, &resnr, &resnm, nullptr);
308 gmx_fprintf_pdb_atomline(out,
324 fprintf(out, "TER\n");
329 //! Writes out domain contents to help diagnose crashes.
330 static void dump_confs(FILE* log,
332 const gmx_mtop_t& mtop,
336 ArrayRef<const RVec> x,
337 ArrayRef<const RVec> xprime,
340 char buf[STRLEN], buf2[22];
342 char* env = getenv("GMX_SUPPRESS_DUMP");
348 sprintf(buf, "step%sb", gmx_step_str(step, buf2));
349 write_constr_pdb(buf, "initial coordinates", mtop, start, homenr, cr, x, box);
350 sprintf(buf, "step%sc", gmx_step_str(step, buf2));
351 write_constr_pdb(buf, "coordinates after constraining", mtop, start, homenr, cr, xprime, box);
354 fprintf(log, "Wrote pdb files with previous and current coordinates\n");
356 fprintf(stderr, "Wrote pdb files with previous and current coordinates\n");
359 bool Constraints::apply(bool bLog,
364 ArrayRefWithPadding<RVec> x,
365 ArrayRefWithPadding<RVec> xprime,
366 ArrayRef<RVec> min_proj,
370 ArrayRefWithPadding<RVec> v,
372 tensor constraintsVirial,
373 ConstraintVariable econq)
375 return impl_->apply(bLog,
392 bool Constraints::Impl::apply(bool bLog,
397 ArrayRefWithPadding<RVec> x,
398 ArrayRefWithPadding<RVec> xprime,
399 ArrayRef<RVec> min_proj,
403 ArrayRefWithPadding<RVec> v,
405 tensor constraintsVirial,
406 ConstraintVariable econq)
411 real invdt, vir_fac = 0, t;
413 t_pbc pbc, *pbc_null;
417 wallcycle_start(wcycle, ewcCONSTR);
419 if (econq == ConstraintVariable::ForceDispl && !EI_ENERGY_MINIMIZATION(ir.eI))
422 "constrain called for forces displacements while not doing energy minimization, "
423 "can not do this while the LINCS and SETTLE constraint connection matrices are "
432 scaled_delta_t = step_scaling * ir.delta_t;
434 /* Prepare time step for use in constraint implementations, and
435 avoid generating inf when ir.delta_t = 0. */
442 invdt = 1.0 / scaled_delta_t;
445 if (ir.efep != FreeEnergyPerturbationType::No && EI_DYNAMICS(ir.eI))
447 /* Set the constraint lengths for the step at which this configuration
448 * is meant to be. The invmasses should not be changed.
450 lambda += delta_step * ir.fepvals->delta_lambda;
455 clear_mat(constraintsVirial);
457 const InteractionList& settle = idef->il[F_SETTLE];
458 nsettle = settle.size() / (1 + NRAL(F_SETTLE));
462 nth = gmx_omp_nthreads_get(emntSETTLE);
469 /* We do not need full pbc when constraints do not cross update groups
470 * i.e. when dd->constraint_comm==NULL.
471 * Note that PBC for constraints is different from PBC for bondeds.
472 * For constraints there is both forward and backward communication.
474 if (ir.pbcType != PbcType::No && (cr->dd || pbcHandlingRequired_)
475 && !(cr->dd && cr->dd->constraint_comm == nullptr))
477 /* With pbc=screw the screw has been changed to a shift
478 * by the constraint coordinate communication routine,
479 * so that here we can use normal pbc.
481 pbc_null = set_pbc_dd(&pbc, ir.pbcType, DOMAINDECOMP(cr) ? cr->dd->numCells : nullptr, FALSE, box);
488 /* Communicate the coordinates required for the non-local constraints
489 * for LINCS and/or SETTLE.
493 dd_move_x_constraints(cr->dd,
495 x.unpaddedArrayRef(),
496 xprime.unpaddedArrayRef(),
497 econq == ConstraintVariable::Positions);
501 /* We need to initialize the non-local components of v.
502 * We never actually use these values, but we do increment them,
503 * so we should avoid uninitialized variables and overflows.
505 clear_constraint_quantity_nonlocal(*cr->dd, v.unpaddedArrayRef());
509 if (lincsd != nullptr)
511 bOK = constrain_lincs(bLog || bEner,
523 hasMassPerturbedAtoms_,
527 v.unpaddedArrayRef(),
534 if (!bOK && maxwarn < INT_MAX)
539 "Constraint error in algorithm %s at step %s\n",
540 enumValueToString(ConstraintAlgorithm::Lincs),
541 gmx_step_str(step, buf));
547 if (shaked != nullptr)
549 bOK = constrain_shake(log,
554 x.unpaddedArrayRef(),
555 xprime.unpaddedArrayRef(),
562 v.unpaddedArrayRef(),
568 if (!bOK && maxwarn < INT_MAX)
573 "Constraint error in algorithm %s at step %s\n",
574 enumValueToString(ConstraintAlgorithm::Shake),
575 gmx_step_str(step, buf));
583 bool bSettleErrorHasOccurred0 = false;
587 case ConstraintVariable::Positions:
588 #pragma omp parallel for num_threads(nth) schedule(static)
589 for (int th = 0; th < nth; th++)
595 clear_mat(threadConstraintsVirial[th]);
607 th == 0 ? constraintsVirial : threadConstraintsVirial[th],
608 th == 0 ? &bSettleErrorHasOccurred0 : &bSettleErrorHasOccurred[th]);
610 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
612 inc_nrnb(nrnb, eNR_SETTLE, nsettle);
615 inc_nrnb(nrnb, eNR_CONSTR_V, nsettle * 3);
619 inc_nrnb(nrnb, eNR_CONSTR_VIR, nsettle * 3);
622 case ConstraintVariable::Velocities:
623 case ConstraintVariable::Derivative:
624 case ConstraintVariable::Force:
625 case ConstraintVariable::ForceDispl:
626 #pragma omp parallel for num_threads(nth) schedule(static)
627 for (int th = 0; th < nth; th++)
631 int calcvir_atom_end;
635 calcvir_atom_end = 0;
639 calcvir_atom_end = numHomeAtoms_;
644 clear_mat(threadConstraintsVirial[th]);
647 int start_th = (nsettle * th) / nth;
648 int end_th = (nsettle * (th + 1)) / nth;
650 if (start_th >= 0 && end_th - start_th > 0)
652 settle_proj(*settled,
655 settle.iatoms.data() + start_th * (1 + NRAL(F_SETTLE)),
657 x.unpaddedArrayRef(),
658 xprime.unpaddedArrayRef(),
661 th == 0 ? constraintsVirial : threadConstraintsVirial[th]);
664 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
666 /* This is an overestimate */
667 inc_nrnb(nrnb, eNR_SETTLE, nsettle);
669 case ConstraintVariable::Deriv_FlexCon:
670 /* Nothing to do, since the are no flexible constraints in settles */
672 default: gmx_incons("Unknown constraint quantity for settle");
677 /* Reduce the virial contributions over the threads */
678 for (int th = 1; th < nth; th++)
680 m_add(constraintsVirial, threadConstraintsVirial[th], constraintsVirial);
684 if (econq == ConstraintVariable::Positions)
686 for (int th = 1; th < nth; th++)
688 bSettleErrorHasOccurred0 = bSettleErrorHasOccurred0 || bSettleErrorHasOccurred[th];
691 if (bSettleErrorHasOccurred0)
697 ": One or more water molecules can not be settled.\n"
698 "Check for bad contacts and/or reduce the timestep if appropriate.\n",
702 fprintf(log, "%s", buf);
704 fprintf(stderr, "%s", buf);
706 if (warncount_settle > maxwarn)
708 too_many_constraint_warnings(ConstraintAlgorithm::Count, warncount_settle);
719 /* The normal uses of constrain() pass step_scaling = 1.0.
720 * The call to constrain() for SD1 that passes step_scaling =
721 * 0.5 also passes vir = NULL, so cannot reach this
722 * assertion. This assertion should remain until someone knows
723 * that this path works for their intended purpose, and then
724 * they can use scaled_delta_t instead of ir.delta_t
726 assert(gmx_within_tol(step_scaling, 1.0, GMX_REAL_EPS));
729 case ConstraintVariable::Positions: vir_fac = 0.5 / (ir.delta_t * ir.delta_t); break;
730 case ConstraintVariable::Velocities: vir_fac = 0.5 / ir.delta_t; break;
731 case ConstraintVariable::Force:
732 case ConstraintVariable::ForceDispl: vir_fac = 0.5; break;
733 default: gmx_incons("Unsupported constraint quantity for virial");
738 vir_fac *= 2; /* only constraining over half the distance here */
740 for (int i = 0; i < DIM; i++)
742 for (int j = 0; j < DIM; j++)
744 constraintsVirial[i][j] *= vir_fac;
751 dump_confs(log, step, mtop, start, numHomeAtoms_, cr, x.unpaddedArrayRef(), xprime.unpaddedArrayRef(), box);
754 if (econq == ConstraintVariable::Positions)
756 if (ir.bPull && pull_have_constraint(*pull_work))
758 if (EI_DYNAMICS(ir.eI))
760 t = ir.init_t + (step + delta_step) * ir.delta_t;
766 set_pbc(&pbc, ir.pbcType, box);
767 pull_constraint(pull_work,
773 x.unpaddedArrayRef(),
774 xprime.unpaddedArrayRef(),
775 v.unpaddedArrayRef(),
778 if (ed && delta_step > 0)
780 /* apply the essential dynamics constraints here */
784 as_rvec_array(xprime.unpaddedArrayRef().data()),
785 as_rvec_array(v.unpaddedArrayRef().data()),
790 wallcycle_stop(wcycle, ewcCONSTR);
792 const bool haveVelocities = (!v.empty() || econq == ConstraintVariable::Velocities);
793 if (haveVelocities && !cFREEZE_.empty())
795 /* Set the velocities of frozen dimensions to zero */
797 if (econq == ConstraintVariable::Velocities)
799 vRef = xprime.unpaddedArrayRef();
803 vRef = v.unpaddedArrayRef();
806 int gmx_unused numThreads = gmx_omp_nthreads_get(emntUpdate);
808 #pragma omp parallel for num_threads(numThreads) schedule(static)
809 for (int i = 0; i < numHomeAtoms_; i++)
811 int freezeGroup = cFREEZE_[i];
813 for (int d = 0; d < DIM; d++)
815 if (ir.opts.nFreeze[freezeGroup][d])
826 ArrayRef<real> Constraints::rmsdData() const
830 return lincs_rmsdData(impl_->lincsd);
838 real Constraints::rmsd() const
842 return lincs_rmsd(impl_->lincsd);
850 int Constraints::numConstraintsTotal()
852 return impl_->ncon_tot;
855 FlexibleConstraintTreatment flexibleConstraintTreatment(bool haveDynamicsIntegrator)
857 if (haveDynamicsIntegrator)
859 return FlexibleConstraintTreatment::Include;
863 return FlexibleConstraintTreatment::Exclude;
867 /*! \brief Returns a block struct to go from atoms to constraints
869 * The block struct will contain constraint indices with lower indices
870 * directly matching the order in F_CONSTR and higher indices matching
871 * the order in F_CONSTRNC offset by the number of constraints in F_CONSTR.
873 * \param[in] numAtoms The number of atoms to construct the list for
874 * \param[in] ilists The interaction lists, size F_NRE
875 * \param[in] iparams Interaction parameters, can be null when
876 * \p flexibleConstraintTreatment==Include
877 * \param[in] flexibleConstraintTreatment The flexible constraint treatment,
880 * \returns a block struct with all constraints for each atom
882 static ListOfLists<int> makeAtomsToConstraintsList(int numAtoms,
883 ArrayRef<const InteractionList> ilists,
884 ArrayRef<const t_iparams> iparams,
885 FlexibleConstraintTreatment flexibleConstraintTreatment)
887 GMX_ASSERT(flexibleConstraintTreatment == FlexibleConstraintTreatment::Include || !iparams.empty(),
888 "With flexible constraint detection we need valid iparams");
890 std::vector<int> count(numAtoms);
892 for (int ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
894 const InteractionList& ilist = ilists[ftype];
895 const int stride = 1 + NRAL(ftype);
896 for (int i = 0; i < ilist.size(); i += stride)
898 if (flexibleConstraintTreatment == FlexibleConstraintTreatment::Include
899 || !isConstraintFlexible(iparams, ilist.iatoms[i]))
901 for (int j = 1; j < 3; j++)
903 int a = ilist.iatoms[i + j];
910 std::vector<int> listRanges(numAtoms + 1);
911 for (int a = 0; a < numAtoms; a++)
913 listRanges[a + 1] = listRanges[a] + count[a];
916 std::vector<int> elements(listRanges[numAtoms]);
918 /* The F_CONSTRNC constraints have constraint numbers
919 * that continue after the last F_CONSTR constraint.
921 int numConstraints = 0;
922 for (int ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
924 const InteractionList& ilist = ilists[ftype];
925 const int stride = 1 + NRAL(ftype);
926 for (int i = 0; i < ilist.size(); i += stride)
928 if (flexibleConstraintTreatment == FlexibleConstraintTreatment::Include
929 || !isConstraintFlexible(iparams, ilist.iatoms[i]))
931 for (int j = 1; j < 3; j++)
933 const int a = ilist.iatoms[i + j];
934 elements[listRanges[a] + count[a]++] = numConstraints;
941 return ListOfLists<int>(std::move(listRanges), std::move(elements));
944 ListOfLists<int> make_at2con(int numAtoms,
945 ArrayRef<const InteractionList> ilist,
946 ArrayRef<const t_iparams> iparams,
947 FlexibleConstraintTreatment flexibleConstraintTreatment)
949 return makeAtomsToConstraintsList(numAtoms, ilist, iparams, flexibleConstraintTreatment);
952 ListOfLists<int> make_at2con(const gmx_moltype_t& moltype,
953 gmx::ArrayRef<const t_iparams> iparams,
954 FlexibleConstraintTreatment flexibleConstraintTreatment)
956 return makeAtomsToConstraintsList(
957 moltype.atoms.nr, makeConstArrayRef(moltype.ilist), iparams, flexibleConstraintTreatment);
960 //! Return the number of flexible constraints in the \c ilist and \c iparams.
961 int countFlexibleConstraints(ArrayRef<const InteractionList> ilist, ArrayRef<const t_iparams> iparams)
964 for (int ftype = F_CONSTR; ftype <= F_CONSTRNC; ftype++)
966 const int numIatomsPerConstraint = 3;
967 for (int i = 0; i < ilist[ftype].size(); i += numIatomsPerConstraint)
969 const int type = ilist[ftype].iatoms[i];
970 if (iparams[type].constr.dA == 0 && iparams[type].constr.dB == 0)
980 //! Returns the index of the settle to which each atom belongs.
981 static std::vector<int> make_at2settle(int natoms, const InteractionList& ilist)
983 /* Set all to no settle */
984 std::vector<int> at2s(natoms, -1);
986 const int stride = 1 + NRAL(F_SETTLE);
988 for (int s = 0; s < ilist.size(); s += stride)
990 at2s[ilist.iatoms[s + 1]] = s / stride;
991 at2s[ilist.iatoms[s + 2]] = s / stride;
992 at2s[ilist.iatoms[s + 3]] = s / stride;
998 void Constraints::Impl::setConstraints(gmx_localtop_t* top,
1001 gmx::ArrayRef<const real> masses,
1002 gmx::ArrayRef<const real> inverseMasses,
1003 const bool hasMassPerturbedAtoms,
1005 gmx::ArrayRef<const unsigned short> cFREEZE)
1007 numAtoms_ = numAtoms;
1008 numHomeAtoms_ = numHomeAtoms;
1010 inverseMasses_ = inverseMasses;
1011 hasMassPerturbedAtoms_ = hasMassPerturbedAtoms;
1019 /* With DD we might also need to call LINCS on a domain no constraints for
1020 * communicating coordinates to other nodes that do have constraints.
1022 if (ir.eConstrAlg == ConstraintAlgorithm::Lincs)
1024 set_lincs(*idef, numAtoms_, inverseMasses_, lambda_, EI_DYNAMICS(ir.eI), cr, lincsd);
1026 if (ir.eConstrAlg == ConstraintAlgorithm::Shake)
1030 // We are using the local topology, so there are only
1031 // F_CONSTR constraints.
1032 GMX_RELEASE_ASSERT(idef->il[F_CONSTRNC].empty(),
1033 "Here we should not have no-connect constraints");
1034 make_shake_sblock_dd(shaked.get(), idef->il[F_CONSTR]);
1038 make_shake_sblock_serial(shaked.get(), &top->idef, numAtoms_);
1045 settled->setConstraints(idef->il[F_SETTLE], numHomeAtoms_, masses_, inverseMasses_);
1048 /* Make a selection of the local atoms for essential dynamics */
1051 dd_make_local_ed_indices(cr->dd, ed);
1055 void Constraints::setConstraints(gmx_localtop_t* top,
1057 const int numHomeAtoms,
1058 gmx::ArrayRef<const real> masses,
1059 gmx::ArrayRef<const real> inverseMasses,
1060 const bool hasMassPerturbedAtoms,
1062 gmx::ArrayRef<const unsigned short> cFREEZE)
1064 impl_->setConstraints(
1065 top, numAtoms, numHomeAtoms, masses, inverseMasses, hasMassPerturbedAtoms, lambda, cFREEZE);
1068 /*! \brief Makes a per-moleculetype container of mappings from atom
1069 * indices to constraint indices.
1071 * Note that flexible constraints are only enabled with a dynamical integrator. */
1072 static std::vector<ListOfLists<int>> makeAtomToConstraintMappings(const gmx_mtop_t& mtop,
1073 FlexibleConstraintTreatment flexibleConstraintTreatment)
1075 std::vector<ListOfLists<int>> mapping;
1076 mapping.reserve(mtop.moltype.size());
1077 for (const gmx_moltype_t& moltype : mtop.moltype)
1079 mapping.push_back(make_at2con(moltype, mtop.ffparams.iparams, flexibleConstraintTreatment));
1084 Constraints::Constraints(const gmx_mtop_t& mtop,
1085 const t_inputrec& ir,
1088 const t_commrec* cr,
1089 const gmx_multisim_t* ms,
1091 gmx_wallcycle* wcycle,
1092 bool pbcHandlingRequired,
1095 impl_(new Impl(mtop, ir, pull_work, log, cr, ms, nrnb, wcycle, pbcHandlingRequired, numConstraints, numSettles))
1099 Constraints::Impl::Impl(const gmx_mtop_t& mtop_p,
1100 const t_inputrec& ir_p,
1103 const t_commrec* cr_p,
1104 const gmx_multisim_t* ms_p,
1106 gmx_wallcycle* wcycle_p,
1107 bool pbcHandlingRequired,
1110 ncon_tot(numConstraints),
1112 pbcHandlingRequired_(pbcHandlingRequired),
1116 pull_work(pull_work),
1121 if (numConstraints + numSettles > 0 && ir.epc == PressureCoupling::Mttk)
1123 gmx_fatal(FARGS, "Constraints are not implemented with MTTK pressure control.");
1127 if (numConstraints > 0)
1129 at2con_mt = makeAtomToConstraintMappings(mtop, flexibleConstraintTreatment(EI_DYNAMICS(ir.eI)));
1131 for (const gmx_molblock_t& molblock : mtop.molblock)
1133 int count = countFlexibleConstraints(mtop.moltype[molblock.type].ilist, mtop.ffparams.iparams);
1134 nflexcon += molblock.nmol * count;
1141 fprintf(log, "There are %d flexible constraints\n", nflexcon);
1142 if (ir.fc_stepsize == 0)
1146 "WARNING: step size for flexible constraining = 0\n"
1147 " All flexible constraints will be rigid.\n"
1148 " Will try to keep all flexible constraints at their original "
1150 " but the lengths may exhibit some drift.\n\n");
1156 please_cite(log, "Hess2002");
1160 if (ir.eConstrAlg == ConstraintAlgorithm::Lincs)
1162 lincsd = init_lincs(log,
1166 DOMAINDECOMP(cr) && ddHaveSplitConstraints(*cr->dd),
1171 if (ir.eConstrAlg == ConstraintAlgorithm::Shake)
1173 if (DOMAINDECOMP(cr) && ddHaveSplitConstraints(*cr->dd))
1176 "SHAKE is not supported with domain decomposition and constraint that "
1177 "cross domain boundaries, use LINCS");
1182 "For this system also velocities and/or forces need to be constrained, "
1183 "this can not be done with SHAKE, you should select LINCS");
1185 please_cite(log, "Ryckaert77a");
1188 please_cite(log, "Barth95a");
1191 shaked = std::make_unique<shakedata>();
1197 please_cite(log, "Miyamoto92a");
1199 settled = std::make_unique<SettleData>(mtop);
1201 /* Make an atom to settle index for use in domain decomposition */
1202 for (size_t mt = 0; mt < mtop.moltype.size(); mt++)
1204 at2settle_mt.emplace_back(
1205 make_at2settle(mtop.moltype[mt].atoms.nr, mtop.moltype[mt].ilist[F_SETTLE]));
1208 /* Allocate thread-local work arrays */
1209 int nthreads = gmx_omp_nthreads_get(emntSETTLE);
1210 if (nthreads > 1 && threadConstraintsVirial == nullptr)
1212 snew(threadConstraintsVirial, nthreads);
1213 snew(bSettleErrorHasOccurred, nthreads);
1218 char* env = getenv("GMX_MAXCONSTRWARN");
1222 sscanf(env, "%8d", &maxwarn);
1229 fprintf(log, "Setting the maximum number of constraint warnings to %d\n", maxwarn);
1233 fprintf(stderr, "Setting the maximum number of constraint warnings to %d\n", maxwarn);
1236 warncount_lincs = 0;
1237 warncount_settle = 0;
1240 Constraints::Impl::~Impl()
1242 if (bSettleErrorHasOccurred != nullptr)
1244 sfree(bSettleErrorHasOccurred);
1246 if (threadConstraintsVirial != nullptr)
1248 sfree(threadConstraintsVirial);
1253 void Constraints::saveEdsamPointer(gmx_edsam* ed)
1258 ArrayRef<const ListOfLists<int>> Constraints::atom2constraints_moltype() const
1260 return impl_->at2con_mt;
1263 ArrayRef<const std::vector<int>> Constraints::atom2settle_moltype() const
1265 return impl_->at2settle_mt;
1268 void do_constrain_first(FILE* fplog,
1269 gmx::Constraints* constr,
1270 const t_inputrec* ir,
1273 ArrayRefWithPadding<RVec> x,
1274 ArrayRefWithPadding<RVec> v,
1278 int i, m, start, end;
1280 real dt = ir->delta_t;
1283 PaddedVector<RVec> savex(numAtoms);
1290 fprintf(debug, "vcm: start=%d, homenr=%d, end=%d\n", start, numHomeAtoms, end);
1292 /* Do a first constrain to reset particles... */
1293 step = ir->init_step;
1296 char buf[STEPSTRSIZE];
1297 fprintf(fplog, "\nConstraining the starting coordinates (step %s)\n", gmx_step_str(step, buf));
1301 bool needsLogging = true;
1302 bool computeEnergy = false;
1303 bool computeVirial = false;
1304 /* constrain the current position */
1305 constr->apply(needsLogging,
1319 gmx::ConstraintVariable::Positions);
1322 /* constrain the inital velocity, and save it */
1323 /* also may be useful if we need the ekin from the halfstep for velocity verlet */
1324 constr->apply(needsLogging,
1331 v.unpaddedArrayRef(),
1338 gmx::ConstraintVariable::Velocities);
1340 /* constrain the inital velocities at t-dt/2 */
1341 if (EI_STATE_VELOCITY(ir->eI) && ir->eI != IntegrationAlgorithm::VV)
1343 auto subX = x.paddedArrayRef().subArray(start, end);
1344 auto subV = v.paddedArrayRef().subArray(start, end);
1345 for (i = start; (i < end); i++)
1347 for (m = 0; (m < DIM); m++)
1349 /* Reverse the velocity */
1350 subV[i][m] = -subV[i][m];
1351 /* Store the position at t-dt in buf */
1352 savex[i][m] = subX[i][m] + dt * subV[i][m];
1355 /* Shake the positions at t=-dt with the positions at t=0
1356 * as reference coordinates.
1360 char buf[STEPSTRSIZE];
1361 fprintf(fplog, "\nConstraining the coordinates at t0-dt (step %s)\n", gmx_step_str(step, buf));
1364 constr->apply(needsLogging,
1370 savex.arrayRefWithPadding(),
1378 gmx::ConstraintVariable::Positions);
1380 for (i = start; i < end; i++)
1382 for (m = 0; m < DIM; m++)
1384 /* Re-reverse the velocities */
1385 subV[i][m] = -subV[i][m];
1391 void constrain_velocities(gmx::Constraints* constr,
1397 gmx_bool computeVirial,
1398 tensor constraintsVirial)
1400 if (constr != nullptr)
1402 constr->apply(do_log,
1407 state->x.arrayRefWithPadding(),
1408 state->v.arrayRefWithPadding(),
1409 state->v.arrayRefWithPadding().unpaddedArrayRef(),
1411 state->lambda[FreeEnergyPerturbationCouplingType::Bonded],
1413 ArrayRefWithPadding<RVec>(),
1416 ConstraintVariable::Velocities);
1420 void constrain_coordinates(gmx::Constraints* constr,
1425 ArrayRefWithPadding<RVec> xp,
1427 gmx_bool computeVirial,
1428 tensor constraintsVirial)
1430 if (constr != nullptr)
1432 constr->apply(do_log,
1437 state->x.arrayRefWithPadding(),
1441 state->lambda[FreeEnergyPerturbationCouplingType::Bonded],
1443 state->v.arrayRefWithPadding(),
1446 ConstraintVariable::Positions);