2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2006 - 2014, The GROMACS development team.
5 * Copyright (c) 2015,2016,2017,2018,2019,2020,2021, by the GROMACS development team, led by
6 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7 * and including many others, as listed in the AUTHORS file in the
8 * top-level source directory and at http://www.gromacs.org.
10 * GROMACS is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public License
12 * as published by the Free Software Foundation; either version 2.1
13 * of the License, or (at your option) any later version.
15 * GROMACS is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with GROMACS; if not, see
22 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 * If you want to redistribute modifications to GROMACS, please
26 * consider that scientific software is very special. Version
27 * control is crucial - bugs must be traceable. We will be happy to
28 * consider code for inclusion in the official distribution, but
29 * derived work must not be called official GROMACS. Details are found
30 * in the README & COPYING files - if they are missing, get the
31 * official version at http://www.gromacs.org.
33 * To help us fund GROMACS development, we humbly ask that you cite
34 * the research papers on the package. Check out http://www.gromacs.org.
39 * \brief This file defines functions used by the domdec module
40 * while managing the construction, use and error checking for
41 * topologies local to a DD rank.
43 * \author Berk Hess <hess@kth.se>
44 * \ingroup module_domdec
58 #include "gromacs/domdec/domdec.h"
59 #include "gromacs/domdec/domdec_network.h"
60 #include "gromacs/domdec/ga2la.h"
61 #include "gromacs/domdec/options.h"
62 #include "gromacs/gmxlib/network.h"
63 #include "gromacs/math/vec.h"
64 #include "gromacs/mdlib/forcerec.h"
65 #include "gromacs/mdlib/gmx_omp_nthreads.h"
66 #include "gromacs/mdlib/vsite.h"
67 #include "gromacs/mdtypes/commrec.h"
68 #include "gromacs/mdtypes/forcerec.h"
69 #include "gromacs/mdtypes/inputrec.h"
70 #include "gromacs/mdtypes/md_enums.h"
71 #include "gromacs/mdtypes/mdatom.h"
72 #include "gromacs/mdtypes/state.h"
73 #include "gromacs/pbcutil/mshift.h"
74 #include "gromacs/pbcutil/pbc.h"
75 #include "gromacs/topology/ifunc.h"
76 #include "gromacs/topology/mtop_util.h"
77 #include "gromacs/topology/topsort.h"
78 #include "gromacs/utility/cstringutil.h"
79 #include "gromacs/utility/exceptions.h"
80 #include "gromacs/utility/fatalerror.h"
81 #include "gromacs/utility/gmxassert.h"
82 #include "gromacs/utility/listoflists.h"
83 #include "gromacs/utility/logger.h"
84 #include "gromacs/utility/smalloc.h"
85 #include "gromacs/utility/strconvert.h"
86 #include "gromacs/utility/stringstream.h"
87 #include "gromacs/utility/stringutil.h"
88 #include "gromacs/utility/textwriter.h"
90 #include "domdec_constraints.h"
91 #include "domdec_internal.h"
92 #include "domdec_vsite.h"
96 using gmx::DDBondedChecking;
97 using gmx::ListOfLists;
100 /*! \brief The number of integer item in the local state, used for broadcasting of the state */
101 #define NITEM_DD_INIT_LOCAL_STATE 5
103 struct reverse_ilist_t
105 std::vector<int> index; /* Index for each atom into il */
106 std::vector<int> il; /* ftype|type|a0|...|an|ftype|... */
107 int numAtomsInMolecule; /* The number of atoms in this molecule */
110 struct MolblockIndices
118 /*! \brief Struct for thread local work data for local topology generation */
121 /*! \brief Constructor
123 * \param[in] ffparams The interaction parameters, the lifetime of the created object should not exceed the lifetime of the passed parameters
125 thread_work_t(const gmx_ffparams_t& ffparams) : idef(ffparams) {}
127 InteractionDefinitions idef; /**< Partial local topology */
128 std::unique_ptr<gmx::VsitePbc> vsitePbc = nullptr; /**< vsite PBC structure */
129 int numBondedInteractions = 0; /**< The number of bonded interactions observed */
130 ListOfLists<int> excl; /**< List of exclusions */
133 /*! \brief Options for setting up gmx_reverse_top_t */
134 struct ReverseTopOptions
136 //! Constructor, constraints and settles are not including with a single argument
137 ReverseTopOptions(DDBondedChecking ddBondedChecking,
138 bool includeConstraints = false,
139 bool includeSettles = false) :
140 ddBondedChecking(ddBondedChecking),
141 includeConstraints(includeConstraints),
142 includeSettles(includeSettles)
146 //! \brief For which bonded interactions to check assignments
147 const DDBondedChecking ddBondedChecking;
148 //! \brief Whether constraints are stored in this reverse top
149 const bool includeConstraints;
150 //! \brief Whether settles are stored in this reverse top
151 const bool includeSettles;
154 /*! \brief Struct for the reverse topology: links bonded interactions to atoms */
155 struct gmx_reverse_top_t::Impl
157 //! Constructs a reverse topology from \p mtop
158 Impl(const gmx_mtop_t& mtop, bool useFreeEnergy, const ReverseTopOptions& reverseTopOptions);
160 //! @cond Doxygen_Suppress
161 //! Options for the setup of this reverse topology
162 const ReverseTopOptions options;
163 //! Are there interaction of type F_POSRES and/or F_FBPOSRES
164 bool havePositionRestraints;
165 //! \brief Are there bondeds/exclusions between atoms?
166 bool bInterAtomicInteractions = false;
167 //! \brief Reverse ilist for all moltypes
168 std::vector<reverse_ilist_t> ril_mt;
169 //! \brief The size of ril_mt[?].index summed over all entries
170 int ril_mt_tot_size = 0;
171 //! \brief The sorting state of bondeds for free energy
172 int ilsort = ilsortUNKNOWN;
173 //! \brief molblock to global atom index for quick lookup of molblocks on atom index
174 std::vector<MolblockIndices> mbi;
176 //! \brief Do we have intermolecular interactions?
177 bool bIntermolecularInteractions = false;
178 //! \brief Intermolecular reverse ilist
179 reverse_ilist_t ril_intermol;
181 /*! \brief Data to help check reverse topology construction
183 * Partitioning could incorrectly miss a bonded interaction.
184 * However, checking for that requires a global communication
185 * stage, which does not otherwise happen during partitioning. So,
186 * for performance, we do that alongside the first global energy
187 * reduction after a new DD is made. These variables handle
188 * whether the check happens, its input for this domain, output
189 * across all domains, and the expected value it should match. */
191 /*! \brief Number of bonded interactions found in the reverse
192 * topology for this domain. */
193 int numBondedInteractions = 0;
194 /*! \brief Whether to check at the next global communication
195 * stage the total number of bonded interactions found.
197 * Cleared after that number is found. */
198 bool shouldCheckNumberOfBondedInteractions = false;
199 /*! \brief The total number of bonded interactions found in
200 * the reverse topology across all domains.
202 * Only has a value after reduction across all ranks, which is
203 * removed when it is again time to check after a new
205 std::optional<int> numBondedInteractionsOverAllDomains;
206 //! The number of bonded interactions computed from the full topology
207 int expectedNumGlobalBondedInteractions = 0;
210 /* Work data structures for multi-threading */
211 //! \brief Thread work array for local topology generation
212 std::vector<thread_work_t> th_work;
217 /*! \brief Returns the number of atom entries for il in gmx_reverse_top_t */
218 static int nral_rt(int ftype)
220 int nral = NRAL(ftype);
221 if (interaction_function[ftype].flags & IF_VSITE)
223 /* With vsites the reverse topology contains an extra entry
224 * for storing if constructing atoms are vsites.
232 /*! \brief Return whether interactions of type \p ftype need to be assigned exactly once */
233 static gmx_bool dd_check_ftype(const int ftype, const ReverseTopOptions rtOptions)
235 return ((((interaction_function[ftype].flags & IF_BOND) != 0U)
236 && ((interaction_function[ftype].flags & IF_VSITE) == 0U)
237 && ((rtOptions.ddBondedChecking == DDBondedChecking::All)
238 || ((interaction_function[ftype].flags & IF_LIMZERO) == 0U)))
239 || (rtOptions.includeConstraints && (ftype == F_CONSTR || ftype == F_CONSTRNC))
240 || (rtOptions.includeSettles && ftype == F_SETTLE));
243 /*! \brief Checks whether interactions have been assigned for one function type
245 * Loops over a list of interactions in the local topology of one function type
246 * and flags each of the interactions as assigned in the global \p isAssigned list.
247 * Exits with an inconsistency error when an interaction is assigned more than once.
249 static void flagInteractionsForType(const int ftype,
250 const InteractionList& il,
251 const reverse_ilist_t& ril,
252 const gmx::Range<int>& atomRange,
253 const int numAtomsPerMolecule,
254 gmx::ArrayRef<const int> globalAtomIndices,
255 gmx::ArrayRef<int> isAssigned)
257 const int nril_mol = ril.index[numAtomsPerMolecule];
258 const int nral = NRAL(ftype);
260 for (int i = 0; i < il.size(); i += 1 + nral)
262 // ia[0] is the interaction type, ia[1, ...] the atom indices
263 const int* ia = il.iatoms.data() + i;
264 // Extract the global atom index of the first atom in this interaction
265 const int a0 = globalAtomIndices[ia[1]];
266 /* Check if this interaction is in
267 * the currently checked molblock.
269 if (atomRange.isInRange(a0))
271 // The molecule index in the list of this molecule type
272 const int moleculeIndex = (a0 - atomRange.begin()) / numAtomsPerMolecule;
273 const int atomOffset = (a0 - atomRange.begin()) - moleculeIndex * numAtomsPerMolecule;
274 const int globalAtomStartInMolecule = atomRange.begin() + moleculeIndex * numAtomsPerMolecule;
275 int j_mol = ril.index[atomOffset];
277 while (j_mol < ril.index[atomOffset + 1] && !found)
279 const int j = moleculeIndex * nril_mol + j_mol;
280 const int ftype_j = ril.il[j_mol];
281 /* Here we need to check if this interaction has
282 * not already been assigned, since we could have
283 * multiply defined interactions.
285 if (ftype == ftype_j && ia[0] == ril.il[j_mol + 1] && isAssigned[j] == 0)
287 /* Check the atoms */
289 for (int a = 0; a < nral; a++)
291 if (globalAtomIndices[ia[1 + a]]
292 != globalAtomStartInMolecule + ril.il[j_mol + 2 + a])
302 j_mol += 2 + nral_rt(ftype_j);
306 gmx_incons("Some interactions seem to be assigned multiple times");
312 /*! \brief Help print error output when interactions are missing in a molblock
314 * \note This function needs to be called on all ranks (contains a global summation)
316 static std::string printMissingInteractionsMolblock(t_commrec* cr,
317 const gmx_reverse_top_t& rt,
318 const char* moltypename,
319 const reverse_ilist_t& ril,
320 const gmx::Range<int>& atomRange,
321 const int numAtomsPerMolecule,
322 const int numMolecules,
323 const InteractionDefinitions& idef)
325 const int nril_mol = ril.index[numAtomsPerMolecule];
326 std::vector<int> isAssigned(numMolecules * nril_mol, 0);
327 gmx::StringOutputStream stream;
328 gmx::TextWriter log(&stream);
330 for (int ftype = 0; ftype < F_NRE; ftype++)
332 if (dd_check_ftype(ftype, rt.impl_->options))
334 flagInteractionsForType(
335 ftype, idef.il[ftype], ril, atomRange, numAtomsPerMolecule, cr->dd->globalAtomIndices, isAssigned);
339 gmx_sumi(isAssigned.size(), isAssigned.data(), cr);
341 const int numMissingToPrint = 10;
343 for (int mol = 0; mol < numMolecules; mol++)
346 while (j_mol < nril_mol)
348 int ftype = ril.il[j_mol];
349 int nral = NRAL(ftype);
350 int j = mol * nril_mol + j_mol;
351 if (isAssigned[j] == 0 && !(interaction_function[ftype].flags & IF_VSITE))
353 if (DDMASTER(cr->dd))
357 log.writeLineFormatted("Molecule type '%s'", moltypename);
358 log.writeLineFormatted(
359 "the first %d missing interactions, except for exclusions:",
362 log.writeStringFormatted("%20s atoms", interaction_function[ftype].longname);
364 for (; a < nral; a++)
366 log.writeStringFormatted("%5d", ril.il[j_mol + 2 + a] + 1);
370 log.writeString(" ");
373 log.writeString(" global");
374 for (int a = 0; a < nral; a++)
376 log.writeStringFormatted("%6d",
377 atomRange.begin() + mol * numAtomsPerMolecule
378 + ril.il[j_mol + 2 + a] + 1);
380 log.ensureLineBreak();
383 if (i >= numMissingToPrint)
388 j_mol += 2 + nral_rt(ftype);
392 return stream.toString();
395 /*! \brief Help print error output when interactions are missing */
396 static void printMissingInteractionsAtoms(const gmx::MDLogger& mdlog,
398 const gmx_mtop_t& mtop,
399 const InteractionDefinitions& idef)
401 const gmx_reverse_top_t& rt = *cr->dd->reverse_top;
403 /* Print the atoms in the missing interactions per molblock */
405 for (const gmx_molblock_t& molb : mtop.molblock)
407 const gmx_moltype_t& moltype = mtop.moltype[molb.type];
408 const int a_start = a_end;
409 a_end = a_start + molb.nmol * moltype.atoms.nr;
410 const gmx::Range<int> atomRange(a_start, a_end);
412 auto warning = printMissingInteractionsMolblock(
413 cr, rt, *(moltype.name), rt.impl_->ril_mt[molb.type], atomRange, moltype.atoms.nr, molb.nmol, idef);
415 GMX_LOG(mdlog.warning).appendText(warning);
419 void dd_print_missing_interactions(const gmx::MDLogger& mdlog,
421 int numBondedInteractionsOverAllDomains,
422 const gmx_mtop_t& top_global,
423 const gmx_localtop_t* top_local,
424 gmx::ArrayRef<const gmx::RVec> x,
428 gmx_domdec_t* dd = cr->dd;
430 GMX_LOG(mdlog.warning)
432 "Not all bonded interactions have been properly assigned to the domain "
433 "decomposition cells");
435 const int ndiff_tot = numBondedInteractionsOverAllDomains
436 - dd->reverse_top->impl_->expectedNumGlobalBondedInteractions;
438 for (int ftype = 0; ftype < F_NRE; ftype++)
440 const int nral = NRAL(ftype);
441 cl[ftype] = top_local->idef.il[ftype].size() / (1 + nral);
444 gmx_sumi(F_NRE, cl, cr);
448 GMX_LOG(mdlog.warning).appendText("A list of missing interactions:");
449 int rest_global = dd->reverse_top->impl_->expectedNumGlobalBondedInteractions;
450 int rest = numBondedInteractionsOverAllDomains;
451 for (int ftype = 0; ftype < F_NRE; ftype++)
453 /* In the reverse and local top all constraints are merged
454 * into F_CONSTR. So in the if statement we skip F_CONSTRNC
455 * and add these constraints when doing F_CONSTR.
457 if (dd_check_ftype(ftype, dd->reverse_top->impl_->options) && ftype != F_CONSTRNC)
459 int n = gmx_mtop_ftype_count(top_global, ftype);
460 if (ftype == F_CONSTR)
462 n += gmx_mtop_ftype_count(top_global, F_CONSTRNC);
464 int ndiff = cl[ftype] - n;
467 GMX_LOG(mdlog.warning)
468 .appendTextFormatted("%20s of %6d missing %6d",
469 interaction_function[ftype].longname,
478 int ndiff = rest - rest_global;
481 GMX_LOG(mdlog.warning).appendTextFormatted("%20s of %6d missing %6d", "exclusions", rest_global, -ndiff);
485 printMissingInteractionsAtoms(mdlog, cr, top_global, top_local->idef);
486 write_dd_pdb("dd_dump_err", 0, "dump", top_global, cr, -1, as_rvec_array(x.data()), box);
488 std::string errorMessage;
493 "One or more interactions were assigned to multiple domains of the domain "
494 "decompostion. Please report this bug.";
498 errorMessage = gmx::formatString(
499 "%d of the %d bonded interactions could not be calculated because some atoms "
500 "involved moved further apart than the multi-body cut-off distance (%g nm) or the "
501 "two-body cut-off distance (%g nm), see option -rdd, for pairs and tabulated bonds "
502 "also see option -ddcheck",
504 dd->reverse_top->impl_->expectedNumGlobalBondedInteractions,
505 dd_cutoff_multibody(dd),
506 dd_cutoff_twobody(dd));
508 gmx_fatal_collective(FARGS, cr->mpi_comm_mygroup, MASTER(cr), "%s", errorMessage.c_str());
511 /*! \brief Return global topology molecule information for global atom index \p i_gl */
512 static void global_atomnr_to_moltype_ind(ArrayRef<const MolblockIndices> molblockIndices,
519 const MolblockIndices* mbi = molblockIndices.data();
521 int end = molblockIndices.size(); /* exclusive */
524 /* binary search for molblock_ind */
527 mid = (start + end) / 2;
528 if (i_gl >= mbi[mid].a_end)
532 else if (i_gl < mbi[mid].a_start)
546 *mol = (i_gl - mbi->a_start) / mbi->natoms_mol;
547 *i_mol = (i_gl - mbi->a_start) - (*mol) * mbi->natoms_mol;
550 /*! \brief Returns the maximum number of exclusions per atom */
551 static int getMaxNumExclusionsPerAtom(const ListOfLists<int>& excls)
554 for (gmx::index at = 0; at < excls.ssize(); at++)
556 const auto list = excls[at];
557 const int numExcls = list.ssize();
559 GMX_RELEASE_ASSERT(numExcls != 1 || list[0] == at,
560 "With 1 exclusion we expect a self-exclusion");
562 maxNumExcls = std::max(maxNumExcls, numExcls);
568 //! Options for linking atoms in make_reverse_ilist
569 enum class AtomLinkRule
571 FirstAtom, //!< Link all interactions to the first atom in the atom list
572 AllAtomsInBondeds //!< Link bonded interactions to all atoms involved, don't link vsites
575 /*! \brief Run the reverse ilist generation and store it in r_il when \p bAssign = TRUE */
576 static int low_make_reverse_ilist(const InteractionLists& il_mt,
579 const ReverseTopOptions& rtOptions,
580 gmx::ArrayRef<const int> r_index,
581 gmx::ArrayRef<int> r_il,
582 const AtomLinkRule atomLinkRule,
583 const bool assignReverseIlist)
585 const bool includeConstraints = rtOptions.includeConstraints;
586 const bool includeSettles = rtOptions.includeSettles;
587 const DDBondedChecking ddBondedChecking = rtOptions.ddBondedChecking;
591 for (int ftype = 0; ftype < F_NRE; ftype++)
593 if ((interaction_function[ftype].flags & (IF_BOND | IF_VSITE))
594 || (includeConstraints && (ftype == F_CONSTR || ftype == F_CONSTRNC))
595 || (includeSettles && ftype == F_SETTLE))
597 const bool isVSite = ((interaction_function[ftype].flags & IF_VSITE) != 0U);
598 const int nral = NRAL(ftype);
599 const auto& il = il_mt[ftype];
600 for (int i = 0; i < il.size(); i += 1 + nral)
602 const int* ia = il.iatoms.data() + i;
603 // Virtual sites should not be linked for bonded interactions
604 const int nlink = (atomLinkRule == AtomLinkRule::FirstAtom) ? 1 : (isVSite ? 0 : nral);
605 for (int link = 0; link < nlink; link++)
607 const int a = ia[1 + link];
608 if (assignReverseIlist)
610 GMX_ASSERT(!r_il.empty(), "with bAssign not allowed to be empty");
611 GMX_ASSERT(!r_index.empty(), "with bAssign not allowed to be empty");
612 r_il[r_index[a] + count[a]] = (ftype == F_CONSTRNC ? F_CONSTR : ftype);
613 r_il[r_index[a] + count[a] + 1] = ia[0];
614 for (int j = 1; j < 1 + nral; j++)
616 /* Store the molecular atom number */
617 r_il[r_index[a] + count[a] + 1 + j] = ia[j];
620 if (interaction_function[ftype].flags & IF_VSITE)
622 if (assignReverseIlist)
624 /* Add an entry to iatoms for storing
625 * which of the constructing atoms are
628 r_il[r_index[a] + count[a] + 2 + nral] = 0;
629 for (int j = 2; j < 1 + nral; j++)
631 if (atom[ia[j]].ptype == ParticleType::VSite)
633 r_il[r_index[a] + count[a] + 2 + nral] |= (2 << j);
640 /* We do not count vsites since they are always
641 * uniquely assigned and can be assigned
642 * to multiple nodes with recursive vsites.
644 if (ddBondedChecking == DDBondedChecking::All
645 || !(interaction_function[ftype].flags & IF_LIMZERO))
650 count[a] += 2 + nral_rt(ftype);
659 /*! \brief Make the reverse ilist: a list of bonded interactions linked to atoms */
660 static int make_reverse_ilist(const InteractionLists& ilist,
661 const t_atoms* atoms,
662 const ReverseTopOptions& rtOptions,
663 const AtomLinkRule atomLinkRule,
664 reverse_ilist_t* ril_mt)
666 /* Count the interactions */
667 const int nat_mt = atoms->nr;
668 std::vector<int> count(nat_mt);
669 low_make_reverse_ilist(ilist, atoms->atom, count.data(), rtOptions, {}, {}, atomLinkRule, FALSE);
671 ril_mt->index.push_back(0);
672 for (int i = 0; i < nat_mt; i++)
674 ril_mt->index.push_back(ril_mt->index[i] + count[i]);
677 ril_mt->il.resize(ril_mt->index[nat_mt]);
679 /* Store the interactions */
680 int nint_mt = low_make_reverse_ilist(
681 ilist, atoms->atom, count.data(), rtOptions, ril_mt->index, ril_mt->il, atomLinkRule, TRUE);
683 ril_mt->numAtomsInMolecule = atoms->nr;
688 gmx_reverse_top_t::gmx_reverse_top_t(const gmx_mtop_t& mtop,
690 const ReverseTopOptions& reverseTopOptions) :
691 impl_(std::make_unique<Impl>(mtop, useFreeEnergy, reverseTopOptions))
695 gmx_reverse_top_t::~gmx_reverse_top_t() {}
697 /*! \brief Generate the reverse topology */
698 gmx_reverse_top_t::Impl::Impl(const gmx_mtop_t& mtop,
699 const bool useFreeEnergy,
700 const ReverseTopOptions& reverseTopOptions) :
701 options(reverseTopOptions),
702 havePositionRestraints(
703 gmx_mtop_ftype_count(mtop, F_POSRES) + gmx_mtop_ftype_count(mtop, F_FBPOSRES) > 0),
704 bInterAtomicInteractions(mtop.bIntermolecularInteractions)
706 bInterAtomicInteractions = mtop.bIntermolecularInteractions;
707 ril_mt.resize(mtop.moltype.size());
709 std::vector<int> nint_mt;
710 for (size_t mt = 0; mt < mtop.moltype.size(); mt++)
712 const gmx_moltype_t& molt = mtop.moltype[mt];
713 if (molt.atoms.nr > 1)
715 bInterAtomicInteractions = true;
718 /* Make the atom to interaction list for this molecule type */
719 int numberOfInteractions = make_reverse_ilist(
720 molt.ilist, &molt.atoms, options, AtomLinkRule::FirstAtom, &ril_mt[mt]);
721 nint_mt.push_back(numberOfInteractions);
723 ril_mt_tot_size += ril_mt[mt].index[molt.atoms.nr];
727 fprintf(debug, "The total size of the atom to interaction index is %d integers\n", ril_mt_tot_size);
730 expectedNumGlobalBondedInteractions = 0;
731 for (const gmx_molblock_t& molblock : mtop.molblock)
733 expectedNumGlobalBondedInteractions += molblock.nmol * nint_mt[molblock.type];
736 /* Make an intermolecular reverse top, if necessary */
737 bIntermolecularInteractions = mtop.bIntermolecularInteractions;
738 if (bIntermolecularInteractions)
740 t_atoms atoms_global;
742 atoms_global.nr = mtop.natoms;
743 atoms_global.atom = nullptr; /* Only used with virtual sites */
745 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
746 "We should have an ilist when intermolecular interactions are on");
748 expectedNumGlobalBondedInteractions += make_reverse_ilist(
749 *mtop.intermolecular_ilist, &atoms_global, options, AtomLinkRule::FirstAtom, &ril_intermol);
752 if (useFreeEnergy && gmx_mtop_bondeds_free_energy(&mtop))
754 ilsort = ilsortFE_UNSORTED;
758 ilsort = ilsortNO_FE;
761 /* Make a molblock index for fast searching */
763 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
765 const gmx_molblock_t& molb = mtop.molblock[mb];
766 const int numAtomsPerMol = mtop.moltype[molb.type].atoms.nr;
767 MolblockIndices mbiMolblock;
768 mbiMolblock.a_start = i;
769 i += molb.nmol * numAtomsPerMol;
770 mbiMolblock.a_end = i;
771 mbiMolblock.natoms_mol = numAtomsPerMol;
772 mbiMolblock.type = molb.type;
773 mbi.push_back(mbiMolblock);
776 for (int th = 0; th < gmx_omp_nthreads_get(ModuleMultiThread::Domdec); th++)
778 th_work.emplace_back(mtop.ffparams);
782 void dd_make_reverse_top(FILE* fplog,
784 const gmx_mtop_t& mtop,
785 const gmx::VirtualSitesHandler* vsite,
786 const t_inputrec& inputrec,
787 const DDBondedChecking ddBondedChecking)
791 fprintf(fplog, "\nLinking all bonded interactions to atoms\n");
794 /* If normal and/or settle constraints act only within charge groups,
795 * we can store them in the reverse top and simply assign them to domains.
796 * Otherwise we need to assign them to multiple domains and set up
797 * the parallel version constraint algorithm(s).
799 GMX_RELEASE_ASSERT(ddBondedChecking == DDBondedChecking::ExcludeZeroLimit
800 || ddBondedChecking == DDBondedChecking::All,
801 "Invalid enum value for mdrun -ddcheck");
802 const ReverseTopOptions rtOptions(ddBondedChecking,
803 !dd->comm->systemInfo.mayHaveSplitConstraints,
804 !dd->comm->systemInfo.mayHaveSplitSettles);
806 dd->reverse_top = std::make_unique<gmx_reverse_top_t>(
807 mtop, inputrec.efep != FreeEnergyPerturbationType::No, rtOptions);
809 dd->haveExclusions = false;
810 for (const gmx_molblock_t& molb : mtop.molblock)
812 const int maxNumExclusionsPerAtom = getMaxNumExclusionsPerAtom(mtop.moltype[molb.type].excls);
813 // We checked above that max 1 exclusion means only self exclusions
814 if (maxNumExclusionsPerAtom > 1)
816 dd->haveExclusions = true;
820 const int numInterUpdategroupVirtualSites =
821 (vsite == nullptr ? 0 : vsite->numInterUpdategroupVirtualSites());
822 if (numInterUpdategroupVirtualSites > 0)
827 "There are %d inter update-group virtual sites,\n"
828 "will perform an extra communication step for selected coordinates and "
830 numInterUpdategroupVirtualSites);
832 init_domdec_vsites(dd, numInterUpdategroupVirtualSites);
835 if (dd->comm->systemInfo.mayHaveSplitConstraints || dd->comm->systemInfo.mayHaveSplitSettles)
837 init_domdec_constraints(dd, mtop);
841 fprintf(fplog, "\n");
845 /*! \brief Store a vsite interaction at the end of \p il
847 * This routine is very similar to add_ifunc, but vsites interactions
848 * have more work to do than other kinds of interactions, and the
849 * complex way nral (and thus vector contents) depends on ftype
850 * confuses static analysis tools unless we fuse the vsite
851 * atom-indexing organization code with the ifunc-adding code, so that
852 * they can see that nral is the same value. */
853 static inline void add_ifunc_for_vsites(t_iatom* tiatoms,
854 const gmx_ga2la_t& ga2la,
860 const t_iatom* iatoms,
864 tiatoms[0] = iatoms[0];
868 /* We know the local index of the first atom */
873 /* Convert later in make_local_vsites */
874 tiatoms[1] = -a_gl - 1;
877 GMX_ASSERT(nral >= 2 && nral <= 5, "Invalid nral for vsites");
878 for (int k = 2; k < 1 + nral; k++)
880 int ak_gl = a_gl + iatoms[k] - a_mol;
881 if (const int* homeIndex = ga2la.findHome(ak_gl))
883 tiatoms[k] = *homeIndex;
887 /* Copy the global index, convert later in make_local_vsites */
888 tiatoms[k] = -(ak_gl + 1);
890 // Note that ga2la_get_home always sets the third parameter if
893 il->push_back(tiatoms[0], nral, tiatoms + 1);
896 /*! \brief Store a position restraint in idef and iatoms, complex because the parameters are different for each entry */
897 static void add_posres(int mol,
899 int numAtomsInMolecule,
900 const gmx_molblock_t& molb,
901 gmx::ArrayRef<int> iatoms,
902 const t_iparams* ip_in,
903 InteractionDefinitions* idef)
905 /* This position restraint has not been added yet,
906 * so it's index is the current number of position restraints.
908 const int n = idef->il[F_POSRES].size() / 2;
910 /* Get the position restraint coordinates from the molblock */
911 const int a_molb = mol * numAtomsInMolecule + a_mol;
912 GMX_ASSERT(a_molb < ssize(molb.posres_xA),
913 "We need a sufficient number of position restraint coordinates");
914 /* Copy the force constants */
915 t_iparams ip = ip_in[iatoms[0]];
916 ip.posres.pos0A[XX] = molb.posres_xA[a_molb][XX];
917 ip.posres.pos0A[YY] = molb.posres_xA[a_molb][YY];
918 ip.posres.pos0A[ZZ] = molb.posres_xA[a_molb][ZZ];
919 if (!molb.posres_xB.empty())
921 ip.posres.pos0B[XX] = molb.posres_xB[a_molb][XX];
922 ip.posres.pos0B[YY] = molb.posres_xB[a_molb][YY];
923 ip.posres.pos0B[ZZ] = molb.posres_xB[a_molb][ZZ];
927 ip.posres.pos0B[XX] = ip.posres.pos0A[XX];
928 ip.posres.pos0B[YY] = ip.posres.pos0A[YY];
929 ip.posres.pos0B[ZZ] = ip.posres.pos0A[ZZ];
931 /* Set the parameter index for idef->iparams_posres */
933 idef->iparams_posres.push_back(ip);
935 GMX_ASSERT(int(idef->iparams_posres.size()) == n + 1,
936 "The index of the parameter type should match n");
939 /*! \brief Store a flat-bottomed position restraint in idef and iatoms, complex because the parameters are different for each entry */
940 static void add_fbposres(int mol,
942 int numAtomsInMolecule,
943 const gmx_molblock_t& molb,
944 gmx::ArrayRef<int> iatoms,
945 const t_iparams* ip_in,
946 InteractionDefinitions* idef)
948 /* This flat-bottom position restraint has not been added yet,
949 * so it's index is the current number of position restraints.
951 const int n = idef->il[F_FBPOSRES].size() / 2;
953 /* Get the position restraint coordinats from the molblock */
954 const int a_molb = mol * numAtomsInMolecule + a_mol;
955 GMX_ASSERT(a_molb < ssize(molb.posres_xA),
956 "We need a sufficient number of position restraint coordinates");
957 /* Copy the force constants */
958 t_iparams ip = ip_in[iatoms[0]];
959 /* Take reference positions from A position of normal posres */
960 ip.fbposres.pos0[XX] = molb.posres_xA[a_molb][XX];
961 ip.fbposres.pos0[YY] = molb.posres_xA[a_molb][YY];
962 ip.fbposres.pos0[ZZ] = molb.posres_xA[a_molb][ZZ];
964 /* Note: no B-type for flat-bottom posres */
966 /* Set the parameter index for idef->iparams_fbposres */
968 idef->iparams_fbposres.push_back(ip);
970 GMX_ASSERT(int(idef->iparams_fbposres.size()) == n + 1,
971 "The index of the parameter type should match n");
974 /*! \brief Store a virtual site interaction, complex because of PBC and recursion */
975 static void add_vsite(const gmx_ga2la_t& ga2la,
976 gmx::ArrayRef<const int> index,
977 gmx::ArrayRef<const int> rtil,
984 const t_iatom* iatoms,
985 InteractionDefinitions* idef)
987 t_iatom tiatoms[1 + MAXATOMLIST];
989 /* Add this interaction to the local topology */
990 add_ifunc_for_vsites(tiatoms, ga2la, nral, bHomeA, a, a_gl, a_mol, iatoms, &idef->il[ftype]);
992 if (iatoms[1 + nral])
994 /* Check for recursion */
995 for (int k = 2; k < 1 + nral; k++)
997 if ((iatoms[1 + nral] & (2 << k)) && (tiatoms[k] < 0))
999 /* This construction atoms is a vsite and not a home atom */
1003 "Constructing atom %d of vsite atom %d is a vsite and non-home\n",
1007 /* Find the vsite construction */
1009 /* Check all interactions assigned to this atom */
1010 int j = index[iatoms[k]];
1011 while (j < index[iatoms[k] + 1])
1013 int ftype_r = rtil[j++];
1014 int nral_r = NRAL(ftype_r);
1015 if (interaction_function[ftype_r].flags & IF_VSITE)
1017 /* Add this vsite (recursion) */
1025 a_gl + iatoms[k] - iatoms[1],
1030 j += 1 + nral_rt(ftype_r);
1037 /*! \brief Returns the squared distance between atoms \p i and \p j */
1038 static real dd_dist2(const t_pbc* pbc_null, ArrayRef<const RVec> coordinates, const int i, const int j)
1044 pbc_dx_aiuc(pbc_null, coordinates[i], coordinates[j], dx);
1048 rvec_sub(coordinates[i], coordinates[j], dx);
1054 /*! \brief Append t_idef structures 1 to nsrc in src to *dest */
1055 static void combine_idef(InteractionDefinitions* dest, gmx::ArrayRef<const thread_work_t> src)
1057 for (int ftype = 0; ftype < F_NRE; ftype++)
1060 for (gmx::index s = 1; s < src.ssize(); s++)
1062 n += src[s].idef.il[ftype].size();
1066 for (gmx::index s = 1; s < src.ssize(); s++)
1068 dest->il[ftype].append(src[s].idef.il[ftype]);
1071 /* Position restraints need an additional treatment */
1072 if (ftype == F_POSRES || ftype == F_FBPOSRES)
1074 int nposres = dest->il[ftype].size() / 2;
1075 std::vector<t_iparams>& iparams_dest =
1076 (ftype == F_POSRES ? dest->iparams_posres : dest->iparams_fbposres);
1078 /* Set nposres to the number of original position restraints in dest */
1079 for (gmx::index s = 1; s < src.ssize(); s++)
1081 nposres -= src[s].idef.il[ftype].size() / 2;
1084 for (gmx::index s = 1; s < src.ssize(); s++)
1086 const std::vector<t_iparams>& iparams_src =
1087 (ftype == F_POSRES ? src[s].idef.iparams_posres : src[s].idef.iparams_fbposres);
1088 iparams_dest.insert(iparams_dest.end(), iparams_src.begin(), iparams_src.end());
1090 /* Correct the indices into iparams_posres */
1091 for (int i = 0; i < src[s].idef.il[ftype].size() / 2; i++)
1093 /* Correct the index into iparams_posres */
1094 dest->il[ftype].iatoms[nposres * 2] = nposres;
1099 int(iparams_dest.size()) == nposres,
1100 "The number of parameters should match the number of restraints");
1106 //! Options for assigning interactions for atoms
1107 enum class InteractionConnectivity
1109 Intramolecular, //!< Only intra-molecular interactions
1110 Intermolecular //!< Only inter-molecular interactions
1113 /*! \brief Determine whether the local domain has responsibility for
1114 * any of the bonded interactions for local atom \p atomIndex
1115 * and assign those to the local domain.
1117 * \returns The total number of bonded interactions for this atom for
1118 * which this domain is responsible.
1120 template<InteractionConnectivity interactionConnectivity>
1121 static inline int assignInteractionsForAtom(const int atomIndex,
1122 const int globalAtomIndex,
1123 const int atomIndexInMolecule,
1124 gmx::ArrayRef<const int> index,
1125 gmx::ArrayRef<const int> rtil,
1126 const int ind_start,
1128 const gmx_ga2la_t& ga2la,
1129 const gmx_domdec_zones_t* zones,
1130 const bool checkDistanceMultiBody,
1132 const bool checkDistanceTwoBody,
1133 const real cutoffSquared,
1134 const t_pbc* pbc_null,
1135 ArrayRef<const RVec> coordinates,
1136 InteractionDefinitions* idef,
1138 const DDBondedChecking ddBondedChecking)
1140 gmx::ArrayRef<const DDPairInteractionRanges> iZones = zones->iZones;
1142 int numBondedInteractions = 0;
1147 t_iatom tiatoms[1 + MAXATOMLIST];
1149 const int ftype = rtil[j++];
1150 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
1151 const int nral = NRAL(ftype);
1152 if (interaction_function[ftype].flags & IF_VSITE)
1154 GMX_ASSERT(interactionConnectivity == InteractionConnectivity::Intramolecular,
1155 "All vsites should be intramolecular");
1157 /* The vsite construction goes where the vsite itself is */
1168 atomIndexInMolecule,
1178 tiatoms[0] = iatoms[0];
1182 GMX_ASSERT(interactionConnectivity == InteractionConnectivity::Intramolecular,
1183 "All interactions that involve a single atom are intramolecular");
1185 /* Assign single-body interactions to the home zone.
1186 * Position restraints are not handled here, but separately.
1188 if (iz == 0 && !(ftype == F_POSRES || ftype == F_FBPOSRES))
1191 tiatoms[1] = atomIndex;
1196 /* This is a two-body interaction, we can assign
1197 * analogous to the non-bonded assignments.
1199 const int k_gl = (interactionConnectivity == InteractionConnectivity::Intramolecular)
1201 /* Get the global index using the offset in the molecule */
1202 (globalAtomIndex + iatoms[2] - atomIndexInMolecule)
1204 if (const auto* entry = ga2la.find(k_gl))
1206 int kz = entry->cell;
1211 /* Check zone interaction assignments */
1212 bUse = ((iz < iZones.ssize() && iz <= kz && iZones[iz].jZoneRange.isInRange(kz))
1213 || (kz < iZones.ssize() && iz > kz && iZones[kz].jZoneRange.isInRange(iz)));
1216 GMX_ASSERT(ftype != F_CONSTR || (iz == 0 && kz == 0),
1217 "Constraint assigned here should only involve home atoms");
1219 tiatoms[1] = atomIndex;
1220 tiatoms[2] = entry->la;
1221 /* If necessary check the cgcm distance */
1222 if (checkDistanceTwoBody
1223 && dd_dist2(pbc_null, coordinates, tiatoms[1], tiatoms[2]) >= cutoffSquared)
1236 /* Assign this multi-body bonded interaction to
1237 * the local domain if we have all the atoms involved
1238 * (local or communicated) and the minimum zone shift
1239 * in each dimension is zero, for dimensions
1240 * with 2 DD cells an extra check may be necessary.
1242 ivec k_zero, k_plus;
1246 for (int k = 1; k <= nral && bUse; k++)
1249 (interactionConnectivity == InteractionConnectivity::Intramolecular)
1251 /* Get the global index using the offset in the molecule */
1252 (globalAtomIndex + iatoms[k] - atomIndexInMolecule)
1254 const auto* entry = ga2la.find(k_gl);
1255 if (entry == nullptr || entry->cell >= zones->n)
1257 /* We do not have this atom of this interaction
1258 * locally, or it comes from more than one cell
1265 tiatoms[k] = entry->la;
1266 for (int d = 0; d < DIM; d++)
1268 if (zones->shift[entry->cell][d] == 0)
1279 bUse = (bUse && (k_zero[XX] != 0) && (k_zero[YY] != 0) && (k_zero[ZZ] != 0));
1280 if (checkDistanceMultiBody)
1282 for (int d = 0; (d < DIM && bUse); d++)
1284 /* Check if the distance falls within
1285 * the cut-off to avoid possible multiple
1286 * assignments of bonded interactions.
1288 if (rcheck[d] && k_plus[d]
1289 && dd_dist2(pbc_null, coordinates, tiatoms[k_zero[d]], tiatoms[k_plus[d]])
1299 /* Add this interaction to the local topology */
1300 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms + 1);
1301 /* Sum so we can check in global_stat
1302 * if we have everything.
1304 if (ddBondedChecking == DDBondedChecking::All
1305 || !(interaction_function[ftype].flags & IF_LIMZERO))
1307 numBondedInteractions++;
1311 j += 1 + nral_rt(ftype);
1314 return numBondedInteractions;
1317 /*! \brief Determine whether the local domain has responsibility for
1318 * any of the position restraints for local atom \p atomIndex
1319 * and assign those to the local domain.
1321 * \returns The total number of bonded interactions for this atom for
1322 * which this domain is responsible.
1324 static inline int assignPositionRestraintsForAtom(const int atomIndex,
1326 const int atomIndexInMolecule,
1327 const int numAtomsInMolecule,
1328 gmx::ArrayRef<const int> rtil,
1329 const int ind_start,
1331 const gmx_molblock_t& molb,
1332 const t_iparams* ip_in,
1333 InteractionDefinitions* idef)
1335 constexpr int nral = 1;
1337 int numBondedInteractions = 0;
1342 const int ftype = rtil[j++];
1343 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
1345 if (ftype == F_POSRES || ftype == F_FBPOSRES)
1347 std::array<int, 1 + nral> tiatoms = { iatoms[0], atomIndex };
1348 if (ftype == F_POSRES)
1350 add_posres(mol, atomIndexInMolecule, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1354 add_fbposres(mol, atomIndexInMolecule, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1356 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms.data() + 1);
1357 numBondedInteractions++;
1359 j += 1 + nral_rt(ftype);
1362 return numBondedInteractions;
1365 /*! \brief This function looks up and assigns bonded interactions for zone iz.
1367 * With thread parallelizing each thread acts on a different atom range:
1368 * at_start to at_end.
1370 static int make_bondeds_zone(gmx_reverse_top_t* rt,
1371 ArrayRef<const int> globalAtomIndices,
1372 const gmx_ga2la_t& ga2la,
1373 const gmx_domdec_zones_t* zones,
1374 const std::vector<gmx_molblock_t>& molb,
1375 const bool checkDistanceMultiBody,
1377 const bool checkDistanceTwoBody,
1378 const real cutoffSquared,
1379 const t_pbc* pbc_null,
1380 ArrayRef<const RVec> coordinates,
1381 const t_iparams* ip_in,
1382 InteractionDefinitions* idef,
1384 const gmx::Range<int>& atomRange)
1389 int atomIndexInMolecule = 0;
1391 const auto ddBondedChecking = rt->impl_->options.ddBondedChecking;
1393 int numBondedInteractions = 0;
1395 for (int i : atomRange)
1397 /* Get the global atom number */
1398 const int globalAtomIndex = globalAtomIndices[i];
1399 global_atomnr_to_moltype_ind(rt->impl_->mbi, globalAtomIndex, &mb, &mt, &mol, &atomIndexInMolecule);
1400 /* Check all intramolecular interactions assigned to this atom */
1401 gmx::ArrayRef<const int> index = rt->impl_->ril_mt[mt].index;
1402 gmx::ArrayRef<const t_iatom> rtil = rt->impl_->ril_mt[mt].il;
1404 numBondedInteractions += assignInteractionsForAtom<InteractionConnectivity::Intramolecular>(
1407 atomIndexInMolecule,
1410 index[atomIndexInMolecule],
1411 index[atomIndexInMolecule + 1],
1414 checkDistanceMultiBody,
1416 checkDistanceTwoBody,
1424 // Assign position restraints, when present, for the home zone
1425 if (izone == 0 && rt->impl_->havePositionRestraints)
1427 numBondedInteractions +=
1428 assignPositionRestraintsForAtom(i,
1430 atomIndexInMolecule,
1431 rt->impl_->ril_mt[mt].numAtomsInMolecule,
1433 index[atomIndexInMolecule],
1434 index[atomIndexInMolecule + 1],
1440 if (rt->impl_->bIntermolecularInteractions)
1442 /* Check all intermolecular interactions assigned to this atom */
1443 index = rt->impl_->ril_intermol.index;
1444 rtil = rt->impl_->ril_intermol.il;
1446 numBondedInteractions += assignInteractionsForAtom<InteractionConnectivity::Intermolecular>(
1452 index[globalAtomIndex],
1453 index[globalAtomIndex + 1],
1456 checkDistanceMultiBody,
1458 checkDistanceTwoBody,
1468 return numBondedInteractions;
1471 /*! \brief Set the exclusion data for i-zone \p iz */
1472 static void make_exclusions_zone(ArrayRef<const int> globalAtomIndices,
1473 const gmx_ga2la_t& ga2la,
1474 gmx_domdec_zones_t* zones,
1475 ArrayRef<const MolblockIndices> molblockIndices,
1476 const std::vector<gmx_moltype_t>& moltype,
1478 ListOfLists<int>* lexcls,
1482 const gmx::ArrayRef<const int> intermolecularExclusionGroup)
1484 const auto& jAtomRange = zones->iZones[iz].jAtomRange;
1486 const gmx::index oldNumLists = lexcls->ssize();
1488 std::vector<int> exclusionsForAtom;
1489 for (int at = at_start; at < at_end; at++)
1491 exclusionsForAtom.clear();
1493 if (GET_CGINFO_EXCL_INTER(cginfo[at]))
1500 /* Copy the exclusions from the global top */
1501 int a_gl = globalAtomIndices[at];
1502 global_atomnr_to_moltype_ind(molblockIndices, a_gl, &mb, &mt, &mol, &a_mol);
1503 const auto excls = moltype[mt].excls[a_mol];
1504 for (const int aj_mol : excls)
1506 if (const auto* jEntry = ga2la.find(a_gl + aj_mol - a_mol))
1508 /* This check is not necessary, but it can reduce
1509 * the number of exclusions in the list, which in turn
1510 * can speed up the pair list construction a bit.
1512 if (jAtomRange.isInRange(jEntry->la))
1514 exclusionsForAtom.push_back(jEntry->la);
1520 bool isExcludedAtom = !intermolecularExclusionGroup.empty()
1521 && std::find(intermolecularExclusionGroup.begin(),
1522 intermolecularExclusionGroup.end(),
1523 globalAtomIndices[at])
1524 != intermolecularExclusionGroup.end();
1528 for (int qmAtomGlobalIndex : intermolecularExclusionGroup)
1530 if (const auto* entry = ga2la.find(qmAtomGlobalIndex))
1532 exclusionsForAtom.push_back(entry->la);
1537 /* Append the exclusions for this atom to the topology */
1538 lexcls->pushBack(exclusionsForAtom);
1542 lexcls->ssize() - oldNumLists == at_end - at_start,
1543 "The number of exclusion list should match the number of atoms in the range");
1546 /*! \brief Generate and store all required local bonded interactions in \p idef and local exclusions in \p lexcls */
1547 static void make_local_bondeds_excls(gmx_domdec_t* dd,
1548 gmx_domdec_zones_t* zones,
1549 const gmx_mtop_t& mtop,
1551 const bool checkDistanceMultiBody,
1553 const gmx_bool checkDistanceTwoBody,
1555 const t_pbc* pbc_null,
1556 ArrayRef<const RVec> coordinates,
1557 InteractionDefinitions* idef,
1558 ListOfLists<int>* lexcls)
1560 int nzone_bondeds = 0;
1562 if (dd->reverse_top->impl_->bInterAtomicInteractions)
1564 nzone_bondeds = zones->n;
1568 /* Only single charge group (or atom) molecules, so interactions don't
1569 * cross zone boundaries and we only need to assign in the home zone.
1574 /* We only use exclusions from i-zones to i- and j-zones */
1575 const int numIZonesForExclusions = (dd->haveExclusions ? zones->iZones.size() : 0);
1577 gmx_reverse_top_t* rt = dd->reverse_top.get();
1579 const real cutoffSquared = gmx::square(cutoff);
1581 /* Clear the counts */
1583 dd->reverse_top->impl_->numBondedInteractions = 0;
1587 for (int izone = 0; izone < nzone_bondeds; izone++)
1589 const int cg0 = zones->cg_range[izone];
1590 const int cg1 = zones->cg_range[izone + 1];
1592 const int numThreads = rt->impl_->th_work.size();
1593 #pragma omp parallel for num_threads(numThreads) schedule(static)
1594 for (int thread = 0; thread < numThreads; thread++)
1598 InteractionDefinitions* idef_t = nullptr;
1600 int cg0t = cg0 + ((cg1 - cg0) * thread) / numThreads;
1601 int cg1t = cg0 + ((cg1 - cg0) * (thread + 1)) / numThreads;
1609 idef_t = &rt->impl_->th_work[thread].idef;
1613 rt->impl_->th_work[thread].numBondedInteractions =
1614 make_bondeds_zone(rt,
1615 dd->globalAtomIndices,
1619 checkDistanceMultiBody,
1621 checkDistanceTwoBody,
1625 idef->iparams.data(),
1628 gmx::Range<int>(cg0t, cg1t));
1630 if (izone < numIZonesForExclusions)
1632 ListOfLists<int>* excl_t = nullptr;
1635 // Thread 0 stores exclusions directly in the final storage
1640 // Threads > 0 store in temporary storage, starting at list index 0
1641 excl_t = &rt->impl_->th_work[thread].excl;
1645 /* No charge groups and no distance check required */
1646 make_exclusions_zone(dd->globalAtomIndices,
1656 mtop.intermolecularExclusionGroup);
1659 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1662 if (rt->impl_->th_work.size() > 1)
1664 combine_idef(idef, rt->impl_->th_work);
1667 for (const thread_work_t& th_work : rt->impl_->th_work)
1669 dd->reverse_top->impl_->numBondedInteractions += th_work.numBondedInteractions;
1672 if (izone < numIZonesForExclusions)
1674 for (std::size_t th = 1; th < rt->impl_->th_work.size(); th++)
1676 lexcls->appendListOfLists(rt->impl_->th_work[th].excl);
1681 // Note that it's possible for this to still be true from the last
1682 // time it was set, e.g. if repartitioning was triggered before
1683 // global communication that would have acted on the true
1684 // value. This could happen for example when replica exchange took
1685 // place soon after a partition.
1686 dd->reverse_top->impl_->shouldCheckNumberOfBondedInteractions = true;
1687 // Clear the old global value, which is now invalid
1688 dd->reverse_top->impl_->numBondedInteractionsOverAllDomains.reset();
1692 fprintf(debug, "We have %d exclusions\n", lexcls->numElements());
1696 bool shouldCheckNumberOfBondedInteractions(const gmx_domdec_t& dd)
1698 return dd.reverse_top->impl_->shouldCheckNumberOfBondedInteractions;
1701 int numBondedInteractions(const gmx_domdec_t& dd)
1703 return dd.reverse_top->impl_->numBondedInteractions;
1706 void setNumberOfBondedInteractionsOverAllDomains(const gmx_domdec_t& dd, int newValue)
1708 GMX_RELEASE_ASSERT(!dd.reverse_top->impl_->numBondedInteractionsOverAllDomains.has_value(),
1709 "Cannot set number of bonded interactions because it is already set");
1710 dd.reverse_top->impl_->numBondedInteractionsOverAllDomains.emplace(newValue);
1713 void checkNumberOfBondedInteractions(const gmx::MDLogger& mdlog,
1715 const gmx_mtop_t& top_global,
1716 const gmx_localtop_t* top_local,
1717 gmx::ArrayRef<const gmx::RVec> x,
1722 "No need to check number of bonded interactions when not using domain decomposition");
1723 if (cr->dd->reverse_top->impl_->shouldCheckNumberOfBondedInteractions)
1725 GMX_RELEASE_ASSERT(cr->dd->reverse_top->impl_->numBondedInteractionsOverAllDomains.has_value(),
1726 "The check for the total number of bonded interactions requires the "
1727 "value to have been reduced across all domains");
1728 if (cr->dd->reverse_top->impl_->numBondedInteractionsOverAllDomains.value()
1729 != cr->dd->reverse_top->impl_->expectedNumGlobalBondedInteractions)
1731 dd_print_missing_interactions(
1734 cr->dd->reverse_top->impl_->numBondedInteractionsOverAllDomains.value(),
1738 box); // Does not return
1740 // Now that the value is set and the check complete, future
1741 // global communication should not compute the value until
1742 // after the next partitioning.
1743 cr->dd->reverse_top->impl_->shouldCheckNumberOfBondedInteractions = false;
1747 void dd_make_local_top(gmx_domdec_t* dd,
1748 gmx_domdec_zones_t* zones,
1754 ArrayRef<const RVec> coordinates,
1755 const gmx_mtop_t& mtop,
1756 gmx_localtop_t* ltop)
1760 t_pbc pbc, *pbc_null = nullptr;
1764 fprintf(debug, "Making local topology\n");
1767 bool checkDistanceMultiBody = false;
1768 bool checkDistanceTwoBody = false;
1770 if (dd->reverse_top->impl_->bInterAtomicInteractions)
1772 /* We need to check to which cell bondeds should be assigned */
1773 rc = dd_cutoff_twobody(dd);
1776 fprintf(debug, "Two-body bonded cut-off distance is %g\n", rc);
1779 /* Should we check distances when assigning bonded interactions? */
1780 for (int d = 0; d < DIM; d++)
1783 /* Only need to check for dimensions where the part of the box
1784 * that is not communicated is smaller than the cut-off.
1786 if (d < npbcdim && dd->numCells[d] > 1
1787 && (dd->numCells[d] - npulse[d]) * cellsize_min[d] < 2 * rc)
1789 if (dd->numCells[d] == 2)
1792 checkDistanceMultiBody = TRUE;
1794 /* Check for interactions between two atoms,
1795 * where we can allow interactions up to the cut-off,
1796 * instead of up to the smallest cell dimension.
1798 checkDistanceTwoBody = TRUE;
1803 "dim %d cellmin %f bonded rcheck[%d] = %d, checkDistanceTwoBody = %s\n",
1808 gmx::boolToString(checkDistanceTwoBody));
1811 if (checkDistanceMultiBody || checkDistanceTwoBody)
1815 pbc_null = set_pbc_dd(&pbc, fr->pbcType, dd->numCells, TRUE, box);
1824 make_local_bondeds_excls(dd,
1828 checkDistanceMultiBody,
1830 checkDistanceTwoBody,
1837 /* The ilist is not sorted yet,
1838 * we can only do this when we have the charge arrays.
1840 ltop->idef.ilsort = ilsortUNKNOWN;
1843 void dd_sort_local_top(const gmx_domdec_t& dd, const t_mdatoms* mdatoms, gmx_localtop_t* ltop)
1845 if (dd.reverse_top->impl_->ilsort == ilsortNO_FE)
1847 ltop->idef.ilsort = ilsortNO_FE;
1851 gmx_sort_ilist_fe(<op->idef, mdatoms->chargeA, mdatoms->chargeB);
1855 void dd_init_local_state(const gmx_domdec_t& dd, const t_state* state_global, t_state* state_local)
1857 int buf[NITEM_DD_INIT_LOCAL_STATE];
1861 buf[0] = state_global->flags;
1862 buf[1] = state_global->ngtc;
1863 buf[2] = state_global->nnhpres;
1864 buf[3] = state_global->nhchainlength;
1865 buf[4] = state_global->dfhist ? state_global->dfhist->nlambda : 0;
1867 dd_bcast(&dd, NITEM_DD_INIT_LOCAL_STATE * sizeof(int), buf);
1869 init_gtc_state(state_local, buf[1], buf[2], buf[3]);
1870 init_dfhist_state(state_local, buf[4]);
1871 state_local->flags = buf[0];
1874 /*! \brief Check if a link is stored in \p link between charge groups \p cg_gl and \p cg_gl_j and if not so, store a link */
1875 static void check_link(t_blocka* link, int cg_gl, int cg_gl_j)
1877 bool bFound = false;
1878 for (int k = link->index[cg_gl]; k < link->index[cg_gl + 1]; k++)
1880 GMX_RELEASE_ASSERT(link->a, "Inconsistent NULL pointer while making charge-group links");
1881 if (link->a[k] == cg_gl_j)
1888 GMX_RELEASE_ASSERT(link->a || link->index[cg_gl + 1] + 1 > link->nalloc_a,
1889 "Inconsistent allocation of link");
1890 /* Add this charge group link */
1891 if (link->index[cg_gl + 1] + 1 > link->nalloc_a)
1893 link->nalloc_a = over_alloc_large(link->index[cg_gl + 1] + 1);
1894 srenew(link->a, link->nalloc_a);
1896 link->a[link->index[cg_gl + 1]] = cg_gl_j;
1897 link->index[cg_gl + 1]++;
1901 t_blocka* makeBondedLinks(const gmx_mtop_t& mtop, gmx::ArrayRef<cginfo_mb_t> cginfo_mb)
1903 t_blocka* link = nullptr;
1905 /* For each atom make a list of other atoms in the system
1906 * that a linked to it via bonded interactions
1907 * which are also stored in reverse_top.
1910 reverse_ilist_t ril_intermol;
1911 if (mtop.bIntermolecularInteractions)
1915 atoms.nr = mtop.natoms;
1916 atoms.atom = nullptr;
1918 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
1919 "We should have an ilist when intermolecular interactions are on");
1921 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1923 *mtop.intermolecular_ilist, &atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril_intermol);
1927 snew(link->index, mtop.natoms + 1);
1934 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
1936 const gmx_molblock_t& molb = mtop.molblock[mb];
1941 const gmx_moltype_t& molt = mtop.moltype[molb.type];
1942 /* Make a reverse ilist in which the interactions are linked
1943 * to all atoms, not only the first atom as in gmx_reverse_top.
1944 * The constraints are discarded here.
1946 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1947 reverse_ilist_t ril;
1948 make_reverse_ilist(molt.ilist, &molt.atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril);
1950 cginfo_mb_t* cgi_mb = &cginfo_mb[mb];
1953 for (mol = 0; mol < (mtop.bIntermolecularInteractions ? molb.nmol : 1); mol++)
1955 for (int a = 0; a < molt.atoms.nr; a++)
1957 int cg_gl = cg_offset + a;
1958 link->index[cg_gl + 1] = link->index[cg_gl];
1959 int i = ril.index[a];
1960 while (i < ril.index[a + 1])
1962 int ftype = ril.il[i++];
1963 int nral = NRAL(ftype);
1964 /* Skip the ifunc index */
1966 for (int j = 0; j < nral; j++)
1968 int aj = ril.il[i + j];
1971 check_link(link, cg_gl, cg_offset + aj);
1974 i += nral_rt(ftype);
1977 if (mtop.bIntermolecularInteractions)
1979 int i = ril_intermol.index[cg_gl];
1980 while (i < ril_intermol.index[cg_gl + 1])
1982 int ftype = ril_intermol.il[i++];
1983 int nral = NRAL(ftype);
1984 /* Skip the ifunc index */
1986 for (int j = 0; j < nral; j++)
1988 /* Here we assume we have no charge groups;
1989 * this has been checked above.
1991 int aj = ril_intermol.il[i + j];
1992 check_link(link, cg_gl, aj);
1994 i += nral_rt(ftype);
1997 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0)
1999 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[a]);
2004 cg_offset += molt.atoms.nr;
2006 int nlink_mol = link->index[cg_offset] - link->index[cg_offset - molt.atoms.nr];
2011 "molecule type '%s' %d atoms has %d atom links through bonded interac.\n",
2017 if (molb.nmol > mol)
2019 /* Copy the data for the rest of the molecules in this block */
2020 link->nalloc_a += (molb.nmol - mol) * nlink_mol;
2021 srenew(link->a, link->nalloc_a);
2022 for (; mol < molb.nmol; mol++)
2024 for (int a = 0; a < molt.atoms.nr; a++)
2026 int cg_gl = cg_offset + a;
2027 link->index[cg_gl + 1] = link->index[cg_gl + 1 - molt.atoms.nr] + nlink_mol;
2028 for (int j = link->index[cg_gl]; j < link->index[cg_gl + 1]; j++)
2030 link->a[j] = link->a[j - nlink_mol] + molt.atoms.nr;
2032 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0
2033 && cg_gl - cgi_mb->cg_start < cgi_mb->cg_mod)
2035 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[cg_gl - cgi_mb->cg_start]);
2039 cg_offset += molt.atoms.nr;
2046 fprintf(debug, "Of the %d atoms %d are linked via bonded interactions\n", mtop.natoms, ncgi);
2058 } bonded_distance_t;
2060 /*! \brief Compare distance^2 \p r2 against the distance in \p bd and if larger store it along with \p ftype and atom indices \p a1 and \p a2 */
2061 static void update_max_bonded_distance(real r2, int ftype, int a1, int a2, bonded_distance_t* bd)
2072 /*! \brief Set the distance, function type and atom indices for the longest distance between atoms of molecule type \p molt for two-body and multi-body bonded interactions */
2073 static void bonded_cg_distance_mol(const gmx_moltype_t* molt,
2074 const DDBondedChecking ddBondedChecking,
2076 ArrayRef<const RVec> x,
2077 bonded_distance_t* bd_2b,
2078 bonded_distance_t* bd_mb)
2080 const ReverseTopOptions rtOptions(ddBondedChecking);
2082 for (int ftype = 0; ftype < F_NRE; ftype++)
2084 if (dd_check_ftype(ftype, rtOptions))
2086 const auto& il = molt->ilist[ftype];
2087 int nral = NRAL(ftype);
2090 for (int i = 0; i < il.size(); i += 1 + nral)
2092 for (int ai = 0; ai < nral; ai++)
2094 int atomI = il.iatoms[i + 1 + ai];
2095 for (int aj = ai + 1; aj < nral; aj++)
2097 int atomJ = il.iatoms[i + 1 + aj];
2100 real rij2 = distance2(x[atomI], x[atomJ]);
2102 update_max_bonded_distance(
2103 rij2, ftype, atomI, atomJ, (nral == 2) ? bd_2b : bd_mb);
2113 const auto& excls = molt->excls;
2114 for (gmx::index ai = 0; ai < excls.ssize(); ai++)
2116 for (const int aj : excls[ai])
2120 real rij2 = distance2(x[ai], x[aj]);
2122 /* There is no function type for exclusions, use -1 */
2123 update_max_bonded_distance(rij2, -1, ai, aj, bd_2b);
2130 /*! \brief Set the distance, function type and atom indices for the longest atom distance involved in intermolecular interactions for two-body and multi-body bonded interactions */
2131 static void bonded_distance_intermol(const InteractionLists& ilists_intermol,
2132 const DDBondedChecking ddBondedChecking,
2133 ArrayRef<const RVec> x,
2136 bonded_distance_t* bd_2b,
2137 bonded_distance_t* bd_mb)
2141 set_pbc(&pbc, pbcType, box);
2143 const ReverseTopOptions rtOptions(ddBondedChecking);
2145 for (int ftype = 0; ftype < F_NRE; ftype++)
2147 if (dd_check_ftype(ftype, rtOptions))
2149 const auto& il = ilists_intermol[ftype];
2150 int nral = NRAL(ftype);
2152 /* No nral>1 check here, since intermol interactions always
2153 * have nral>=2 (and the code is also correct for nral=1).
2155 for (int i = 0; i < il.size(); i += 1 + nral)
2157 for (int ai = 0; ai < nral; ai++)
2159 int atom_i = il.iatoms[i + 1 + ai];
2161 for (int aj = ai + 1; aj < nral; aj++)
2165 int atom_j = il.iatoms[i + 1 + aj];
2167 pbc_dx(&pbc, x[atom_i], x[atom_j], dx);
2169 const real rij2 = norm2(dx);
2171 update_max_bonded_distance(rij2, ftype, atom_i, atom_j, (nral == 2) ? bd_2b : bd_mb);
2179 //! Returns whether \p molt has at least one virtual site
2180 static bool moltypeHasVsite(const gmx_moltype_t& molt)
2182 bool hasVsite = false;
2183 for (int i = 0; i < F_NRE; i++)
2185 if ((interaction_function[i].flags & IF_VSITE) && !molt.ilist[i].empty())
2194 //! Returns coordinates not broken over PBC for a molecule
2195 static void getWholeMoleculeCoordinates(const gmx_moltype_t* molt,
2196 const gmx_ffparams_t* ffparams,
2200 ArrayRef<const RVec> x,
2203 if (pbcType != PbcType::No)
2205 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(x.data()));
2207 shift_x(graph, box, as_rvec_array(x.data()), as_rvec_array(xs.data()));
2208 /* By doing an extra mk_mshift the molecules that are broken
2209 * because they were e.g. imported from another software
2210 * will be made whole again. Such are the healing powers
2213 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(xs.data()));
2217 /* We copy the coordinates so the original coordinates remain
2218 * unchanged, just to be 100% sure that we do not affect
2219 * binary reproducibility of simulations.
2221 for (int i = 0; i < molt->atoms.nr; i++)
2223 copy_rvec(x[i], xs[i]);
2227 if (moltypeHasVsite(*molt))
2229 gmx::constructVirtualSites(xs, ffparams->iparams, molt->ilist);
2233 void dd_bonded_cg_distance(const gmx::MDLogger& mdlog,
2234 const gmx_mtop_t& mtop,
2235 const t_inputrec& inputrec,
2236 ArrayRef<const RVec> x,
2238 const DDBondedChecking ddBondedChecking,
2242 bonded_distance_t bd_2b = { 0, -1, -1, -1 };
2243 bonded_distance_t bd_mb = { 0, -1, -1, -1 };
2245 bool bExclRequired = inputrecExclForces(&inputrec);
2250 for (const gmx_molblock_t& molb : mtop.molblock)
2252 const gmx_moltype_t& molt = mtop.moltype[molb.type];
2253 if (molt.atoms.nr == 1 || molb.nmol == 0)
2255 at_offset += molb.nmol * molt.atoms.nr;
2260 if (inputrec.pbcType != PbcType::No)
2262 graph = mk_graph_moltype(molt);
2265 std::vector<RVec> xs(molt.atoms.nr);
2266 for (int mol = 0; mol < molb.nmol; mol++)
2268 getWholeMoleculeCoordinates(&molt,
2273 x.subArray(at_offset, molt.atoms.nr),
2276 bonded_distance_t bd_mol_2b = { 0, -1, -1, -1 };
2277 bonded_distance_t bd_mol_mb = { 0, -1, -1, -1 };
2279 bonded_cg_distance_mol(&molt, ddBondedChecking, bExclRequired, xs, &bd_mol_2b, &bd_mol_mb);
2281 /* Process the mol data adding the atom index offset */
2282 update_max_bonded_distance(bd_mol_2b.r2,
2284 at_offset + bd_mol_2b.a1,
2285 at_offset + bd_mol_2b.a2,
2287 update_max_bonded_distance(bd_mol_mb.r2,
2289 at_offset + bd_mol_mb.a1,
2290 at_offset + bd_mol_mb.a2,
2293 at_offset += molt.atoms.nr;
2298 if (mtop.bIntermolecularInteractions)
2300 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
2301 "We should have an ilist when intermolecular interactions are on");
2303 bonded_distance_intermol(
2304 *mtop.intermolecular_ilist, ddBondedChecking, x, inputrec.pbcType, box, &bd_2b, &bd_mb);
2307 *r_2b = sqrt(bd_2b.r2);
2308 *r_mb = sqrt(bd_mb.r2);
2310 if (*r_2b > 0 || *r_mb > 0)
2312 GMX_LOG(mdlog.info).appendText("Initial maximum distances in bonded interactions:");
2316 .appendTextFormatted(
2317 " two-body bonded interactions: %5.3f nm, %s, atoms %d %d",
2319 (bd_2b.ftype >= 0) ? interaction_function[bd_2b.ftype].longname : "Exclusion",
2326 .appendTextFormatted(
2327 " multi-body bonded interactions: %5.3f nm, %s, atoms %d %d",
2329 interaction_function[bd_mb.ftype].longname,