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/localtopologychecker.h"
62 #include "gromacs/domdec/options.h"
63 #include "gromacs/domdec/reversetopology.h"
64 #include "gromacs/gmxlib/network.h"
65 #include "gromacs/math/vec.h"
66 #include "gromacs/mdlib/forcerec.h"
67 #include "gromacs/mdlib/gmx_omp_nthreads.h"
68 #include "gromacs/mdlib/vsite.h"
69 #include "gromacs/mdtypes/commrec.h"
70 #include "gromacs/mdtypes/forcerec.h"
71 #include "gromacs/mdtypes/inputrec.h"
72 #include "gromacs/mdtypes/md_enums.h"
73 #include "gromacs/mdtypes/mdatom.h"
74 #include "gromacs/mdtypes/state.h"
75 #include "gromacs/pbcutil/mshift.h"
76 #include "gromacs/pbcutil/pbc.h"
77 #include "gromacs/topology/mtop_util.h"
78 #include "gromacs/topology/topsort.h"
79 #include "gromacs/utility/cstringutil.h"
80 #include "gromacs/utility/exceptions.h"
81 #include "gromacs/utility/fatalerror.h"
82 #include "gromacs/utility/gmxassert.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 /*! \brief Struct for the reverse topology: links bonded interactions to atoms */
104 struct gmx_reverse_top_t::Impl
106 //! Constructs a reverse topology from \p mtop
107 Impl(const gmx_mtop_t& mtop, bool useFreeEnergy, const ReverseTopOptions& reverseTopOptions);
109 //! @cond Doxygen_Suppress
110 //! Options for the setup of this reverse topology
111 const ReverseTopOptions options;
112 //! Are there interaction of type F_POSRES and/or F_FBPOSRES
113 bool hasPositionRestraints;
114 //! \brief Are there bondeds/exclusions between atoms?
115 bool bInterAtomicInteractions = false;
116 //! \brief Reverse ilist for all moltypes
117 std::vector<reverse_ilist_t> ril_mt;
118 //! \brief The size of ril_mt[?].index summed over all entries
119 int ril_mt_tot_size = 0;
120 //! \brief The sorting state of bondeds for free energy
121 int ilsort = ilsortUNKNOWN;
122 //! \brief molblock to global atom index for quick lookup of molblocks on atom index
123 std::vector<MolblockIndices> mbi;
125 //! \brief Do we have intermolecular interactions?
126 bool bIntermolecularInteractions = false;
127 //! \brief Intermolecular reverse ilist
128 reverse_ilist_t ril_intermol;
130 /*! \brief Data to help check reverse topology construction
132 * Partitioning could incorrectly miss a bonded interaction.
133 * However, checking for that requires a global communication
134 * stage, which does not otherwise happen during partitioning. So,
135 * for performance, we do that alongside the first global energy
136 * reduction after a new DD is made. These variables handle
137 * whether the check happens, its input for this domain, output
138 * across all domains, and the expected value it should match. */
140 /*! \brief Number of bonded interactions found in the reverse
141 * topology for this domain. */
142 int numBondedInteractions = 0;
143 /*! \brief Whether to check at the next global communication
144 * stage the total number of bonded interactions found.
146 * Cleared after that number is found. */
147 bool shouldCheckNumberOfBondedInteractions = false;
148 /*! \brief The total number of bonded interactions found in
149 * the reverse topology across all domains.
151 * Only has a value after reduction across all ranks, which is
152 * removed when it is again time to check after a new
154 std::optional<int> numBondedInteractionsOverAllDomains;
155 //! The number of bonded interactions computed from the full topology
156 int expectedNumGlobalBondedInteractions = 0;
159 /* Work data structures for multi-threading */
160 //! \brief Thread work array for local topology generation
161 std::vector<thread_work_t> th_work;
166 /*! \brief Returns the number of atom entries for il in gmx_reverse_top_t */
167 static int nral_rt(int ftype)
169 int nral = NRAL(ftype);
170 if (interaction_function[ftype].flags & IF_VSITE)
172 /* With vsites the reverse topology contains an extra entry
173 * for storing if constructing atoms are vsites.
181 /*! \brief Return whether interactions of type \p ftype need to be assigned exactly once */
182 static gmx_bool dd_check_ftype(const int ftype, const ReverseTopOptions rtOptions)
184 return ((((interaction_function[ftype].flags & IF_BOND) != 0U)
185 && ((interaction_function[ftype].flags & IF_VSITE) == 0U)
186 && ((rtOptions.ddBondedChecking == DDBondedChecking::All)
187 || ((interaction_function[ftype].flags & IF_LIMZERO) == 0U)))
188 || (rtOptions.includeConstraints && (ftype == F_CONSTR || ftype == F_CONSTRNC))
189 || (rtOptions.includeSettles && ftype == F_SETTLE));
192 /*! \brief Checks whether interactions have been assigned for one function type
194 * Loops over a list of interactions in the local topology of one function type
195 * and flags each of the interactions as assigned in the global \p isAssigned list.
196 * Exits with an inconsistency error when an interaction is assigned more than once.
198 static void flagInteractionsForType(const int ftype,
199 const InteractionList& il,
200 const reverse_ilist_t& ril,
201 const gmx::Range<int>& atomRange,
202 const int numAtomsPerMolecule,
203 gmx::ArrayRef<const int> globalAtomIndices,
204 gmx::ArrayRef<int> isAssigned)
206 const int nril_mol = ril.index[numAtomsPerMolecule];
207 const int nral = NRAL(ftype);
209 for (int i = 0; i < il.size(); i += 1 + nral)
211 // ia[0] is the interaction type, ia[1, ...] the atom indices
212 const int* ia = il.iatoms.data() + i;
213 // Extract the global atom index of the first atom in this interaction
214 const int a0 = globalAtomIndices[ia[1]];
215 /* Check if this interaction is in
216 * the currently checked molblock.
218 if (atomRange.isInRange(a0))
220 // The molecule index in the list of this molecule type
221 const int moleculeIndex = (a0 - atomRange.begin()) / numAtomsPerMolecule;
222 const int atomOffset = (a0 - atomRange.begin()) - moleculeIndex * numAtomsPerMolecule;
223 const int globalAtomStartInMolecule = atomRange.begin() + moleculeIndex * numAtomsPerMolecule;
224 int j_mol = ril.index[atomOffset];
226 while (j_mol < ril.index[atomOffset + 1] && !found)
228 const int j = moleculeIndex * nril_mol + j_mol;
229 const int ftype_j = ril.il[j_mol];
230 /* Here we need to check if this interaction has
231 * not already been assigned, since we could have
232 * multiply defined interactions.
234 if (ftype == ftype_j && ia[0] == ril.il[j_mol + 1] && isAssigned[j] == 0)
236 /* Check the atoms */
238 for (int a = 0; a < nral; a++)
240 if (globalAtomIndices[ia[1 + a]]
241 != globalAtomStartInMolecule + ril.il[j_mol + 2 + a])
251 j_mol += 2 + nral_rt(ftype_j);
255 gmx_incons("Some interactions seem to be assigned multiple times");
261 /*! \brief Help print error output when interactions are missing in a molblock
263 * \note This function needs to be called on all ranks (contains a global summation)
265 static std::string printMissingInteractionsMolblock(t_commrec* cr,
266 const gmx_reverse_top_t& rt,
267 const char* moltypename,
268 const reverse_ilist_t& ril,
269 const gmx::Range<int>& atomRange,
270 const int numAtomsPerMolecule,
271 const int numMolecules,
272 const InteractionDefinitions& idef)
274 const int nril_mol = ril.index[numAtomsPerMolecule];
275 std::vector<int> isAssigned(numMolecules * nril_mol, 0);
276 gmx::StringOutputStream stream;
277 gmx::TextWriter log(&stream);
279 for (int ftype = 0; ftype < F_NRE; ftype++)
281 if (dd_check_ftype(ftype, rt.options()))
283 flagInteractionsForType(
284 ftype, idef.il[ftype], ril, atomRange, numAtomsPerMolecule, cr->dd->globalAtomIndices, isAssigned);
288 gmx_sumi(isAssigned.size(), isAssigned.data(), cr);
290 const int numMissingToPrint = 10;
292 for (int mol = 0; mol < numMolecules; mol++)
295 while (j_mol < nril_mol)
297 int ftype = ril.il[j_mol];
298 int nral = NRAL(ftype);
299 int j = mol * nril_mol + j_mol;
300 if (isAssigned[j] == 0 && !(interaction_function[ftype].flags & IF_VSITE))
302 if (DDMASTER(cr->dd))
306 log.writeLineFormatted("Molecule type '%s'", moltypename);
307 log.writeLineFormatted(
308 "the first %d missing interactions, except for exclusions:",
311 log.writeStringFormatted("%20s atoms", interaction_function[ftype].longname);
313 for (; a < nral; a++)
315 log.writeStringFormatted("%5d", ril.il[j_mol + 2 + a] + 1);
319 log.writeString(" ");
322 log.writeString(" global");
323 for (int a = 0; a < nral; a++)
325 log.writeStringFormatted("%6d",
326 atomRange.begin() + mol * numAtomsPerMolecule
327 + ril.il[j_mol + 2 + a] + 1);
329 log.ensureLineBreak();
332 if (i >= numMissingToPrint)
337 j_mol += 2 + nral_rt(ftype);
341 return stream.toString();
344 /*! \brief Help print error output when interactions are missing */
345 static void printMissingInteractionsAtoms(const gmx::MDLogger& mdlog,
347 const gmx_mtop_t& mtop,
348 const InteractionDefinitions& idef)
350 const gmx_reverse_top_t& rt = *cr->dd->reverse_top;
352 /* Print the atoms in the missing interactions per molblock */
354 for (const gmx_molblock_t& molb : mtop.molblock)
356 const gmx_moltype_t& moltype = mtop.moltype[molb.type];
357 const int a_start = a_end;
358 a_end = a_start + molb.nmol * moltype.atoms.nr;
359 const gmx::Range<int> atomRange(a_start, a_end);
361 auto warning = printMissingInteractionsMolblock(cr,
364 rt.interactionListForMoleculeType(molb.type),
370 GMX_LOG(mdlog.warning).appendText(warning);
374 void dd_print_missing_interactions(const gmx::MDLogger& mdlog,
376 int numBondedInteractionsOverAllDomains,
377 const gmx_mtop_t& top_global,
378 const gmx_localtop_t* top_local,
379 gmx::ArrayRef<const gmx::RVec> x,
383 gmx_domdec_t* dd = cr->dd;
385 GMX_LOG(mdlog.warning)
387 "Not all bonded interactions have been properly assigned to the domain "
388 "decomposition cells");
390 const int ndiff_tot = numBondedInteractionsOverAllDomains
391 - dd->reverse_top->expectedNumGlobalBondedInteractions();
393 for (int ftype = 0; ftype < F_NRE; ftype++)
395 const int nral = NRAL(ftype);
396 cl[ftype] = top_local->idef.il[ftype].size() / (1 + nral);
399 gmx_sumi(F_NRE, cl, cr);
403 GMX_LOG(mdlog.warning).appendText("A list of missing interactions:");
404 int rest_global = dd->reverse_top->expectedNumGlobalBondedInteractions();
405 int rest = numBondedInteractionsOverAllDomains;
406 for (int ftype = 0; ftype < F_NRE; ftype++)
408 /* In the reverse and local top all constraints are merged
409 * into F_CONSTR. So in the if statement we skip F_CONSTRNC
410 * and add these constraints when doing F_CONSTR.
412 if (dd_check_ftype(ftype, dd->reverse_top->options()) && ftype != F_CONSTRNC)
414 int n = gmx_mtop_ftype_count(top_global, ftype);
415 if (ftype == F_CONSTR)
417 n += gmx_mtop_ftype_count(top_global, F_CONSTRNC);
419 int ndiff = cl[ftype] - n;
422 GMX_LOG(mdlog.warning)
423 .appendTextFormatted("%20s of %6d missing %6d",
424 interaction_function[ftype].longname,
433 int ndiff = rest - rest_global;
436 GMX_LOG(mdlog.warning).appendTextFormatted("%20s of %6d missing %6d", "exclusions", rest_global, -ndiff);
440 printMissingInteractionsAtoms(mdlog, cr, top_global, top_local->idef);
441 write_dd_pdb("dd_dump_err", 0, "dump", top_global, cr, -1, as_rvec_array(x.data()), box);
443 std::string errorMessage;
448 "One or more interactions were assigned to multiple domains of the domain "
449 "decompostion. Please report this bug.";
453 errorMessage = gmx::formatString(
454 "%d of the %d bonded interactions could not be calculated because some atoms "
455 "involved moved further apart than the multi-body cut-off distance (%g nm) or the "
456 "two-body cut-off distance (%g nm), see option -rdd, for pairs and tabulated bonds "
457 "also see option -ddcheck",
459 dd->reverse_top->expectedNumGlobalBondedInteractions(),
460 dd_cutoff_multibody(dd),
461 dd_cutoff_twobody(dd));
463 gmx_fatal_collective(FARGS, cr->mpi_comm_mygroup, MASTER(cr), "%s", errorMessage.c_str());
466 /*! \brief Return global topology molecule information for global atom index \p i_gl */
467 static void global_atomnr_to_moltype_ind(ArrayRef<const MolblockIndices> molblockIndices,
474 const MolblockIndices* mbi = molblockIndices.data();
476 int end = molblockIndices.size(); /* exclusive */
479 /* binary search for molblock_ind */
482 mid = (start + end) / 2;
483 if (i_gl >= mbi[mid].a_end)
487 else if (i_gl < mbi[mid].a_start)
501 *mol = (i_gl - mbi->a_start) / mbi->natoms_mol;
502 *i_mol = (i_gl - mbi->a_start) - (*mol) * mbi->natoms_mol;
505 /*! \brief Returns the maximum number of exclusions per atom */
506 static int getMaxNumExclusionsPerAtom(const ListOfLists<int>& excls)
509 for (gmx::index at = 0; at < excls.ssize(); at++)
511 const auto list = excls[at];
512 const int numExcls = list.ssize();
514 GMX_RELEASE_ASSERT(numExcls != 1 || list[0] == at,
515 "With 1 exclusion we expect a self-exclusion");
517 maxNumExcls = std::max(maxNumExcls, numExcls);
523 /*! \brief Run the reverse ilist generation and store it in r_il when \p bAssign = TRUE */
524 static int low_make_reverse_ilist(const InteractionLists& il_mt,
527 const ReverseTopOptions& rtOptions,
528 gmx::ArrayRef<const int> r_index,
529 gmx::ArrayRef<int> r_il,
530 const AtomLinkRule atomLinkRule,
531 const bool assignReverseIlist)
533 const bool includeConstraints = rtOptions.includeConstraints;
534 const bool includeSettles = rtOptions.includeSettles;
535 const DDBondedChecking ddBondedChecking = rtOptions.ddBondedChecking;
539 for (int ftype = 0; ftype < F_NRE; ftype++)
541 if ((interaction_function[ftype].flags & (IF_BOND | IF_VSITE))
542 || (includeConstraints && (ftype == F_CONSTR || ftype == F_CONSTRNC))
543 || (includeSettles && ftype == F_SETTLE))
545 const bool isVSite = ((interaction_function[ftype].flags & IF_VSITE) != 0U);
546 const int nral = NRAL(ftype);
547 const auto& il = il_mt[ftype];
548 for (int i = 0; i < il.size(); i += 1 + nral)
550 const int* ia = il.iatoms.data() + i;
551 // Virtual sites should not be linked for bonded interactions
552 const int nlink = (atomLinkRule == AtomLinkRule::FirstAtom) ? 1 : (isVSite ? 0 : nral);
553 for (int link = 0; link < nlink; link++)
555 const int a = ia[1 + link];
556 if (assignReverseIlist)
558 GMX_ASSERT(!r_il.empty(), "with bAssign not allowed to be empty");
559 GMX_ASSERT(!r_index.empty(), "with bAssign not allowed to be empty");
560 r_il[r_index[a] + count[a]] = (ftype == F_CONSTRNC ? F_CONSTR : ftype);
561 r_il[r_index[a] + count[a] + 1] = ia[0];
562 for (int j = 1; j < 1 + nral; j++)
564 /* Store the molecular atom number */
565 r_il[r_index[a] + count[a] + 1 + j] = ia[j];
568 if (interaction_function[ftype].flags & IF_VSITE)
570 if (assignReverseIlist)
572 /* Add an entry to iatoms for storing
573 * which of the constructing atoms are
576 r_il[r_index[a] + count[a] + 2 + nral] = 0;
577 for (int j = 2; j < 1 + nral; j++)
579 if (atom[ia[j]].ptype == ParticleType::VSite)
581 r_il[r_index[a] + count[a] + 2 + nral] |= (2 << j);
588 /* We do not count vsites since they are always
589 * uniquely assigned and can be assigned
590 * to multiple nodes with recursive vsites.
592 if (ddBondedChecking == DDBondedChecking::All
593 || !(interaction_function[ftype].flags & IF_LIMZERO))
598 count[a] += 2 + nral_rt(ftype);
607 /*! \brief Make the reverse ilist: a list of bonded interactions linked to atoms */
608 static int make_reverse_ilist(const InteractionLists& ilist,
609 const t_atoms* atoms,
610 const ReverseTopOptions& rtOptions,
611 const AtomLinkRule atomLinkRule,
612 reverse_ilist_t* ril_mt)
614 /* Count the interactions */
615 const int nat_mt = atoms->nr;
616 std::vector<int> count(nat_mt);
617 low_make_reverse_ilist(ilist, atoms->atom, count.data(), rtOptions, {}, {}, atomLinkRule, FALSE);
619 ril_mt->index.push_back(0);
620 for (int i = 0; i < nat_mt; i++)
622 ril_mt->index.push_back(ril_mt->index[i] + count[i]);
625 ril_mt->il.resize(ril_mt->index[nat_mt]);
627 /* Store the interactions */
628 int nint_mt = low_make_reverse_ilist(
629 ilist, atoms->atom, count.data(), rtOptions, ril_mt->index, ril_mt->il, atomLinkRule, TRUE);
631 ril_mt->numAtomsInMolecule = atoms->nr;
636 gmx_reverse_top_t::gmx_reverse_top_t(const gmx_mtop_t& mtop,
638 const ReverseTopOptions& reverseTopOptions) :
639 impl_(std::make_unique<Impl>(mtop, useFreeEnergy, reverseTopOptions))
643 gmx_reverse_top_t::~gmx_reverse_top_t() {}
645 const ReverseTopOptions& gmx_reverse_top_t::options() const
647 return impl_->options;
650 const reverse_ilist_t& gmx_reverse_top_t::interactionListForMoleculeType(int moleculeType) const
652 return impl_->ril_mt[moleculeType];
655 int gmx_reverse_top_t::expectedNumGlobalBondedInteractions() const
657 return impl_->expectedNumGlobalBondedInteractions;
660 ArrayRef<const MolblockIndices> gmx_reverse_top_t::molblockIndices() const
665 bool gmx_reverse_top_t::hasIntermolecularInteractions() const
667 return impl_->bIntermolecularInteractions;
670 const reverse_ilist_t& gmx_reverse_top_t::interactionListForIntermolecularInteractions() const
672 return impl_->ril_intermol;
675 bool gmx_reverse_top_t::hasInterAtomicInteractions() const
677 return impl_->bInterAtomicInteractions;
680 bool gmx_reverse_top_t::hasPositionRestraints() const
682 return impl_->hasPositionRestraints;
685 ArrayRef<thread_work_t> gmx_reverse_top_t::threadWorkObjects() const
687 return impl_->th_work;
690 bool gmx_reverse_top_t::doSorting() const
692 return impl_->ilsort != ilsortNO_FE;
695 /*! \brief Generate the reverse topology */
696 gmx_reverse_top_t::Impl::Impl(const gmx_mtop_t& mtop,
697 const bool useFreeEnergy,
698 const ReverseTopOptions& reverseTopOptions) :
699 options(reverseTopOptions),
700 hasPositionRestraints(gmx_mtop_ftype_count(mtop, F_POSRES) + gmx_mtop_ftype_count(mtop, F_FBPOSRES) > 0),
701 bInterAtomicInteractions(mtop.bIntermolecularInteractions)
703 bInterAtomicInteractions = mtop.bIntermolecularInteractions;
704 ril_mt.resize(mtop.moltype.size());
706 std::vector<int> nint_mt;
707 for (size_t mt = 0; mt < mtop.moltype.size(); mt++)
709 const gmx_moltype_t& molt = mtop.moltype[mt];
710 if (molt.atoms.nr > 1)
712 bInterAtomicInteractions = true;
715 /* Make the atom to interaction list for this molecule type */
716 int numberOfInteractions = make_reverse_ilist(
717 molt.ilist, &molt.atoms, options, AtomLinkRule::FirstAtom, &ril_mt[mt]);
718 nint_mt.push_back(numberOfInteractions);
720 ril_mt_tot_size += ril_mt[mt].index[molt.atoms.nr];
724 fprintf(debug, "The total size of the atom to interaction index is %d integers\n", ril_mt_tot_size);
727 expectedNumGlobalBondedInteractions = 0;
728 for (const gmx_molblock_t& molblock : mtop.molblock)
730 expectedNumGlobalBondedInteractions += molblock.nmol * nint_mt[molblock.type];
733 /* Make an intermolecular reverse top, if necessary */
734 bIntermolecularInteractions = mtop.bIntermolecularInteractions;
735 if (bIntermolecularInteractions)
737 t_atoms atoms_global;
739 atoms_global.nr = mtop.natoms;
740 atoms_global.atom = nullptr; /* Only used with virtual sites */
742 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
743 "We should have an ilist when intermolecular interactions are on");
745 expectedNumGlobalBondedInteractions += make_reverse_ilist(
746 *mtop.intermolecular_ilist, &atoms_global, options, AtomLinkRule::FirstAtom, &ril_intermol);
749 if (useFreeEnergy && gmx_mtop_bondeds_free_energy(&mtop))
751 ilsort = ilsortFE_UNSORTED;
755 ilsort = ilsortNO_FE;
758 /* Make a molblock index for fast searching */
760 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
762 const gmx_molblock_t& molb = mtop.molblock[mb];
763 const int numAtomsPerMol = mtop.moltype[molb.type].atoms.nr;
764 MolblockIndices mbiMolblock;
765 mbiMolblock.a_start = i;
766 i += molb.nmol * numAtomsPerMol;
767 mbiMolblock.a_end = i;
768 mbiMolblock.natoms_mol = numAtomsPerMol;
769 mbiMolblock.type = molb.type;
770 mbi.push_back(mbiMolblock);
773 for (int th = 0; th < gmx_omp_nthreads_get(ModuleMultiThread::Domdec); th++)
775 th_work.emplace_back(mtop.ffparams);
779 void dd_make_reverse_top(FILE* fplog,
781 const gmx_mtop_t& mtop,
782 const gmx::VirtualSitesHandler* vsite,
783 const t_inputrec& inputrec,
784 const DDBondedChecking ddBondedChecking)
788 fprintf(fplog, "\nLinking all bonded interactions to atoms\n");
791 /* If normal and/or settle constraints act only within charge groups,
792 * we can store them in the reverse top and simply assign them to domains.
793 * Otherwise we need to assign them to multiple domains and set up
794 * the parallel version constraint algorithm(s).
796 GMX_RELEASE_ASSERT(ddBondedChecking == DDBondedChecking::ExcludeZeroLimit
797 || ddBondedChecking == DDBondedChecking::All,
798 "Invalid enum value for mdrun -ddcheck");
799 const ReverseTopOptions rtOptions(ddBondedChecking,
800 !dd->comm->systemInfo.mayHaveSplitConstraints,
801 !dd->comm->systemInfo.mayHaveSplitSettles);
803 dd->reverse_top = std::make_unique<gmx_reverse_top_t>(
804 mtop, inputrec.efep != FreeEnergyPerturbationType::No, rtOptions);
806 dd->haveExclusions = false;
807 for (const gmx_molblock_t& molb : mtop.molblock)
809 const int maxNumExclusionsPerAtom = getMaxNumExclusionsPerAtom(mtop.moltype[molb.type].excls);
810 // We checked above that max 1 exclusion means only self exclusions
811 if (maxNumExclusionsPerAtom > 1)
813 dd->haveExclusions = true;
817 const int numInterUpdategroupVirtualSites =
818 (vsite == nullptr ? 0 : vsite->numInterUpdategroupVirtualSites());
819 if (numInterUpdategroupVirtualSites > 0)
824 "There are %d inter update-group virtual sites,\n"
825 "will perform an extra communication step for selected coordinates and "
827 numInterUpdategroupVirtualSites);
829 init_domdec_vsites(dd, numInterUpdategroupVirtualSites);
832 if (dd->comm->systemInfo.mayHaveSplitConstraints || dd->comm->systemInfo.mayHaveSplitSettles)
834 init_domdec_constraints(dd, mtop);
838 fprintf(fplog, "\n");
842 /*! \brief Store a vsite interaction at the end of \p il
844 * This routine is very similar to add_ifunc, but vsites interactions
845 * have more work to do than other kinds of interactions, and the
846 * complex way nral (and thus vector contents) depends on ftype
847 * confuses static analysis tools unless we fuse the vsite
848 * atom-indexing organization code with the ifunc-adding code, so that
849 * they can see that nral is the same value. */
850 static inline void add_ifunc_for_vsites(t_iatom* tiatoms,
851 const gmx_ga2la_t& ga2la,
857 const t_iatom* iatoms,
861 tiatoms[0] = iatoms[0];
865 /* We know the local index of the first atom */
870 /* Convert later in make_local_vsites */
871 tiatoms[1] = -a_gl - 1;
874 GMX_ASSERT(nral >= 2 && nral <= 5, "Invalid nral for vsites");
875 for (int k = 2; k < 1 + nral; k++)
877 int ak_gl = a_gl + iatoms[k] - a_mol;
878 if (const int* homeIndex = ga2la.findHome(ak_gl))
880 tiatoms[k] = *homeIndex;
884 /* Copy the global index, convert later in make_local_vsites */
885 tiatoms[k] = -(ak_gl + 1);
887 // Note that ga2la_get_home always sets the third parameter if
890 il->push_back(tiatoms[0], nral, tiatoms + 1);
893 /*! \brief Store a position restraint in idef and iatoms, complex because the parameters are different for each entry */
894 static void add_posres(int mol,
896 int numAtomsInMolecule,
897 const gmx_molblock_t& molb,
898 gmx::ArrayRef<int> iatoms,
899 const t_iparams* ip_in,
900 InteractionDefinitions* idef)
902 /* This position restraint has not been added yet,
903 * so it's index is the current number of position restraints.
905 const int n = idef->il[F_POSRES].size() / 2;
907 /* Get the position restraint coordinates from the molblock */
908 const int a_molb = mol * numAtomsInMolecule + a_mol;
909 GMX_ASSERT(a_molb < ssize(molb.posres_xA),
910 "We need a sufficient number of position restraint coordinates");
911 /* Copy the force constants */
912 t_iparams ip = ip_in[iatoms[0]];
913 ip.posres.pos0A[XX] = molb.posres_xA[a_molb][XX];
914 ip.posres.pos0A[YY] = molb.posres_xA[a_molb][YY];
915 ip.posres.pos0A[ZZ] = molb.posres_xA[a_molb][ZZ];
916 if (!molb.posres_xB.empty())
918 ip.posres.pos0B[XX] = molb.posres_xB[a_molb][XX];
919 ip.posres.pos0B[YY] = molb.posres_xB[a_molb][YY];
920 ip.posres.pos0B[ZZ] = molb.posres_xB[a_molb][ZZ];
924 ip.posres.pos0B[XX] = ip.posres.pos0A[XX];
925 ip.posres.pos0B[YY] = ip.posres.pos0A[YY];
926 ip.posres.pos0B[ZZ] = ip.posres.pos0A[ZZ];
928 /* Set the parameter index for idef->iparams_posres */
930 idef->iparams_posres.push_back(ip);
932 GMX_ASSERT(int(idef->iparams_posres.size()) == n + 1,
933 "The index of the parameter type should match n");
936 /*! \brief Store a flat-bottomed position restraint in idef and iatoms, complex because the parameters are different for each entry */
937 static void add_fbposres(int mol,
939 int numAtomsInMolecule,
940 const gmx_molblock_t& molb,
941 gmx::ArrayRef<int> iatoms,
942 const t_iparams* ip_in,
943 InteractionDefinitions* idef)
945 /* This flat-bottom position restraint has not been added yet,
946 * so it's index is the current number of position restraints.
948 const int n = idef->il[F_FBPOSRES].size() / 2;
950 /* Get the position restraint coordinats from the molblock */
951 const int a_molb = mol * numAtomsInMolecule + a_mol;
952 GMX_ASSERT(a_molb < ssize(molb.posres_xA),
953 "We need a sufficient number of position restraint coordinates");
954 /* Copy the force constants */
955 t_iparams ip = ip_in[iatoms[0]];
956 /* Take reference positions from A position of normal posres */
957 ip.fbposres.pos0[XX] = molb.posres_xA[a_molb][XX];
958 ip.fbposres.pos0[YY] = molb.posres_xA[a_molb][YY];
959 ip.fbposres.pos0[ZZ] = molb.posres_xA[a_molb][ZZ];
961 /* Note: no B-type for flat-bottom posres */
963 /* Set the parameter index for idef->iparams_fbposres */
965 idef->iparams_fbposres.push_back(ip);
967 GMX_ASSERT(int(idef->iparams_fbposres.size()) == n + 1,
968 "The index of the parameter type should match n");
971 /*! \brief Store a virtual site interaction, complex because of PBC and recursion */
972 static void add_vsite(const gmx_ga2la_t& ga2la,
973 gmx::ArrayRef<const int> index,
974 gmx::ArrayRef<const int> rtil,
981 const t_iatom* iatoms,
982 InteractionDefinitions* idef)
984 t_iatom tiatoms[1 + MAXATOMLIST];
986 /* Add this interaction to the local topology */
987 add_ifunc_for_vsites(tiatoms, ga2la, nral, bHomeA, a, a_gl, a_mol, iatoms, &idef->il[ftype]);
989 if (iatoms[1 + nral])
991 /* Check for recursion */
992 for (int k = 2; k < 1 + nral; k++)
994 if ((iatoms[1 + nral] & (2 << k)) && (tiatoms[k] < 0))
996 /* This construction atoms is a vsite and not a home atom */
1000 "Constructing atom %d of vsite atom %d is a vsite and non-home\n",
1004 /* Find the vsite construction */
1006 /* Check all interactions assigned to this atom */
1007 int j = index[iatoms[k]];
1008 while (j < index[iatoms[k] + 1])
1010 int ftype_r = rtil[j++];
1011 int nral_r = NRAL(ftype_r);
1012 if (interaction_function[ftype_r].flags & IF_VSITE)
1014 /* Add this vsite (recursion) */
1022 a_gl + iatoms[k] - iatoms[1],
1027 j += 1 + nral_rt(ftype_r);
1034 /*! \brief Returns the squared distance between atoms \p i and \p j */
1035 static real dd_dist2(const t_pbc* pbc_null, ArrayRef<const RVec> coordinates, const int i, const int j)
1041 pbc_dx_aiuc(pbc_null, coordinates[i], coordinates[j], dx);
1045 rvec_sub(coordinates[i], coordinates[j], dx);
1051 /*! \brief Append t_idef structures 1 to nsrc in src to *dest */
1052 static void combine_idef(InteractionDefinitions* dest, gmx::ArrayRef<const thread_work_t> src)
1054 for (int ftype = 0; ftype < F_NRE; ftype++)
1057 for (gmx::index s = 1; s < src.ssize(); s++)
1059 n += src[s].idef.il[ftype].size();
1063 for (gmx::index s = 1; s < src.ssize(); s++)
1065 dest->il[ftype].append(src[s].idef.il[ftype]);
1068 /* Position restraints need an additional treatment */
1069 if (ftype == F_POSRES || ftype == F_FBPOSRES)
1071 int nposres = dest->il[ftype].size() / 2;
1072 std::vector<t_iparams>& iparams_dest =
1073 (ftype == F_POSRES ? dest->iparams_posres : dest->iparams_fbposres);
1075 /* Set nposres to the number of original position restraints in dest */
1076 for (gmx::index s = 1; s < src.ssize(); s++)
1078 nposres -= src[s].idef.il[ftype].size() / 2;
1081 for (gmx::index s = 1; s < src.ssize(); s++)
1083 const std::vector<t_iparams>& iparams_src =
1084 (ftype == F_POSRES ? src[s].idef.iparams_posres : src[s].idef.iparams_fbposres);
1085 iparams_dest.insert(iparams_dest.end(), iparams_src.begin(), iparams_src.end());
1087 /* Correct the indices into iparams_posres */
1088 for (int i = 0; i < src[s].idef.il[ftype].size() / 2; i++)
1090 /* Correct the index into iparams_posres */
1091 dest->il[ftype].iatoms[nposres * 2] = nposres;
1096 int(iparams_dest.size()) == nposres,
1097 "The number of parameters should match the number of restraints");
1103 //! Options for assigning interactions for atoms
1104 enum class InteractionConnectivity
1106 Intramolecular, //!< Only intra-molecular interactions
1107 Intermolecular //!< Only inter-molecular interactions
1110 /*! \brief Determine whether the local domain has responsibility for
1111 * any of the bonded interactions for local atom \p atomIndex
1112 * and assign those to the local domain.
1114 * \returns The total number of bonded interactions for this atom for
1115 * which this domain is responsible.
1117 template<InteractionConnectivity interactionConnectivity>
1118 static inline int assignInteractionsForAtom(const int atomIndex,
1119 const int globalAtomIndex,
1120 const int atomIndexInMolecule,
1121 gmx::ArrayRef<const int> index,
1122 gmx::ArrayRef<const int> rtil,
1123 const int ind_start,
1125 const gmx_ga2la_t& ga2la,
1126 const gmx_domdec_zones_t* zones,
1127 const bool checkDistanceMultiBody,
1129 const bool checkDistanceTwoBody,
1130 const real cutoffSquared,
1131 const t_pbc* pbc_null,
1132 ArrayRef<const RVec> coordinates,
1133 InteractionDefinitions* idef,
1135 const DDBondedChecking ddBondedChecking)
1137 gmx::ArrayRef<const DDPairInteractionRanges> iZones = zones->iZones;
1139 int numBondedInteractions = 0;
1144 t_iatom tiatoms[1 + MAXATOMLIST];
1146 const int ftype = rtil[j++];
1147 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
1148 const int nral = NRAL(ftype);
1149 if (interaction_function[ftype].flags & IF_VSITE)
1151 GMX_ASSERT(interactionConnectivity == InteractionConnectivity::Intramolecular,
1152 "All vsites should be intramolecular");
1154 /* The vsite construction goes where the vsite itself is */
1165 atomIndexInMolecule,
1175 tiatoms[0] = iatoms[0];
1179 GMX_ASSERT(interactionConnectivity == InteractionConnectivity::Intramolecular,
1180 "All interactions that involve a single atom are intramolecular");
1182 /* Assign single-body interactions to the home zone.
1183 * Position restraints are not handled here, but separately.
1185 if (iz == 0 && !(ftype == F_POSRES || ftype == F_FBPOSRES))
1188 tiatoms[1] = atomIndex;
1193 /* This is a two-body interaction, we can assign
1194 * analogous to the non-bonded assignments.
1196 const int k_gl = (interactionConnectivity == InteractionConnectivity::Intramolecular)
1198 /* Get the global index using the offset in the molecule */
1199 (globalAtomIndex + iatoms[2] - atomIndexInMolecule)
1201 if (const auto* entry = ga2la.find(k_gl))
1203 int kz = entry->cell;
1208 /* Check zone interaction assignments */
1209 bUse = ((iz < iZones.ssize() && iz <= kz && iZones[iz].jZoneRange.isInRange(kz))
1210 || (kz < iZones.ssize() && iz > kz && iZones[kz].jZoneRange.isInRange(iz)));
1213 GMX_ASSERT(ftype != F_CONSTR || (iz == 0 && kz == 0),
1214 "Constraint assigned here should only involve home atoms");
1216 tiatoms[1] = atomIndex;
1217 tiatoms[2] = entry->la;
1218 /* If necessary check the cgcm distance */
1219 if (checkDistanceTwoBody
1220 && dd_dist2(pbc_null, coordinates, tiatoms[1], tiatoms[2]) >= cutoffSquared)
1233 /* Assign this multi-body bonded interaction to
1234 * the local domain if we have all the atoms involved
1235 * (local or communicated) and the minimum zone shift
1236 * in each dimension is zero, for dimensions
1237 * with 2 DD cells an extra check may be necessary.
1239 ivec k_zero, k_plus;
1243 for (int k = 1; k <= nral && bUse; k++)
1246 (interactionConnectivity == InteractionConnectivity::Intramolecular)
1248 /* Get the global index using the offset in the molecule */
1249 (globalAtomIndex + iatoms[k] - atomIndexInMolecule)
1251 const auto* entry = ga2la.find(k_gl);
1252 if (entry == nullptr || entry->cell >= zones->n)
1254 /* We do not have this atom of this interaction
1255 * locally, or it comes from more than one cell
1262 tiatoms[k] = entry->la;
1263 for (int d = 0; d < DIM; d++)
1265 if (zones->shift[entry->cell][d] == 0)
1276 bUse = (bUse && (k_zero[XX] != 0) && (k_zero[YY] != 0) && (k_zero[ZZ] != 0));
1277 if (checkDistanceMultiBody)
1279 for (int d = 0; (d < DIM && bUse); d++)
1281 /* Check if the distance falls within
1282 * the cut-off to avoid possible multiple
1283 * assignments of bonded interactions.
1285 if (rcheck[d] && k_plus[d]
1286 && dd_dist2(pbc_null, coordinates, tiatoms[k_zero[d]], tiatoms[k_plus[d]])
1296 /* Add this interaction to the local topology */
1297 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms + 1);
1298 /* Sum so we can check in global_stat
1299 * if we have everything.
1301 if (ddBondedChecking == DDBondedChecking::All
1302 || !(interaction_function[ftype].flags & IF_LIMZERO))
1304 numBondedInteractions++;
1308 j += 1 + nral_rt(ftype);
1311 return numBondedInteractions;
1314 /*! \brief Determine whether the local domain has responsibility for
1315 * any of the position restraints for local atom \p atomIndex
1316 * and assign those to the local domain.
1318 * \returns The total number of bonded interactions for this atom for
1319 * which this domain is responsible.
1321 static inline int assignPositionRestraintsForAtom(const int atomIndex,
1323 const int atomIndexInMolecule,
1324 const int numAtomsInMolecule,
1325 gmx::ArrayRef<const int> rtil,
1326 const int ind_start,
1328 const gmx_molblock_t& molb,
1329 const t_iparams* ip_in,
1330 InteractionDefinitions* idef)
1332 constexpr int nral = 1;
1334 int numBondedInteractions = 0;
1339 const int ftype = rtil[j++];
1340 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
1342 if (ftype == F_POSRES || ftype == F_FBPOSRES)
1344 std::array<int, 1 + nral> tiatoms = { iatoms[0], atomIndex };
1345 if (ftype == F_POSRES)
1347 add_posres(mol, atomIndexInMolecule, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1351 add_fbposres(mol, atomIndexInMolecule, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1353 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms.data() + 1);
1354 numBondedInteractions++;
1356 j += 1 + nral_rt(ftype);
1359 return numBondedInteractions;
1362 /*! \brief This function looks up and assigns bonded interactions for zone iz.
1364 * With thread parallelizing each thread acts on a different atom range:
1365 * at_start to at_end.
1367 static int make_bondeds_zone(gmx_reverse_top_t* rt,
1368 ArrayRef<const int> globalAtomIndices,
1369 const gmx_ga2la_t& ga2la,
1370 const gmx_domdec_zones_t* zones,
1371 const std::vector<gmx_molblock_t>& molb,
1372 const bool checkDistanceMultiBody,
1374 const bool checkDistanceTwoBody,
1375 const real cutoffSquared,
1376 const t_pbc* pbc_null,
1377 ArrayRef<const RVec> coordinates,
1378 const t_iparams* ip_in,
1379 InteractionDefinitions* idef,
1381 const gmx::Range<int>& atomRange)
1386 int atomIndexInMolecule = 0;
1388 const auto ddBondedChecking = rt->options().ddBondedChecking;
1390 int numBondedInteractions = 0;
1392 for (int i : atomRange)
1394 /* Get the global atom number */
1395 const int globalAtomIndex = globalAtomIndices[i];
1396 global_atomnr_to_moltype_ind(
1397 rt->molblockIndices(), globalAtomIndex, &mb, &mt, &mol, &atomIndexInMolecule);
1398 /* Check all intramolecular interactions assigned to this atom */
1399 gmx::ArrayRef<const int> index = rt->interactionListForMoleculeType(mt).index;
1400 gmx::ArrayRef<const t_iatom> rtil = rt->interactionListForMoleculeType(mt).il;
1402 numBondedInteractions += assignInteractionsForAtom<InteractionConnectivity::Intramolecular>(
1405 atomIndexInMolecule,
1408 index[atomIndexInMolecule],
1409 index[atomIndexInMolecule + 1],
1412 checkDistanceMultiBody,
1414 checkDistanceTwoBody,
1422 // Assign position restraints, when present, for the home zone
1423 if (izone == 0 && rt->hasPositionRestraints())
1425 numBondedInteractions += assignPositionRestraintsForAtom(
1428 atomIndexInMolecule,
1429 rt->interactionListForMoleculeType(mt).numAtomsInMolecule,
1431 index[atomIndexInMolecule],
1432 index[atomIndexInMolecule + 1],
1438 if (rt->hasIntermolecularInteractions())
1440 /* Check all intermolecular interactions assigned to this atom */
1441 index = rt->interactionListForIntermolecularInteractions().index;
1442 rtil = rt->interactionListForIntermolecularInteractions().il;
1444 numBondedInteractions += assignInteractionsForAtom<InteractionConnectivity::Intermolecular>(
1450 index[globalAtomIndex],
1451 index[globalAtomIndex + 1],
1454 checkDistanceMultiBody,
1456 checkDistanceTwoBody,
1466 return numBondedInteractions;
1469 /*! \brief Set the exclusion data for i-zone \p iz */
1470 static void make_exclusions_zone(ArrayRef<const int> globalAtomIndices,
1471 const gmx_ga2la_t& ga2la,
1472 gmx_domdec_zones_t* zones,
1473 ArrayRef<const MolblockIndices> molblockIndices,
1474 const std::vector<gmx_moltype_t>& moltype,
1476 ListOfLists<int>* lexcls,
1480 const gmx::ArrayRef<const int> intermolecularExclusionGroup)
1482 const auto& jAtomRange = zones->iZones[iz].jAtomRange;
1484 const gmx::index oldNumLists = lexcls->ssize();
1486 std::vector<int> exclusionsForAtom;
1487 for (int at = at_start; at < at_end; at++)
1489 exclusionsForAtom.clear();
1491 if (GET_CGINFO_EXCL_INTER(cginfo[at]))
1498 /* Copy the exclusions from the global top */
1499 int a_gl = globalAtomIndices[at];
1500 global_atomnr_to_moltype_ind(molblockIndices, a_gl, &mb, &mt, &mol, &a_mol);
1501 const auto excls = moltype[mt].excls[a_mol];
1502 for (const int aj_mol : excls)
1504 if (const auto* jEntry = ga2la.find(a_gl + aj_mol - a_mol))
1506 /* This check is not necessary, but it can reduce
1507 * the number of exclusions in the list, which in turn
1508 * can speed up the pair list construction a bit.
1510 if (jAtomRange.isInRange(jEntry->la))
1512 exclusionsForAtom.push_back(jEntry->la);
1518 bool isExcludedAtom = !intermolecularExclusionGroup.empty()
1519 && std::find(intermolecularExclusionGroup.begin(),
1520 intermolecularExclusionGroup.end(),
1521 globalAtomIndices[at])
1522 != intermolecularExclusionGroup.end();
1526 for (int qmAtomGlobalIndex : intermolecularExclusionGroup)
1528 if (const auto* entry = ga2la.find(qmAtomGlobalIndex))
1530 exclusionsForAtom.push_back(entry->la);
1535 /* Append the exclusions for this atom to the topology */
1536 lexcls->pushBack(exclusionsForAtom);
1540 lexcls->ssize() - oldNumLists == at_end - at_start,
1541 "The number of exclusion list should match the number of atoms in the range");
1544 /*! \brief Generate and store all required local bonded interactions in \p idef and local exclusions in \p lexcls
1546 * \returns Total count of bonded interactions in the local topology on this domain */
1547 static int 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->hasInterAtomicInteractions())
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 int 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 gmx::ArrayRef<thread_work_t> threadWorkObjects = rt->threadWorkObjects();
1593 const int numThreads = threadWorkObjects.size();
1594 #pragma omp parallel for num_threads(numThreads) schedule(static)
1595 for (int thread = 0; thread < numThreads; thread++)
1599 InteractionDefinitions* idef_t = nullptr;
1601 int cg0t = cg0 + ((cg1 - cg0) * thread) / numThreads;
1602 int cg1t = cg0 + ((cg1 - cg0) * (thread + 1)) / numThreads;
1610 idef_t = &threadWorkObjects[thread].idef;
1614 threadWorkObjects[thread].numBondedInteractions =
1615 make_bondeds_zone(rt,
1616 dd->globalAtomIndices,
1620 checkDistanceMultiBody,
1622 checkDistanceTwoBody,
1626 idef->iparams.data(),
1629 gmx::Range<int>(cg0t, cg1t));
1631 if (izone < numIZonesForExclusions)
1633 ListOfLists<int>* excl_t = nullptr;
1636 // Thread 0 stores exclusions directly in the final storage
1641 // Threads > 0 store in temporary storage, starting at list index 0
1642 excl_t = &threadWorkObjects[thread].excl;
1646 /* No charge groups and no distance check required */
1647 make_exclusions_zone(dd->globalAtomIndices,
1650 rt->molblockIndices(),
1657 mtop.intermolecularExclusionGroup);
1660 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1663 if (threadWorkObjects.size() > 1)
1665 combine_idef(idef, threadWorkObjects);
1668 for (const thread_work_t& th_work : threadWorkObjects)
1670 numBondedInteractions += th_work.numBondedInteractions;
1673 if (izone < numIZonesForExclusions)
1675 for (std::size_t th = 1; th < threadWorkObjects.size(); th++)
1677 lexcls->appendListOfLists(threadWorkObjects[th].excl);
1684 fprintf(debug, "We have %d exclusions\n", lexcls->numElements());
1687 return numBondedInteractions;
1690 void scheduleCheckOfLocalTopology(gmx_domdec_t* dd, const int numBondedInteractionsToReduce)
1692 dd->localTopologyChecker->numBondedInteractionsToReduce = numBondedInteractionsToReduce;
1693 // Note that it's possible for this to still be true from the last
1694 // time it was set, e.g. if repartitioning was triggered before
1695 // global communication that would have acted on the true
1696 // value. This could happen for example when replica exchange took
1697 // place soon after a partition.
1698 dd->localTopologyChecker->shouldCheckNumberOfBondedInteractions = true;
1699 // Clear the old global value, which is now invalid
1700 dd->localTopologyChecker->numBondedInteractionsOverAllDomains.reset();
1703 bool shouldCheckNumberOfBondedInteractions(const gmx_domdec_t& dd)
1705 return dd.localTopologyChecker->shouldCheckNumberOfBondedInteractions;
1708 int numBondedInteractions(const gmx_domdec_t& dd)
1710 return dd.localTopologyChecker->numBondedInteractionsToReduce;
1713 void setNumberOfBondedInteractionsOverAllDomains(const gmx_domdec_t& dd, int newValue)
1715 GMX_RELEASE_ASSERT(!dd.localTopologyChecker->numBondedInteractionsOverAllDomains.has_value(),
1716 "Cannot set number of bonded interactions because it is already set");
1717 dd.localTopologyChecker->numBondedInteractionsOverAllDomains.emplace(newValue);
1720 void checkNumberOfBondedInteractions(const gmx::MDLogger& mdlog,
1722 const gmx_mtop_t& top_global,
1723 const gmx_localtop_t* top_local,
1724 gmx::ArrayRef<const gmx::RVec> x,
1729 "No need to check number of bonded interactions when not using domain decomposition");
1730 if (cr->dd->localTopologyChecker->shouldCheckNumberOfBondedInteractions)
1732 GMX_RELEASE_ASSERT(cr->dd->localTopologyChecker->numBondedInteractionsOverAllDomains.has_value(),
1733 "The check for the total number of bonded interactions requires the "
1734 "value to have been reduced across all domains");
1735 if (cr->dd->localTopologyChecker->numBondedInteractionsOverAllDomains.value()
1736 != cr->dd->reverse_top->expectedNumGlobalBondedInteractions())
1738 dd_print_missing_interactions(
1741 cr->dd->localTopologyChecker->numBondedInteractionsOverAllDomains.value(),
1745 box); // Does not return
1747 // Now that the value is set and the check complete, future
1748 // global communication should not compute the value until
1749 // after the next partitioning.
1750 cr->dd->localTopologyChecker->shouldCheckNumberOfBondedInteractions = false;
1754 int dd_make_local_top(gmx_domdec_t* dd,
1755 gmx_domdec_zones_t* zones,
1761 ArrayRef<const RVec> coordinates,
1762 const gmx_mtop_t& mtop,
1763 gmx_localtop_t* ltop)
1767 t_pbc pbc, *pbc_null = nullptr;
1771 fprintf(debug, "Making local topology\n");
1774 bool checkDistanceMultiBody = false;
1775 bool checkDistanceTwoBody = false;
1777 if (dd->reverse_top->hasInterAtomicInteractions())
1779 /* We need to check to which cell bondeds should be assigned */
1780 rc = dd_cutoff_twobody(dd);
1783 fprintf(debug, "Two-body bonded cut-off distance is %g\n", rc);
1786 /* Should we check distances when assigning bonded interactions? */
1787 for (int d = 0; d < DIM; d++)
1790 /* Only need to check for dimensions where the part of the box
1791 * that is not communicated is smaller than the cut-off.
1793 if (d < npbcdim && dd->numCells[d] > 1
1794 && (dd->numCells[d] - npulse[d]) * cellsize_min[d] < 2 * rc)
1796 if (dd->numCells[d] == 2)
1799 checkDistanceMultiBody = TRUE;
1801 /* Check for interactions between two atoms,
1802 * where we can allow interactions up to the cut-off,
1803 * instead of up to the smallest cell dimension.
1805 checkDistanceTwoBody = TRUE;
1810 "dim %d cellmin %f bonded rcheck[%d] = %d, checkDistanceTwoBody = %s\n",
1815 gmx::boolToString(checkDistanceTwoBody));
1818 if (checkDistanceMultiBody || checkDistanceTwoBody)
1822 pbc_null = set_pbc_dd(&pbc, fr->pbcType, dd->numCells, TRUE, box);
1831 int numBondedInteractionsToReduce = make_local_bondeds_excls(dd,
1835 checkDistanceMultiBody,
1837 checkDistanceTwoBody,
1844 /* The ilist is not sorted yet,
1845 * we can only do this when we have the charge arrays.
1847 ltop->idef.ilsort = ilsortUNKNOWN;
1849 return numBondedInteractionsToReduce;
1852 void dd_sort_local_top(const gmx_domdec_t& dd, const t_mdatoms* mdatoms, gmx_localtop_t* ltop)
1854 if (dd.reverse_top->doSorting())
1856 gmx_sort_ilist_fe(<op->idef, mdatoms->chargeA, mdatoms->chargeB);
1860 ltop->idef.ilsort = ilsortNO_FE;
1864 void dd_init_local_state(const gmx_domdec_t& dd, const t_state* state_global, t_state* state_local)
1866 int buf[NITEM_DD_INIT_LOCAL_STATE];
1870 buf[0] = state_global->flags;
1871 buf[1] = state_global->ngtc;
1872 buf[2] = state_global->nnhpres;
1873 buf[3] = state_global->nhchainlength;
1874 buf[4] = state_global->dfhist ? state_global->dfhist->nlambda : 0;
1876 dd_bcast(&dd, NITEM_DD_INIT_LOCAL_STATE * sizeof(int), buf);
1878 init_gtc_state(state_local, buf[1], buf[2], buf[3]);
1879 init_dfhist_state(state_local, buf[4]);
1880 state_local->flags = buf[0];
1883 /*! \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 */
1884 static void check_link(t_blocka* link, int cg_gl, int cg_gl_j)
1886 bool bFound = false;
1887 for (int k = link->index[cg_gl]; k < link->index[cg_gl + 1]; k++)
1889 GMX_RELEASE_ASSERT(link->a, "Inconsistent NULL pointer while making charge-group links");
1890 if (link->a[k] == cg_gl_j)
1897 GMX_RELEASE_ASSERT(link->a || link->index[cg_gl + 1] + 1 > link->nalloc_a,
1898 "Inconsistent allocation of link");
1899 /* Add this charge group link */
1900 if (link->index[cg_gl + 1] + 1 > link->nalloc_a)
1902 link->nalloc_a = over_alloc_large(link->index[cg_gl + 1] + 1);
1903 srenew(link->a, link->nalloc_a);
1905 link->a[link->index[cg_gl + 1]] = cg_gl_j;
1906 link->index[cg_gl + 1]++;
1910 void makeBondedLinks(gmx_domdec_t* dd, const gmx_mtop_t& mtop, gmx::ArrayRef<cginfo_mb_t> cginfo_mb)
1913 if (!dd->comm->systemInfo.filterBondedCommunication)
1915 /* Only communicate atoms based on cut-off */
1916 dd->comm->bondedLinks = nullptr;
1920 t_blocka* link = nullptr;
1922 /* For each atom make a list of other atoms in the system
1923 * that a linked to it via bonded interactions
1924 * which are also stored in reverse_top.
1927 reverse_ilist_t ril_intermol;
1928 if (mtop.bIntermolecularInteractions)
1932 atoms.nr = mtop.natoms;
1933 atoms.atom = nullptr;
1935 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
1936 "We should have an ilist when intermolecular interactions are on");
1938 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1940 *mtop.intermolecular_ilist, &atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril_intermol);
1944 snew(link->index, mtop.natoms + 1);
1951 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
1953 const gmx_molblock_t& molb = mtop.molblock[mb];
1958 const gmx_moltype_t& molt = mtop.moltype[molb.type];
1959 /* Make a reverse ilist in which the interactions are linked
1960 * to all atoms, not only the first atom as in gmx_reverse_top.
1961 * The constraints are discarded here.
1963 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1964 reverse_ilist_t ril;
1965 make_reverse_ilist(molt.ilist, &molt.atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril);
1967 cginfo_mb_t* cgi_mb = &cginfo_mb[mb];
1970 for (mol = 0; mol < (mtop.bIntermolecularInteractions ? molb.nmol : 1); mol++)
1972 for (int a = 0; a < molt.atoms.nr; a++)
1974 int cg_gl = cg_offset + a;
1975 link->index[cg_gl + 1] = link->index[cg_gl];
1976 int i = ril.index[a];
1977 while (i < ril.index[a + 1])
1979 int ftype = ril.il[i++];
1980 int nral = NRAL(ftype);
1981 /* Skip the ifunc index */
1983 for (int j = 0; j < nral; j++)
1985 int aj = ril.il[i + j];
1988 check_link(link, cg_gl, cg_offset + aj);
1991 i += nral_rt(ftype);
1994 if (mtop.bIntermolecularInteractions)
1996 int i = ril_intermol.index[cg_gl];
1997 while (i < ril_intermol.index[cg_gl + 1])
1999 int ftype = ril_intermol.il[i++];
2000 int nral = NRAL(ftype);
2001 /* Skip the ifunc index */
2003 for (int j = 0; j < nral; j++)
2005 /* Here we assume we have no charge groups;
2006 * this has been checked above.
2008 int aj = ril_intermol.il[i + j];
2009 check_link(link, cg_gl, aj);
2011 i += nral_rt(ftype);
2014 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0)
2016 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[a]);
2021 cg_offset += molt.atoms.nr;
2023 int nlink_mol = link->index[cg_offset] - link->index[cg_offset - molt.atoms.nr];
2028 "molecule type '%s' %d atoms has %d atom links through bonded interac.\n",
2034 if (molb.nmol > mol)
2036 /* Copy the data for the rest of the molecules in this block */
2037 link->nalloc_a += (molb.nmol - mol) * nlink_mol;
2038 srenew(link->a, link->nalloc_a);
2039 for (; mol < molb.nmol; mol++)
2041 for (int a = 0; a < molt.atoms.nr; a++)
2043 int cg_gl = cg_offset + a;
2044 link->index[cg_gl + 1] = link->index[cg_gl + 1 - molt.atoms.nr] + nlink_mol;
2045 for (int j = link->index[cg_gl]; j < link->index[cg_gl + 1]; j++)
2047 link->a[j] = link->a[j - nlink_mol] + molt.atoms.nr;
2049 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0
2050 && cg_gl - cgi_mb->cg_start < cgi_mb->cg_mod)
2052 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[cg_gl - cgi_mb->cg_start]);
2056 cg_offset += molt.atoms.nr;
2063 fprintf(debug, "Of the %d atoms %d are linked via bonded interactions\n", mtop.natoms, ncgi);
2066 dd->comm->bondedLinks = link;
2075 } bonded_distance_t;
2077 /*! \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 */
2078 static void update_max_bonded_distance(real r2, int ftype, int a1, int a2, bonded_distance_t* bd)
2089 /*! \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 */
2090 static void bonded_cg_distance_mol(const gmx_moltype_t* molt,
2091 const DDBondedChecking ddBondedChecking,
2093 ArrayRef<const RVec> x,
2094 bonded_distance_t* bd_2b,
2095 bonded_distance_t* bd_mb)
2097 const ReverseTopOptions rtOptions(ddBondedChecking);
2099 for (int ftype = 0; ftype < F_NRE; ftype++)
2101 if (dd_check_ftype(ftype, rtOptions))
2103 const auto& il = molt->ilist[ftype];
2104 int nral = NRAL(ftype);
2107 for (int i = 0; i < il.size(); i += 1 + nral)
2109 for (int ai = 0; ai < nral; ai++)
2111 int atomI = il.iatoms[i + 1 + ai];
2112 for (int aj = ai + 1; aj < nral; aj++)
2114 int atomJ = il.iatoms[i + 1 + aj];
2117 real rij2 = distance2(x[atomI], x[atomJ]);
2119 update_max_bonded_distance(
2120 rij2, ftype, atomI, atomJ, (nral == 2) ? bd_2b : bd_mb);
2130 const auto& excls = molt->excls;
2131 for (gmx::index ai = 0; ai < excls.ssize(); ai++)
2133 for (const int aj : excls[ai])
2137 real rij2 = distance2(x[ai], x[aj]);
2139 /* There is no function type for exclusions, use -1 */
2140 update_max_bonded_distance(rij2, -1, ai, aj, bd_2b);
2147 /*! \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 */
2148 static void bonded_distance_intermol(const InteractionLists& ilists_intermol,
2149 const DDBondedChecking ddBondedChecking,
2150 ArrayRef<const RVec> x,
2153 bonded_distance_t* bd_2b,
2154 bonded_distance_t* bd_mb)
2158 set_pbc(&pbc, pbcType, box);
2160 const ReverseTopOptions rtOptions(ddBondedChecking);
2162 for (int ftype = 0; ftype < F_NRE; ftype++)
2164 if (dd_check_ftype(ftype, rtOptions))
2166 const auto& il = ilists_intermol[ftype];
2167 int nral = NRAL(ftype);
2169 /* No nral>1 check here, since intermol interactions always
2170 * have nral>=2 (and the code is also correct for nral=1).
2172 for (int i = 0; i < il.size(); i += 1 + nral)
2174 for (int ai = 0; ai < nral; ai++)
2176 int atom_i = il.iatoms[i + 1 + ai];
2178 for (int aj = ai + 1; aj < nral; aj++)
2182 int atom_j = il.iatoms[i + 1 + aj];
2184 pbc_dx(&pbc, x[atom_i], x[atom_j], dx);
2186 const real rij2 = norm2(dx);
2188 update_max_bonded_distance(rij2, ftype, atom_i, atom_j, (nral == 2) ? bd_2b : bd_mb);
2196 //! Returns whether \p molt has at least one virtual site
2197 static bool moltypeHasVsite(const gmx_moltype_t& molt)
2199 bool hasVsite = false;
2200 for (int i = 0; i < F_NRE; i++)
2202 if ((interaction_function[i].flags & IF_VSITE) && !molt.ilist[i].empty())
2211 //! Returns coordinates not broken over PBC for a molecule
2212 static void getWholeMoleculeCoordinates(const gmx_moltype_t* molt,
2213 const gmx_ffparams_t* ffparams,
2217 ArrayRef<const RVec> x,
2220 if (pbcType != PbcType::No)
2222 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(x.data()));
2224 shift_x(graph, box, as_rvec_array(x.data()), as_rvec_array(xs.data()));
2225 /* By doing an extra mk_mshift the molecules that are broken
2226 * because they were e.g. imported from another software
2227 * will be made whole again. Such are the healing powers
2230 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(xs.data()));
2234 /* We copy the coordinates so the original coordinates remain
2235 * unchanged, just to be 100% sure that we do not affect
2236 * binary reproducibility of simulations.
2238 for (int i = 0; i < molt->atoms.nr; i++)
2240 copy_rvec(x[i], xs[i]);
2244 if (moltypeHasVsite(*molt))
2246 gmx::constructVirtualSites(xs, ffparams->iparams, molt->ilist);
2250 void dd_bonded_cg_distance(const gmx::MDLogger& mdlog,
2251 const gmx_mtop_t& mtop,
2252 const t_inputrec& inputrec,
2253 ArrayRef<const RVec> x,
2255 const DDBondedChecking ddBondedChecking,
2259 bonded_distance_t bd_2b = { 0, -1, -1, -1 };
2260 bonded_distance_t bd_mb = { 0, -1, -1, -1 };
2262 bool bExclRequired = inputrecExclForces(&inputrec);
2267 for (const gmx_molblock_t& molb : mtop.molblock)
2269 const gmx_moltype_t& molt = mtop.moltype[molb.type];
2270 if (molt.atoms.nr == 1 || molb.nmol == 0)
2272 at_offset += molb.nmol * molt.atoms.nr;
2277 if (inputrec.pbcType != PbcType::No)
2279 graph = mk_graph_moltype(molt);
2282 std::vector<RVec> xs(molt.atoms.nr);
2283 for (int mol = 0; mol < molb.nmol; mol++)
2285 getWholeMoleculeCoordinates(&molt,
2290 x.subArray(at_offset, molt.atoms.nr),
2293 bonded_distance_t bd_mol_2b = { 0, -1, -1, -1 };
2294 bonded_distance_t bd_mol_mb = { 0, -1, -1, -1 };
2296 bonded_cg_distance_mol(&molt, ddBondedChecking, bExclRequired, xs, &bd_mol_2b, &bd_mol_mb);
2298 /* Process the mol data adding the atom index offset */
2299 update_max_bonded_distance(bd_mol_2b.r2,
2301 at_offset + bd_mol_2b.a1,
2302 at_offset + bd_mol_2b.a2,
2304 update_max_bonded_distance(bd_mol_mb.r2,
2306 at_offset + bd_mol_mb.a1,
2307 at_offset + bd_mol_mb.a2,
2310 at_offset += molt.atoms.nr;
2315 if (mtop.bIntermolecularInteractions)
2317 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
2318 "We should have an ilist when intermolecular interactions are on");
2320 bonded_distance_intermol(
2321 *mtop.intermolecular_ilist, ddBondedChecking, x, inputrec.pbcType, box, &bd_2b, &bd_mb);
2324 *r_2b = sqrt(bd_2b.r2);
2325 *r_mb = sqrt(bd_mb.r2);
2327 if (*r_2b > 0 || *r_mb > 0)
2329 GMX_LOG(mdlog.info).appendText("Initial maximum distances in bonded interactions:");
2333 .appendTextFormatted(
2334 " two-body bonded interactions: %5.3f nm, %s, atoms %d %d",
2336 (bd_2b.ftype >= 0) ? interaction_function[bd_2b.ftype].longname : "Exclusion",
2343 .appendTextFormatted(
2344 " multi-body bonded interactions: %5.3f nm, %s, atoms %d %d",
2346 interaction_function[bd_mb.ftype].longname,