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
57 #include "gromacs/domdec/domdec.h"
58 #include "gromacs/domdec/domdec_network.h"
59 #include "gromacs/domdec/ga2la.h"
60 #include "gromacs/gmxlib/network.h"
61 #include "gromacs/math/vec.h"
62 #include "gromacs/mdlib/forcerec.h"
63 #include "gromacs/mdlib/gmx_omp_nthreads.h"
64 #include "gromacs/mdlib/vsite.h"
65 #include "gromacs/mdtypes/commrec.h"
66 #include "gromacs/mdtypes/forcerec.h"
67 #include "gromacs/mdtypes/inputrec.h"
68 #include "gromacs/mdtypes/md_enums.h"
69 #include "gromacs/mdtypes/mdatom.h"
70 #include "gromacs/mdtypes/state.h"
71 #include "gromacs/pbcutil/mshift.h"
72 #include "gromacs/pbcutil/pbc.h"
73 #include "gromacs/topology/ifunc.h"
74 #include "gromacs/topology/mtop_util.h"
75 #include "gromacs/topology/topsort.h"
76 #include "gromacs/utility/cstringutil.h"
77 #include "gromacs/utility/exceptions.h"
78 #include "gromacs/utility/fatalerror.h"
79 #include "gromacs/utility/gmxassert.h"
80 #include "gromacs/utility/listoflists.h"
81 #include "gromacs/utility/logger.h"
82 #include "gromacs/utility/smalloc.h"
83 #include "gromacs/utility/strconvert.h"
84 #include "gromacs/utility/stringstream.h"
85 #include "gromacs/utility/stringutil.h"
86 #include "gromacs/utility/textwriter.h"
88 #include "domdec_constraints.h"
89 #include "domdec_internal.h"
90 #include "domdec_vsite.h"
94 using gmx::ListOfLists;
97 /*! \brief The number of integer item in the local state, used for broadcasting of the state */
98 #define NITEM_DD_INIT_LOCAL_STATE 5
100 struct reverse_ilist_t
102 std::vector<int> index; /* Index for each atom into il */
103 std::vector<int> il; /* ftype|type|a0|...|an|ftype|... */
104 int numAtomsInMolecule; /* The number of atoms in this molecule */
107 struct MolblockIndices
115 /*! \brief Struct for thread local work data for local topology generation */
118 /*! \brief Constructor
120 * \param[in] ffparams The interaction parameters, the lifetime of the created object should not exceed the lifetime of the passed parameters
122 thread_work_t(const gmx_ffparams_t& ffparams) : idef(ffparams) {}
124 InteractionDefinitions idef; /**< Partial local topology */
125 std::unique_ptr<gmx::VsitePbc> vsitePbc = nullptr; /**< vsite PBC structure */
126 int nbonded = 0; /**< The number of bondeds in this struct */
127 ListOfLists<int> excl; /**< List of exclusions */
128 int excl_count = 0; /**< The total exclusion count for \p excl */
131 /*! \brief Options for setting up gmx_reverse_top_t */
132 struct ReverseTopOptions
134 //! Constructor, constraints and settles are not including with a single argument
135 ReverseTopOptions(DDBondedChecking ddBondedChecking,
136 bool includeConstraints = false,
137 bool includeSettles = false) :
138 ddBondedChecking(ddBondedChecking),
139 includeConstraints(includeConstraints),
140 includeSettles(includeSettles)
144 //! \brief For which bonded interactions to check assignments
145 const DDBondedChecking ddBondedChecking;
146 //! \brief Whether constraints are stored in this reverse top
147 const bool includeConstraints;
148 //! \brief Whether settles are stored in this reverse top
149 const bool includeSettles;
152 /*! \brief Struct for the reverse topology: links bonded interactions to atomsx */
153 struct gmx_reverse_top_t
155 //! Constructs a reverse topology from \p mtop
156 gmx_reverse_top_t(const gmx_mtop_t& mtop, bool useFreeEnergy, const ReverseTopOptions& reverseTopOptions);
158 //! @cond Doxygen_Suppress
159 //! Options for the setup of this reverse topology
160 const ReverseTopOptions options;
161 //! \brief Are there bondeds/exclusions between atoms?
162 bool bInterAtomicInteractions = false;
163 //! \brief Reverse ilist for all moltypes
164 std::vector<reverse_ilist_t> ril_mt;
165 //! \brief The size of ril_mt[?].index summed over all entries
166 int ril_mt_tot_size = 0;
167 //! \brief The sorting state of bondeds for free energy
168 int ilsort = ilsortUNKNOWN;
169 //! \brief molblock to global atom index for quick lookup of molblocks on atom index
170 std::vector<MolblockIndices> mbi;
172 //! \brief Do we have intermolecular interactions?
173 bool bIntermolecularInteractions = false;
174 //! \brief Intermolecular reverse ilist
175 reverse_ilist_t ril_intermol;
177 //! The interaction count for the interactions that have to be present
178 int numInteractionsToCheck;
180 /* Work data structures for multi-threading */
181 //! \brief Thread work array for local topology generation
182 std::vector<thread_work_t> th_work;
186 /*! \brief Returns the number of atom entries for il in gmx_reverse_top_t */
187 static int nral_rt(int ftype)
189 int nral = NRAL(ftype);
190 if (interaction_function[ftype].flags & IF_VSITE)
192 /* With vsites the reverse topology contains an extra entry
193 * for storing if constructing atoms are vsites.
201 /*! \brief Return whether interactions of type \p ftype need to be assigned exactly once */
202 static gmx_bool dd_check_ftype(const int ftype, const ReverseTopOptions rtOptions)
204 return ((((interaction_function[ftype].flags & IF_BOND) != 0U)
205 && ((interaction_function[ftype].flags & IF_VSITE) == 0U)
206 && ((rtOptions.ddBondedChecking == DDBondedChecking::All)
207 || ((interaction_function[ftype].flags & IF_LIMZERO) == 0U)))
208 || (rtOptions.includeConstraints && (ftype == F_CONSTR || ftype == F_CONSTRNC))
209 || (rtOptions.includeSettles && ftype == F_SETTLE));
212 /*! \brief Checks whether interactions have been assigned for one function type
214 * Loops over a list of interactions in the local topology of one function type
215 * and flags each of the interactions as assigned in the global \p isAssigned list.
216 * Exits with an inconsistency error when an interaction is assigned more than once.
218 static void flagInteractionsForType(const int ftype,
219 const InteractionList& il,
220 const reverse_ilist_t& ril,
221 const gmx::Range<int>& atomRange,
222 const int numAtomsPerMolecule,
223 gmx::ArrayRef<const int> globalAtomIndices,
224 gmx::ArrayRef<int> isAssigned)
226 const int nril_mol = ril.index[numAtomsPerMolecule];
227 const int nral = NRAL(ftype);
229 for (int i = 0; i < il.size(); i += 1 + nral)
231 // ia[0] is the interaction type, ia[1, ...] the atom indices
232 const int* ia = il.iatoms.data() + i;
233 // Extract the global atom index of the first atom in this interaction
234 const int a0 = globalAtomIndices[ia[1]];
235 /* Check if this interaction is in
236 * the currently checked molblock.
238 if (atomRange.isInRange(a0))
240 // The molecule index in the list of this molecule type
241 const int moleculeIndex = (a0 - atomRange.begin()) / numAtomsPerMolecule;
242 const int atomOffset = (a0 - atomRange.begin()) - moleculeIndex * numAtomsPerMolecule;
243 const int globalAtomStartInMolecule = atomRange.begin() + moleculeIndex * numAtomsPerMolecule;
244 int j_mol = ril.index[atomOffset];
246 while (j_mol < ril.index[atomOffset + 1] && !found)
248 const int j = moleculeIndex * nril_mol + j_mol;
249 const int ftype_j = ril.il[j_mol];
250 /* Here we need to check if this interaction has
251 * not already been assigned, since we could have
252 * multiply defined interactions.
254 if (ftype == ftype_j && ia[0] == ril.il[j_mol + 1] && isAssigned[j] == 0)
256 /* Check the atoms */
258 for (int a = 0; a < nral; a++)
260 if (globalAtomIndices[ia[1 + a]]
261 != globalAtomStartInMolecule + ril.il[j_mol + 2 + a])
271 j_mol += 2 + nral_rt(ftype_j);
275 gmx_incons("Some interactions seem to be assigned multiple times");
281 /*! \brief Help print error output when interactions are missing in a molblock
283 * \note This function needs to be called on all ranks (contains a global summation)
285 static std::string printMissingInteractionsMolblock(t_commrec* cr,
286 const gmx_reverse_top_t& rt,
287 const char* moltypename,
288 const reverse_ilist_t& ril,
289 const gmx::Range<int>& atomRange,
290 const int numAtomsPerMolecule,
291 const int numMolecules,
292 const InteractionDefinitions& idef)
294 const int nril_mol = ril.index[numAtomsPerMolecule];
295 std::vector<int> isAssigned(numMolecules * nril_mol, 0);
296 gmx::StringOutputStream stream;
297 gmx::TextWriter log(&stream);
299 for (int ftype = 0; ftype < F_NRE; ftype++)
301 if (dd_check_ftype(ftype, rt.options))
303 flagInteractionsForType(
304 ftype, idef.il[ftype], ril, atomRange, numAtomsPerMolecule, cr->dd->globalAtomIndices, isAssigned);
308 gmx_sumi(isAssigned.size(), isAssigned.data(), cr);
310 const int numMissingToPrint = 10;
312 for (int mol = 0; mol < numMolecules; mol++)
315 while (j_mol < nril_mol)
317 int ftype = ril.il[j_mol];
318 int nral = NRAL(ftype);
319 int j = mol * nril_mol + j_mol;
320 if (isAssigned[j] == 0 && !(interaction_function[ftype].flags & IF_VSITE))
322 if (DDMASTER(cr->dd))
326 log.writeLineFormatted("Molecule type '%s'", moltypename);
327 log.writeLineFormatted(
328 "the first %d missing interactions, except for exclusions:",
331 log.writeStringFormatted("%20s atoms", interaction_function[ftype].longname);
333 for (; a < nral; a++)
335 log.writeStringFormatted("%5d", ril.il[j_mol + 2 + a] + 1);
339 log.writeString(" ");
342 log.writeString(" global");
343 for (int a = 0; a < nral; a++)
345 log.writeStringFormatted("%6d",
346 atomRange.begin() + mol * numAtomsPerMolecule
347 + ril.il[j_mol + 2 + a] + 1);
349 log.ensureLineBreak();
352 if (i >= numMissingToPrint)
357 j_mol += 2 + nral_rt(ftype);
361 return stream.toString();
364 /*! \brief Help print error output when interactions are missing */
365 static void printMissingInteractionsAtoms(const gmx::MDLogger& mdlog,
367 const gmx_mtop_t& mtop,
368 const InteractionDefinitions& idef)
370 const gmx_reverse_top_t& rt = *cr->dd->reverse_top;
372 /* Print the atoms in the missing interactions per molblock */
374 for (const gmx_molblock_t& molb : mtop.molblock)
376 const gmx_moltype_t& moltype = mtop.moltype[molb.type];
377 const int a_start = a_end;
378 a_end = a_start + molb.nmol * moltype.atoms.nr;
379 const gmx::Range<int> atomRange(a_start, a_end);
381 auto warning = printMissingInteractionsMolblock(
382 cr, rt, *(moltype.name), rt.ril_mt[molb.type], atomRange, moltype.atoms.nr, molb.nmol, idef);
384 GMX_LOG(mdlog.warning).appendText(warning);
388 void dd_print_missing_interactions(const gmx::MDLogger& mdlog,
391 const gmx_mtop_t* top_global,
392 const gmx_localtop_t* top_local,
393 gmx::ArrayRef<const gmx::RVec> x,
397 gmx_domdec_t* dd = cr->dd;
399 GMX_LOG(mdlog.warning)
401 "Not all bonded interactions have been properly assigned to the domain "
402 "decomposition cells");
404 const int ndiff_tot = local_count - dd->nbonded_global;
406 for (int ftype = 0; ftype < F_NRE; ftype++)
408 const int nral = NRAL(ftype);
409 cl[ftype] = top_local->idef.il[ftype].size() / (1 + nral);
412 gmx_sumi(F_NRE, cl, cr);
416 GMX_LOG(mdlog.warning).appendText("A list of missing interactions:");
417 int rest_global = dd->nbonded_global;
418 int rest_local = local_count;
419 for (int ftype = 0; ftype < F_NRE; ftype++)
421 /* In the reverse and local top all constraints are merged
422 * into F_CONSTR. So in the if statement we skip F_CONSTRNC
423 * and add these constraints when doing F_CONSTR.
425 if (dd_check_ftype(ftype, dd->reverse_top->options) && ftype != F_CONSTRNC)
427 int n = gmx_mtop_ftype_count(top_global, ftype);
428 if (ftype == F_CONSTR)
430 n += gmx_mtop_ftype_count(top_global, F_CONSTRNC);
432 int ndiff = cl[ftype] - n;
435 GMX_LOG(mdlog.warning)
436 .appendTextFormatted("%20s of %6d missing %6d",
437 interaction_function[ftype].longname,
442 rest_local -= cl[ftype];
446 int ndiff = rest_local - rest_global;
449 GMX_LOG(mdlog.warning).appendTextFormatted("%20s of %6d missing %6d", "exclusions", rest_global, -ndiff);
453 printMissingInteractionsAtoms(mdlog, cr, *top_global, top_local->idef);
454 write_dd_pdb("dd_dump_err", 0, "dump", top_global, cr, -1, as_rvec_array(x.data()), box);
456 std::string errorMessage;
461 "One or more interactions were assigned to multiple domains of the domain "
462 "decompostion. Please report this bug.";
466 errorMessage = gmx::formatString(
467 "%d of the %d bonded interactions could not be calculated because some atoms "
468 "involved moved further apart than the multi-body cut-off distance (%g nm) or the "
469 "two-body cut-off distance (%g nm), see option -rdd, for pairs and tabulated bonds "
470 "also see option -ddcheck",
472 cr->dd->nbonded_global,
473 dd_cutoff_multibody(dd),
474 dd_cutoff_twobody(dd));
476 gmx_fatal_collective(FARGS, cr->mpi_comm_mygroup, MASTER(cr), "%s", errorMessage.c_str());
479 /*! \brief Return global topology molecule information for global atom index \p i_gl */
480 static void global_atomnr_to_moltype_ind(const gmx_reverse_top_t* rt, int i_gl, int* mb, int* mt, int* mol, int* i_mol)
482 const MolblockIndices* mbi = rt->mbi.data();
484 int end = rt->mbi.size(); /* exclusive */
487 /* binary search for molblock_ind */
490 mid = (start + end) / 2;
491 if (i_gl >= mbi[mid].a_end)
495 else if (i_gl < mbi[mid].a_start)
509 *mol = (i_gl - mbi->a_start) / mbi->natoms_mol;
510 *i_mol = (i_gl - mbi->a_start) - (*mol) * mbi->natoms_mol;
513 /*! \brief Returns the maximum number of exclusions per atom */
514 static int getMaxNumExclusionsPerAtom(const ListOfLists<int>& excls)
517 for (gmx::index at = 0; at < excls.ssize(); at++)
519 const auto list = excls[at];
520 const int numExcls = list.ssize();
522 GMX_RELEASE_ASSERT(numExcls != 1 || list[0] == at,
523 "With 1 exclusion we expect a self-exclusion");
525 maxNumExcls = std::max(maxNumExcls, numExcls);
531 //! Options for linking atoms in make_reverse_ilist
532 enum class AtomLinkRule
534 FirstAtom, //!< Link all interactions to the first atom in the atom list
535 AllAtomsInBondeds //!< Link bonded interactions to all atoms involved, don't link vsites
538 /*! \brief Run the reverse ilist generation and store it in r_il when \p bAssign = TRUE */
539 static int low_make_reverse_ilist(const InteractionLists& il_mt,
542 const ReverseTopOptions& rtOptions,
543 gmx::ArrayRef<const int> r_index,
544 gmx::ArrayRef<int> r_il,
545 const AtomLinkRule atomLinkRule,
546 const bool assignReverseIlist)
548 const bool includeConstraints = rtOptions.includeConstraints;
549 const bool includeSettles = rtOptions.includeSettles;
550 const DDBondedChecking ddBondedChecking = rtOptions.ddBondedChecking;
554 for (int ftype = 0; ftype < F_NRE; ftype++)
556 if ((interaction_function[ftype].flags & (IF_BOND | IF_VSITE))
557 || (includeConstraints && (ftype == F_CONSTR || ftype == F_CONSTRNC))
558 || (includeSettles && ftype == F_SETTLE))
560 const bool isVSite = ((interaction_function[ftype].flags & IF_VSITE) != 0U);
561 const int nral = NRAL(ftype);
562 const auto& il = il_mt[ftype];
563 for (int i = 0; i < il.size(); i += 1 + nral)
565 const int* ia = il.iatoms.data() + i;
566 // Virtual sites should not be linked for bonded interactions
567 const int nlink = (atomLinkRule == AtomLinkRule::FirstAtom) ? 1 : (isVSite ? 0 : nral);
568 for (int link = 0; link < nlink; link++)
570 const int a = ia[1 + link];
571 if (assignReverseIlist)
573 GMX_ASSERT(!r_il.empty(), "with bAssign not allowed to be empty");
574 GMX_ASSERT(!r_index.empty(), "with bAssign not allowed to be empty");
575 r_il[r_index[a] + count[a]] = (ftype == F_CONSTRNC ? F_CONSTR : ftype);
576 r_il[r_index[a] + count[a] + 1] = ia[0];
577 for (int j = 1; j < 1 + nral; j++)
579 /* Store the molecular atom number */
580 r_il[r_index[a] + count[a] + 1 + j] = ia[j];
583 if (interaction_function[ftype].flags & IF_VSITE)
585 if (assignReverseIlist)
587 /* Add an entry to iatoms for storing
588 * which of the constructing atoms are
591 r_il[r_index[a] + count[a] + 2 + nral] = 0;
592 for (int j = 2; j < 1 + nral; j++)
594 if (atom[ia[j]].ptype == eptVSite)
596 r_il[r_index[a] + count[a] + 2 + nral] |= (2 << j);
603 /* We do not count vsites since they are always
604 * uniquely assigned and can be assigned
605 * to multiple nodes with recursive vsites.
607 if (ddBondedChecking == DDBondedChecking::All
608 || !(interaction_function[ftype].flags & IF_LIMZERO))
613 count[a] += 2 + nral_rt(ftype);
622 /*! \brief Make the reverse ilist: a list of bonded interactions linked to atoms */
623 static int make_reverse_ilist(const InteractionLists& ilist,
624 const t_atoms* atoms,
625 const ReverseTopOptions& rtOptions,
626 const AtomLinkRule atomLinkRule,
627 reverse_ilist_t* ril_mt)
629 /* Count the interactions */
630 const int nat_mt = atoms->nr;
631 std::vector<int> count(nat_mt);
632 low_make_reverse_ilist(ilist, atoms->atom, count.data(), rtOptions, {}, {}, atomLinkRule, FALSE);
634 ril_mt->index.push_back(0);
635 for (int i = 0; i < nat_mt; i++)
637 ril_mt->index.push_back(ril_mt->index[i] + count[i]);
640 ril_mt->il.resize(ril_mt->index[nat_mt]);
642 /* Store the interactions */
643 int nint_mt = low_make_reverse_ilist(
644 ilist, atoms->atom, count.data(), rtOptions, ril_mt->index, ril_mt->il, atomLinkRule, TRUE);
646 ril_mt->numAtomsInMolecule = atoms->nr;
651 /*! \brief Generate the reverse topology */
652 gmx_reverse_top_t::gmx_reverse_top_t(const gmx_mtop_t& mtop,
653 const bool useFreeEnergy,
654 const ReverseTopOptions& reverseTopOptions) :
655 options(reverseTopOptions)
657 bInterAtomicInteractions = mtop.bIntermolecularInteractions;
658 ril_mt.resize(mtop.moltype.size());
660 std::vector<int> nint_mt;
661 for (size_t mt = 0; mt < mtop.moltype.size(); mt++)
663 const gmx_moltype_t& molt = mtop.moltype[mt];
664 if (molt.atoms.nr > 1)
666 bInterAtomicInteractions = true;
669 /* Make the atom to interaction list for this molecule type */
670 int numberOfInteractions = make_reverse_ilist(
671 molt.ilist, &molt.atoms, options, AtomLinkRule::FirstAtom, &ril_mt[mt]);
672 nint_mt.push_back(numberOfInteractions);
674 ril_mt_tot_size += ril_mt[mt].index[molt.atoms.nr];
678 fprintf(debug, "The total size of the atom to interaction index is %d integers\n", ril_mt_tot_size);
681 numInteractionsToCheck = 0;
682 for (const gmx_molblock_t& molblock : mtop.molblock)
684 numInteractionsToCheck += molblock.nmol * nint_mt[molblock.type];
687 /* Make an intermolecular reverse top, if necessary */
688 bIntermolecularInteractions = mtop.bIntermolecularInteractions;
689 if (bIntermolecularInteractions)
691 t_atoms atoms_global;
693 atoms_global.nr = mtop.natoms;
694 atoms_global.atom = nullptr; /* Only used with virtual sites */
696 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
697 "We should have an ilist when intermolecular interactions are on");
699 numInteractionsToCheck += make_reverse_ilist(
700 *mtop.intermolecular_ilist, &atoms_global, options, AtomLinkRule::FirstAtom, &ril_intermol);
703 if (useFreeEnergy && gmx_mtop_bondeds_free_energy(&mtop))
705 ilsort = ilsortFE_UNSORTED;
709 ilsort = ilsortNO_FE;
712 /* Make a molblock index for fast searching */
714 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
716 const gmx_molblock_t& molb = mtop.molblock[mb];
717 const int numAtomsPerMol = mtop.moltype[molb.type].atoms.nr;
718 MolblockIndices mbiMolblock;
719 mbiMolblock.a_start = i;
720 i += molb.nmol * numAtomsPerMol;
721 mbiMolblock.a_end = i;
722 mbiMolblock.natoms_mol = numAtomsPerMol;
723 mbiMolblock.type = molb.type;
724 mbi.push_back(mbiMolblock);
727 for (int th = 0; th < gmx_omp_nthreads_get(emntDomdec); th++)
729 th_work.emplace_back(mtop.ffparams);
733 void dd_make_reverse_top(FILE* fplog,
735 const gmx_mtop_t* mtop,
736 const gmx::VirtualSitesHandler* vsite,
737 const t_inputrec* ir,
738 const DDBondedChecking ddBondedChecking)
742 fprintf(fplog, "\nLinking all bonded interactions to atoms\n");
745 /* If normal and/or settle constraints act only within charge groups,
746 * we can store them in the reverse top and simply assign them to domains.
747 * Otherwise we need to assign them to multiple domains and set up
748 * the parallel version constraint algorithm(s).
750 const ReverseTopOptions rtOptions(ddBondedChecking,
751 !dd->comm->systemInfo.haveSplitConstraints,
752 !dd->comm->systemInfo.haveSplitSettles);
754 dd->reverse_top = new gmx_reverse_top_t(*mtop, ir->efep != FreeEnergyPerturbationType::No, rtOptions);
756 dd->nbonded_global = dd->reverse_top->numInteractionsToCheck;
758 dd->haveExclusions = false;
759 for (const gmx_molblock_t& molb : mtop->molblock)
761 const int maxNumExclusionsPerAtom = getMaxNumExclusionsPerAtom(mtop->moltype[molb.type].excls);
762 // We checked above that max 1 exclusion means only self exclusions
763 if (maxNumExclusionsPerAtom > 1)
765 dd->haveExclusions = true;
769 const int numInterUpdategroupVirtualSites =
770 (vsite == nullptr ? 0 : vsite->numInterUpdategroupVirtualSites());
771 if (numInterUpdategroupVirtualSites > 0)
776 "There are %d inter update-group virtual sites,\n"
777 "will perform an extra communication step for selected coordinates and "
779 numInterUpdategroupVirtualSites);
781 init_domdec_vsites(dd, numInterUpdategroupVirtualSites);
784 if (dd->comm->systemInfo.haveSplitConstraints || dd->comm->systemInfo.haveSplitSettles)
786 init_domdec_constraints(dd, mtop);
790 fprintf(fplog, "\n");
794 /*! \brief Store a vsite interaction at the end of \p il
796 * This routine is very similar to add_ifunc, but vsites interactions
797 * have more work to do than other kinds of interactions, and the
798 * complex way nral (and thus vector contents) depends on ftype
799 * confuses static analysis tools unless we fuse the vsite
800 * atom-indexing organization code with the ifunc-adding code, so that
801 * they can see that nral is the same value. */
802 static inline void add_ifunc_for_vsites(t_iatom* tiatoms,
803 const gmx_ga2la_t& ga2la,
809 const t_iatom* iatoms,
813 tiatoms[0] = iatoms[0];
817 /* We know the local index of the first atom */
822 /* Convert later in make_local_vsites */
823 tiatoms[1] = -a_gl - 1;
826 GMX_ASSERT(nral >= 2 && nral <= 5, "Invalid nral for vsites");
827 for (int k = 2; k < 1 + nral; k++)
829 int ak_gl = a_gl + iatoms[k] - a_mol;
830 if (const int* homeIndex = ga2la.findHome(ak_gl))
832 tiatoms[k] = *homeIndex;
836 /* Copy the global index, convert later in make_local_vsites */
837 tiatoms[k] = -(ak_gl + 1);
839 // Note that ga2la_get_home always sets the third parameter if
842 il->push_back(tiatoms[0], nral, tiatoms + 1);
845 /*! \brief Store a position restraint in idef and iatoms, complex because the parameters are different for each entry */
846 static void add_posres(int mol,
848 int numAtomsInMolecule,
849 const gmx_molblock_t* molb,
851 const t_iparams* ip_in,
852 InteractionDefinitions* idef)
854 /* This position restraint has not been added yet,
855 * so it's index is the current number of position restraints.
857 const int n = idef->il[F_POSRES].size() / 2;
859 /* Get the position restraint coordinates from the molblock */
860 const int a_molb = mol * numAtomsInMolecule + a_mol;
861 GMX_ASSERT(a_molb < ssize(molb->posres_xA),
862 "We need a sufficient number of position restraint coordinates");
863 /* Copy the force constants */
864 t_iparams ip = ip_in[iatoms[0]];
865 ip.posres.pos0A[XX] = molb->posres_xA[a_molb][XX];
866 ip.posres.pos0A[YY] = molb->posres_xA[a_molb][YY];
867 ip.posres.pos0A[ZZ] = molb->posres_xA[a_molb][ZZ];
868 if (!molb->posres_xB.empty())
870 ip.posres.pos0B[XX] = molb->posres_xB[a_molb][XX];
871 ip.posres.pos0B[YY] = molb->posres_xB[a_molb][YY];
872 ip.posres.pos0B[ZZ] = molb->posres_xB[a_molb][ZZ];
876 ip.posres.pos0B[XX] = ip.posres.pos0A[XX];
877 ip.posres.pos0B[YY] = ip.posres.pos0A[YY];
878 ip.posres.pos0B[ZZ] = ip.posres.pos0A[ZZ];
880 /* Set the parameter index for idef->iparams_posres */
882 idef->iparams_posres.push_back(ip);
884 GMX_ASSERT(int(idef->iparams_posres.size()) == n + 1,
885 "The index of the parameter type should match n");
888 /*! \brief Store a flat-bottomed position restraint in idef and iatoms, complex because the parameters are different for each entry */
889 static void add_fbposres(int mol,
891 int numAtomsInMolecule,
892 const gmx_molblock_t* molb,
894 const t_iparams* ip_in,
895 InteractionDefinitions* idef)
897 /* This flat-bottom position restraint has not been added yet,
898 * so it's index is the current number of position restraints.
900 const int n = idef->il[F_FBPOSRES].size() / 2;
902 /* Get the position restraint coordinats from the molblock */
903 const int a_molb = mol * numAtomsInMolecule + a_mol;
904 GMX_ASSERT(a_molb < ssize(molb->posres_xA),
905 "We need a sufficient number of position restraint coordinates");
906 /* Copy the force constants */
907 t_iparams ip = ip_in[iatoms[0]];
908 /* Take reference positions from A position of normal posres */
909 ip.fbposres.pos0[XX] = molb->posres_xA[a_molb][XX];
910 ip.fbposres.pos0[YY] = molb->posres_xA[a_molb][YY];
911 ip.fbposres.pos0[ZZ] = molb->posres_xA[a_molb][ZZ];
913 /* Note: no B-type for flat-bottom posres */
915 /* Set the parameter index for idef->iparams_fbposres */
917 idef->iparams_fbposres.push_back(ip);
919 GMX_ASSERT(int(idef->iparams_fbposres.size()) == n + 1,
920 "The index of the parameter type should match n");
923 /*! \brief Store a virtual site interaction, complex because of PBC and recursion */
924 static void add_vsite(const gmx_ga2la_t& ga2la,
925 gmx::ArrayRef<const int> index,
926 gmx::ArrayRef<const int> rtil,
933 const t_iatom* iatoms,
934 InteractionDefinitions* idef)
936 t_iatom tiatoms[1 + MAXATOMLIST];
938 /* Add this interaction to the local topology */
939 add_ifunc_for_vsites(tiatoms, ga2la, nral, bHomeA, a, a_gl, a_mol, iatoms, &idef->il[ftype]);
941 if (iatoms[1 + nral])
943 /* Check for recursion */
944 for (int k = 2; k < 1 + nral; k++)
946 if ((iatoms[1 + nral] & (2 << k)) && (tiatoms[k] < 0))
948 /* This construction atoms is a vsite and not a home atom */
952 "Constructing atom %d of vsite atom %d is a vsite and non-home\n",
956 /* Find the vsite construction */
958 /* Check all interactions assigned to this atom */
959 int j = index[iatoms[k]];
960 while (j < index[iatoms[k] + 1])
962 int ftype_r = rtil[j++];
963 int nral_r = NRAL(ftype_r);
964 if (interaction_function[ftype_r].flags & IF_VSITE)
966 /* Add this vsite (recursion) */
974 a_gl + iatoms[k] - iatoms[1],
979 j += 1 + nral_rt(ftype_r);
986 /*! \brief Returns the squared distance between atoms \p i and \p j */
987 static real dd_dist2(t_pbc* pbc_null, const rvec* x, const int i, int j)
993 pbc_dx_aiuc(pbc_null, x[i], x[j], dx);
997 rvec_sub(x[i], x[j], dx);
1003 /*! \brief Append t_idef structures 1 to nsrc in src to *dest */
1004 static void combine_idef(InteractionDefinitions* dest, gmx::ArrayRef<const thread_work_t> src)
1006 for (int ftype = 0; ftype < F_NRE; ftype++)
1009 for (gmx::index s = 1; s < src.ssize(); s++)
1011 n += src[s].idef.il[ftype].size();
1015 for (gmx::index s = 1; s < src.ssize(); s++)
1017 dest->il[ftype].append(src[s].idef.il[ftype]);
1020 /* Position restraints need an additional treatment */
1021 if (ftype == F_POSRES || ftype == F_FBPOSRES)
1023 int nposres = dest->il[ftype].size() / 2;
1024 std::vector<t_iparams>& iparams_dest =
1025 (ftype == F_POSRES ? dest->iparams_posres : dest->iparams_fbposres);
1027 /* Set nposres to the number of original position restraints in dest */
1028 for (gmx::index s = 1; s < src.ssize(); s++)
1030 nposres -= src[s].idef.il[ftype].size() / 2;
1033 for (gmx::index s = 1; s < src.ssize(); s++)
1035 const std::vector<t_iparams>& iparams_src =
1036 (ftype == F_POSRES ? src[s].idef.iparams_posres : src[s].idef.iparams_fbposres);
1037 iparams_dest.insert(iparams_dest.end(), iparams_src.begin(), iparams_src.end());
1039 /* Correct the indices into iparams_posres */
1040 for (int i = 0; i < src[s].idef.il[ftype].size() / 2; i++)
1042 /* Correct the index into iparams_posres */
1043 dest->il[ftype].iatoms[nposres * 2] = nposres;
1048 int(iparams_dest.size()) == nposres,
1049 "The number of parameters should match the number of restraints");
1055 /*! \brief Check and when available assign bonded interactions for local atom i
1057 static inline void check_assign_interactions_atom(int i,
1061 int numAtomsInMolecule,
1062 gmx::ArrayRef<const int> index,
1063 gmx::ArrayRef<const int> rtil,
1064 gmx_bool bInterMolInteractions,
1067 const gmx_domdec_t* dd,
1068 const gmx_domdec_zones_t* zones,
1069 const gmx_molblock_t* molb,
1076 const t_iparams* ip_in,
1077 InteractionDefinitions* idef,
1079 const DDBondedChecking ddBondedChecking,
1082 gmx::ArrayRef<const DDPairInteractionRanges> iZones = zones->iZones;
1087 t_iatom tiatoms[1 + MAXATOMLIST];
1089 const int ftype = rtil[j++];
1090 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
1091 const int nral = NRAL(ftype);
1092 if (interaction_function[ftype].flags & IF_VSITE)
1094 assert(!bInterMolInteractions);
1095 /* The vsite construction goes where the vsite itself is */
1098 add_vsite(*dd->ga2la, index, rtil, ftype, nral, TRUE, i, i_gl, i_mol, iatoms.data(), idef);
1106 tiatoms[0] = iatoms[0];
1110 assert(!bInterMolInteractions);
1111 /* Assign single-body interactions to the home zone */
1116 if (ftype == F_POSRES)
1118 add_posres(mol, i_mol, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1120 else if (ftype == F_FBPOSRES)
1122 add_fbposres(mol, i_mol, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1132 /* This is a two-body interaction, we can assign
1133 * analogous to the non-bonded assignments.
1135 const int k_gl = (!bInterMolInteractions)
1137 /* Get the global index using the offset in the molecule */
1138 (i_gl + iatoms[2] - i_mol)
1140 if (const auto* entry = dd->ga2la->find(k_gl))
1142 int kz = entry->cell;
1147 /* Check zone interaction assignments */
1148 bUse = ((iz < iZones.ssize() && iz <= kz && iZones[iz].jZoneRange.isInRange(kz))
1149 || (kz < iZones.ssize() && iz > kz && iZones[kz].jZoneRange.isInRange(iz)));
1152 GMX_ASSERT(ftype != F_CONSTR || (iz == 0 && kz == 0),
1153 "Constraint assigned here should only involve home atoms");
1156 tiatoms[2] = entry->la;
1157 /* If necessary check the cgcm distance */
1158 if (bRCheck2B && dd_dist2(pbc_null, cg_cm, tiatoms[1], tiatoms[2]) >= rc2)
1171 /* Assign this multi-body bonded interaction to
1172 * the local node if we have all the atoms involved
1173 * (local or communicated) and the minimum zone shift
1174 * in each dimension is zero, for dimensions
1175 * with 2 DD cells an extra check may be necessary.
1177 ivec k_zero, k_plus;
1181 for (int k = 1; k <= nral && bUse; k++)
1183 const int k_gl = (!bInterMolInteractions)
1185 /* Get the global index using the offset in the molecule */
1186 (i_gl + iatoms[k] - i_mol)
1188 const auto* entry = dd->ga2la->find(k_gl);
1189 if (entry == nullptr || entry->cell >= zones->n)
1191 /* We do not have this atom of this interaction
1192 * locally, or it comes from more than one cell
1199 tiatoms[k] = entry->la;
1200 for (int d = 0; d < DIM; d++)
1202 if (zones->shift[entry->cell][d] == 0)
1213 bUse = (bUse && (k_zero[XX] != 0) && (k_zero[YY] != 0) && (k_zero[ZZ] != 0));
1216 for (int d = 0; (d < DIM && bUse); d++)
1218 /* Check if the cg_cm distance falls within
1219 * the cut-off to avoid possible multiple
1220 * assignments of bonded interactions.
1222 if (rcheck[d] && k_plus[d]
1223 && dd_dist2(pbc_null, cg_cm, tiatoms[k_zero[d]], tiatoms[k_plus[d]]) >= rc2)
1232 /* Add this interaction to the local topology */
1233 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms + 1);
1234 /* Sum so we can check in global_stat
1235 * if we have everything.
1237 if (ddBondedChecking == DDBondedChecking::All
1238 || !(interaction_function[ftype].flags & IF_LIMZERO))
1244 j += 1 + nral_rt(ftype);
1248 /*! \brief This function looks up and assigns bonded interactions for zone iz.
1250 * With thread parallelizing each thread acts on a different atom range:
1251 * at_start to at_end.
1253 static int make_bondeds_zone(gmx_domdec_t* dd,
1254 const gmx_domdec_zones_t* zones,
1255 const std::vector<gmx_molblock_t>& molb,
1262 const t_iparams* ip_in,
1263 InteractionDefinitions* idef,
1265 const gmx::Range<int>& atomRange)
1272 gmx_reverse_top_t* rt = dd->reverse_top;
1274 const auto ddBondedChecking = rt->options.ddBondedChecking;
1276 int nbonded_local = 0;
1278 for (int i : atomRange)
1280 /* Get the global atom number */
1281 const int i_gl = dd->globalAtomIndices[i];
1282 global_atomnr_to_moltype_ind(rt, i_gl, &mb, &mt, &mol, &i_mol);
1283 /* Check all intramolecular interactions assigned to this atom */
1284 gmx::ArrayRef<const int> index = rt->ril_mt[mt].index;
1285 gmx::ArrayRef<const t_iatom> rtil = rt->ril_mt[mt].il;
1287 check_assign_interactions_atom(i,
1291 rt->ril_mt[mt].numAtomsInMolecule,
1313 if (rt->bIntermolecularInteractions)
1315 /* Check all intermolecular interactions assigned to this atom */
1316 index = rt->ril_intermol.index;
1317 rtil = rt->ril_intermol.il;
1319 check_assign_interactions_atom(i,
1323 rt->ril_mt[mt].numAtomsInMolecule,
1346 return nbonded_local;
1349 /*! \brief Set the exclusion data for i-zone \p iz */
1350 static void make_exclusions_zone(gmx_domdec_t* dd,
1351 gmx_domdec_zones_t* zones,
1352 const std::vector<gmx_moltype_t>& moltype,
1354 ListOfLists<int>* lexcls,
1358 const gmx::ArrayRef<const int> intermolecularExclusionGroup)
1360 const gmx_ga2la_t& ga2la = *dd->ga2la;
1362 const auto& jAtomRange = zones->iZones[iz].jAtomRange;
1364 const gmx::index oldNumLists = lexcls->ssize();
1366 std::vector<int> exclusionsForAtom;
1367 for (int at = at_start; at < at_end; at++)
1369 exclusionsForAtom.clear();
1371 if (GET_CGINFO_EXCL_INTER(cginfo[at]))
1378 /* Copy the exclusions from the global top */
1379 int a_gl = dd->globalAtomIndices[at];
1380 global_atomnr_to_moltype_ind(dd->reverse_top, a_gl, &mb, &mt, &mol, &a_mol);
1381 const auto excls = moltype[mt].excls[a_mol];
1382 for (const int aj_mol : excls)
1384 if (const auto* jEntry = ga2la.find(a_gl + aj_mol - a_mol))
1386 /* This check is not necessary, but it can reduce
1387 * the number of exclusions in the list, which in turn
1388 * can speed up the pair list construction a bit.
1390 if (jAtomRange.isInRange(jEntry->la))
1392 exclusionsForAtom.push_back(jEntry->la);
1398 bool isExcludedAtom = !intermolecularExclusionGroup.empty()
1399 && std::find(intermolecularExclusionGroup.begin(),
1400 intermolecularExclusionGroup.end(),
1401 dd->globalAtomIndices[at])
1402 != intermolecularExclusionGroup.end();
1406 for (int qmAtomGlobalIndex : intermolecularExclusionGroup)
1408 if (const auto* entry = dd->ga2la->find(qmAtomGlobalIndex))
1410 exclusionsForAtom.push_back(entry->la);
1415 /* Append the exclusions for this atom to the topology */
1416 lexcls->pushBack(exclusionsForAtom);
1420 lexcls->ssize() - oldNumLists == at_end - at_start,
1421 "The number of exclusion list should match the number of atoms in the range");
1424 /*! \brief Generate and store all required local bonded interactions in \p idef and local exclusions in \p lexcls */
1425 static int make_local_bondeds_excls(gmx_domdec_t* dd,
1426 gmx_domdec_zones_t* zones,
1427 const gmx_mtop_t* mtop,
1435 InteractionDefinitions* idef,
1436 ListOfLists<int>* lexcls,
1439 int nzone_bondeds = 0;
1441 if (dd->reverse_top->bInterAtomicInteractions)
1443 nzone_bondeds = zones->n;
1447 /* Only single charge group (or atom) molecules, so interactions don't
1448 * cross zone boundaries and we only need to assign in the home zone.
1453 /* We only use exclusions from i-zones to i- and j-zones */
1454 const int numIZonesForExclusions = (dd->haveExclusions ? zones->iZones.size() : 0);
1456 gmx_reverse_top_t* rt = dd->reverse_top;
1460 /* Clear the counts */
1462 int nbonded_local = 0;
1467 for (int izone = 0; izone < nzone_bondeds; izone++)
1469 const int cg0 = zones->cg_range[izone];
1470 const int cg1 = zones->cg_range[izone + 1];
1472 const int numThreads = rt->th_work.size();
1473 #pragma omp parallel for num_threads(numThreads) schedule(static)
1474 for (int thread = 0; thread < numThreads; thread++)
1478 InteractionDefinitions* idef_t = nullptr;
1480 int cg0t = cg0 + ((cg1 - cg0) * thread) / numThreads;
1481 int cg1t = cg0 + ((cg1 - cg0) * (thread + 1)) / numThreads;
1489 idef_t = &rt->th_work[thread].idef;
1493 rt->th_work[thread].nbonded = make_bondeds_zone(dd,
1502 idef->iparams.data(),
1505 gmx::Range<int>(cg0t, cg1t));
1507 if (izone < numIZonesForExclusions)
1509 ListOfLists<int>* excl_t = nullptr;
1512 // Thread 0 stores exclusions directly in the final storage
1517 // Threads > 0 store in temporary storage, starting at list index 0
1518 excl_t = &rt->th_work[thread].excl;
1522 /* No charge groups and no distance check required */
1523 make_exclusions_zone(
1524 dd, zones, mtop->moltype, cginfo, excl_t, izone, cg0t, cg1t, mtop->intermolecularExclusionGroup);
1527 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1530 if (rt->th_work.size() > 1)
1532 combine_idef(idef, rt->th_work);
1535 for (const thread_work_t& th_work : rt->th_work)
1537 nbonded_local += th_work.nbonded;
1540 if (izone < numIZonesForExclusions)
1542 for (std::size_t th = 1; th < rt->th_work.size(); th++)
1544 lexcls->appendListOfLists(rt->th_work[th].excl);
1546 for (const thread_work_t& th_work : rt->th_work)
1548 *excl_count += th_work.excl_count;
1555 fprintf(debug, "We have %d exclusions, check count %d\n", lexcls->numElements(), *excl_count);
1558 return nbonded_local;
1561 void dd_make_local_top(gmx_domdec_t* dd,
1562 gmx_domdec_zones_t* zones,
1569 const gmx_mtop_t& mtop,
1570 gmx_localtop_t* ltop)
1575 t_pbc pbc, *pbc_null = nullptr;
1579 fprintf(debug, "Making local topology\n");
1582 bool bRCheckMB = false;
1583 bool bRCheck2B = false;
1585 if (dd->reverse_top->bInterAtomicInteractions)
1587 /* We need to check to which cell bondeds should be assigned */
1588 rc = dd_cutoff_twobody(dd);
1591 fprintf(debug, "Two-body bonded cut-off distance is %g\n", rc);
1594 /* Should we check cg_cm distances when assigning bonded interactions? */
1595 for (int d = 0; d < DIM; d++)
1598 /* Only need to check for dimensions where the part of the box
1599 * that is not communicated is smaller than the cut-off.
1601 if (d < npbcdim && dd->numCells[d] > 1
1602 && (dd->numCells[d] - npulse[d]) * cellsize_min[d] < 2 * rc)
1604 if (dd->numCells[d] == 2)
1609 /* Check for interactions between two atoms,
1610 * where we can allow interactions up to the cut-off,
1611 * instead of up to the smallest cell dimension.
1618 "dim %d cellmin %f bonded rcheck[%d] = %d, bRCheck2B = %s\n",
1623 gmx::boolToString(bRCheck2B));
1626 if (bRCheckMB || bRCheck2B)
1630 pbc_null = set_pbc_dd(&pbc, fr->pbcType, dd->numCells, TRUE, box);
1639 dd->nbonded_local = make_local_bondeds_excls(dd,
1653 /* The ilist is not sorted yet,
1654 * we can only do this when we have the charge arrays.
1656 ltop->idef.ilsort = ilsortUNKNOWN;
1659 void dd_sort_local_top(gmx_domdec_t* dd, const t_mdatoms* mdatoms, gmx_localtop_t* ltop)
1661 if (dd->reverse_top->ilsort == ilsortNO_FE)
1663 ltop->idef.ilsort = ilsortNO_FE;
1667 gmx_sort_ilist_fe(<op->idef, mdatoms->chargeA, mdatoms->chargeB);
1671 void dd_init_local_state(gmx_domdec_t* dd, const t_state* state_global, t_state* state_local)
1673 int buf[NITEM_DD_INIT_LOCAL_STATE];
1677 buf[0] = state_global->flags;
1678 buf[1] = state_global->ngtc;
1679 buf[2] = state_global->nnhpres;
1680 buf[3] = state_global->nhchainlength;
1681 buf[4] = state_global->dfhist ? state_global->dfhist->nlambda : 0;
1683 dd_bcast(dd, NITEM_DD_INIT_LOCAL_STATE * sizeof(int), buf);
1685 init_gtc_state(state_local, buf[1], buf[2], buf[3]);
1686 init_dfhist_state(state_local, buf[4]);
1687 state_local->flags = buf[0];
1690 /*! \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 */
1691 static void check_link(t_blocka* link, int cg_gl, int cg_gl_j)
1693 bool bFound = false;
1694 for (int k = link->index[cg_gl]; k < link->index[cg_gl + 1]; k++)
1696 GMX_RELEASE_ASSERT(link->a, "Inconsistent NULL pointer while making charge-group links");
1697 if (link->a[k] == cg_gl_j)
1704 GMX_RELEASE_ASSERT(link->a || link->index[cg_gl + 1] + 1 > link->nalloc_a,
1705 "Inconsistent allocation of link");
1706 /* Add this charge group link */
1707 if (link->index[cg_gl + 1] + 1 > link->nalloc_a)
1709 link->nalloc_a = over_alloc_large(link->index[cg_gl + 1] + 1);
1710 srenew(link->a, link->nalloc_a);
1712 link->a[link->index[cg_gl + 1]] = cg_gl_j;
1713 link->index[cg_gl + 1]++;
1717 t_blocka* makeBondedLinks(const gmx_mtop_t& mtop, gmx::ArrayRef<cginfo_mb_t> cginfo_mb)
1719 t_blocka* link = nullptr;
1721 /* For each atom make a list of other atoms in the system
1722 * that a linked to it via bonded interactions
1723 * which are also stored in reverse_top.
1726 reverse_ilist_t ril_intermol;
1727 if (mtop.bIntermolecularInteractions)
1731 atoms.nr = mtop.natoms;
1732 atoms.atom = nullptr;
1734 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
1735 "We should have an ilist when intermolecular interactions are on");
1737 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1739 *mtop.intermolecular_ilist, &atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril_intermol);
1743 snew(link->index, mtop.natoms + 1);
1750 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
1752 const gmx_molblock_t& molb = mtop.molblock[mb];
1757 const gmx_moltype_t& molt = mtop.moltype[molb.type];
1758 /* Make a reverse ilist in which the interactions are linked
1759 * to all atoms, not only the first atom as in gmx_reverse_top.
1760 * The constraints are discarded here.
1762 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1763 reverse_ilist_t ril;
1764 make_reverse_ilist(molt.ilist, &molt.atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril);
1766 cginfo_mb_t* cgi_mb = &cginfo_mb[mb];
1769 for (mol = 0; mol < (mtop.bIntermolecularInteractions ? molb.nmol : 1); mol++)
1771 for (int a = 0; a < molt.atoms.nr; a++)
1773 int cg_gl = cg_offset + a;
1774 link->index[cg_gl + 1] = link->index[cg_gl];
1775 int i = ril.index[a];
1776 while (i < ril.index[a + 1])
1778 int ftype = ril.il[i++];
1779 int nral = NRAL(ftype);
1780 /* Skip the ifunc index */
1782 for (int j = 0; j < nral; j++)
1784 int aj = ril.il[i + j];
1787 check_link(link, cg_gl, cg_offset + aj);
1790 i += nral_rt(ftype);
1793 if (mtop.bIntermolecularInteractions)
1795 int i = ril_intermol.index[cg_gl];
1796 while (i < ril_intermol.index[cg_gl + 1])
1798 int ftype = ril_intermol.il[i++];
1799 int nral = NRAL(ftype);
1800 /* Skip the ifunc index */
1802 for (int j = 0; j < nral; j++)
1804 /* Here we assume we have no charge groups;
1805 * this has been checked above.
1807 int aj = ril_intermol.il[i + j];
1808 check_link(link, cg_gl, aj);
1810 i += nral_rt(ftype);
1813 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0)
1815 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[a]);
1820 cg_offset += molt.atoms.nr;
1822 int nlink_mol = link->index[cg_offset] - link->index[cg_offset - molt.atoms.nr];
1827 "molecule type '%s' %d atoms has %d atom links through bonded interac.\n",
1833 if (molb.nmol > mol)
1835 /* Copy the data for the rest of the molecules in this block */
1836 link->nalloc_a += (molb.nmol - mol) * nlink_mol;
1837 srenew(link->a, link->nalloc_a);
1838 for (; mol < molb.nmol; mol++)
1840 for (int a = 0; a < molt.atoms.nr; a++)
1842 int cg_gl = cg_offset + a;
1843 link->index[cg_gl + 1] = link->index[cg_gl + 1 - molt.atoms.nr] + nlink_mol;
1844 for (int j = link->index[cg_gl]; j < link->index[cg_gl + 1]; j++)
1846 link->a[j] = link->a[j - nlink_mol] + molt.atoms.nr;
1848 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0
1849 && cg_gl - cgi_mb->cg_start < cgi_mb->cg_mod)
1851 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[cg_gl - cgi_mb->cg_start]);
1855 cg_offset += molt.atoms.nr;
1862 fprintf(debug, "Of the %d atoms %d are linked via bonded interactions\n", mtop.natoms, ncgi);
1874 } bonded_distance_t;
1876 /*! \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 */
1877 static void update_max_bonded_distance(real r2, int ftype, int a1, int a2, bonded_distance_t* bd)
1888 /*! \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 */
1889 static void bonded_cg_distance_mol(const gmx_moltype_t* molt,
1890 const DDBondedChecking ddBondedChecking,
1892 ArrayRef<const RVec> x,
1893 bonded_distance_t* bd_2b,
1894 bonded_distance_t* bd_mb)
1896 const ReverseTopOptions rtOptions(ddBondedChecking);
1898 for (int ftype = 0; ftype < F_NRE; ftype++)
1900 if (dd_check_ftype(ftype, rtOptions))
1902 const auto& il = molt->ilist[ftype];
1903 int nral = NRAL(ftype);
1906 for (int i = 0; i < il.size(); i += 1 + nral)
1908 for (int ai = 0; ai < nral; ai++)
1910 int atomI = il.iatoms[i + 1 + ai];
1911 for (int aj = ai + 1; aj < nral; aj++)
1913 int atomJ = il.iatoms[i + 1 + aj];
1916 real rij2 = distance2(x[atomI], x[atomJ]);
1918 update_max_bonded_distance(
1919 rij2, ftype, atomI, atomJ, (nral == 2) ? bd_2b : bd_mb);
1929 const auto& excls = molt->excls;
1930 for (gmx::index ai = 0; ai < excls.ssize(); ai++)
1932 for (const int aj : excls[ai])
1936 real rij2 = distance2(x[ai], x[aj]);
1938 /* There is no function type for exclusions, use -1 */
1939 update_max_bonded_distance(rij2, -1, ai, aj, bd_2b);
1946 /*! \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 */
1947 static void bonded_distance_intermol(const InteractionLists& ilists_intermol,
1948 const DDBondedChecking ddBondedChecking,
1949 ArrayRef<const RVec> x,
1952 bonded_distance_t* bd_2b,
1953 bonded_distance_t* bd_mb)
1957 set_pbc(&pbc, pbcType, box);
1959 const ReverseTopOptions rtOptions(ddBondedChecking);
1961 for (int ftype = 0; ftype < F_NRE; ftype++)
1963 if (dd_check_ftype(ftype, rtOptions))
1965 const auto& il = ilists_intermol[ftype];
1966 int nral = NRAL(ftype);
1968 /* No nral>1 check here, since intermol interactions always
1969 * have nral>=2 (and the code is also correct for nral=1).
1971 for (int i = 0; i < il.size(); i += 1 + nral)
1973 for (int ai = 0; ai < nral; ai++)
1975 int atom_i = il.iatoms[i + 1 + ai];
1977 for (int aj = ai + 1; aj < nral; aj++)
1981 int atom_j = il.iatoms[i + 1 + aj];
1983 pbc_dx(&pbc, x[atom_i], x[atom_j], dx);
1985 const real rij2 = norm2(dx);
1987 update_max_bonded_distance(rij2, ftype, atom_i, atom_j, (nral == 2) ? bd_2b : bd_mb);
1995 //! Returns whether \p molt has at least one virtual site
1996 static bool moltypeHasVsite(const gmx_moltype_t& molt)
1998 bool hasVsite = false;
1999 for (int i = 0; i < F_NRE; i++)
2001 if ((interaction_function[i].flags & IF_VSITE) && !molt.ilist[i].empty())
2010 //! Returns coordinates not broken over PBC for a molecule
2011 static void getWholeMoleculeCoordinates(const gmx_moltype_t* molt,
2012 const gmx_ffparams_t* ffparams,
2016 ArrayRef<const RVec> x,
2019 if (pbcType != PbcType::No)
2021 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(x.data()));
2023 shift_x(graph, box, as_rvec_array(x.data()), as_rvec_array(xs.data()));
2024 /* By doing an extra mk_mshift the molecules that are broken
2025 * because they were e.g. imported from another software
2026 * will be made whole again. Such are the healing powers
2029 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(xs.data()));
2033 /* We copy the coordinates so the original coordinates remain
2034 * unchanged, just to be 100% sure that we do not affect
2035 * binary reproducibility of simulations.
2037 for (int i = 0; i < molt->atoms.nr; i++)
2039 copy_rvec(x[i], xs[i]);
2043 if (moltypeHasVsite(*molt))
2045 gmx::constructVirtualSites(xs, ffparams->iparams, molt->ilist);
2049 void dd_bonded_cg_distance(const gmx::MDLogger& mdlog,
2050 const gmx_mtop_t* mtop,
2051 const t_inputrec* ir,
2052 ArrayRef<const RVec> x,
2054 const DDBondedChecking ddBondedChecking,
2058 bonded_distance_t bd_2b = { 0, -1, -1, -1 };
2059 bonded_distance_t bd_mb = { 0, -1, -1, -1 };
2061 bool bExclRequired = inputrecExclForces(ir);
2066 for (const gmx_molblock_t& molb : mtop->molblock)
2068 const gmx_moltype_t& molt = mtop->moltype[molb.type];
2069 if (molt.atoms.nr == 1 || molb.nmol == 0)
2071 at_offset += molb.nmol * molt.atoms.nr;
2076 if (ir->pbcType != PbcType::No)
2078 graph = mk_graph_moltype(molt);
2081 std::vector<RVec> xs(molt.atoms.nr);
2082 for (int mol = 0; mol < molb.nmol; mol++)
2084 getWholeMoleculeCoordinates(&molt,
2089 x.subArray(at_offset, molt.atoms.nr),
2092 bonded_distance_t bd_mol_2b = { 0, -1, -1, -1 };
2093 bonded_distance_t bd_mol_mb = { 0, -1, -1, -1 };
2095 bonded_cg_distance_mol(&molt, ddBondedChecking, bExclRequired, xs, &bd_mol_2b, &bd_mol_mb);
2097 /* Process the mol data adding the atom index offset */
2098 update_max_bonded_distance(bd_mol_2b.r2,
2100 at_offset + bd_mol_2b.a1,
2101 at_offset + bd_mol_2b.a2,
2103 update_max_bonded_distance(bd_mol_mb.r2,
2105 at_offset + bd_mol_mb.a1,
2106 at_offset + bd_mol_mb.a2,
2109 at_offset += molt.atoms.nr;
2114 if (mtop->bIntermolecularInteractions)
2116 GMX_RELEASE_ASSERT(mtop->intermolecular_ilist,
2117 "We should have an ilist when intermolecular interactions are on");
2119 bonded_distance_intermol(
2120 *mtop->intermolecular_ilist, ddBondedChecking, x, ir->pbcType, box, &bd_2b, &bd_mb);
2123 *r_2b = sqrt(bd_2b.r2);
2124 *r_mb = sqrt(bd_mb.r2);
2126 if (*r_2b > 0 || *r_mb > 0)
2128 GMX_LOG(mdlog.info).appendText("Initial maximum distances in bonded interactions:");
2132 .appendTextFormatted(
2133 " two-body bonded interactions: %5.3f nm, %s, atoms %d %d",
2135 (bd_2b.ftype >= 0) ? interaction_function[bd_2b.ftype].longname : "Exclusion",
2142 .appendTextFormatted(
2143 " multi-body bonded interactions: %5.3f nm, %s, atoms %d %d",
2145 interaction_function[bd_mb.ftype].longname,