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 Store a vsite interaction at the end of \p il
105 * This routine is very similar to add_ifunc, but vsites interactions
106 * have more work to do than other kinds of interactions, and the
107 * complex way nral (and thus vector contents) depends on ftype
108 * confuses static analysis tools unless we fuse the vsite
109 * atom-indexing organization code with the ifunc-adding code, so that
110 * they can see that nral is the same value. */
111 static inline void add_ifunc_for_vsites(t_iatom* tiatoms,
112 const gmx_ga2la_t& ga2la,
118 const t_iatom* iatoms,
122 tiatoms[0] = iatoms[0];
126 /* We know the local index of the first atom */
131 /* Convert later in make_local_vsites */
132 tiatoms[1] = -a_gl - 1;
135 GMX_ASSERT(nral >= 2 && nral <= 5, "Invalid nral for vsites");
136 for (int k = 2; k < 1 + nral; k++)
138 int ak_gl = a_gl + iatoms[k] - a_mol;
139 if (const int* homeIndex = ga2la.findHome(ak_gl))
141 tiatoms[k] = *homeIndex;
145 /* Copy the global index, convert later in make_local_vsites */
146 tiatoms[k] = -(ak_gl + 1);
148 // Note that ga2la_get_home always sets the third parameter if
151 il->push_back(tiatoms[0], nral, tiatoms + 1);
154 /*! \brief Store a position restraint in idef and iatoms, complex because the parameters are different for each entry */
155 static void add_posres(int mol,
157 int numAtomsInMolecule,
158 const gmx_molblock_t& molb,
159 gmx::ArrayRef<int> iatoms,
160 const t_iparams* ip_in,
161 InteractionDefinitions* idef)
163 /* This position restraint has not been added yet,
164 * so it's index is the current number of position restraints.
166 const int n = idef->il[F_POSRES].size() / 2;
168 /* Get the position restraint coordinates from the molblock */
169 const int a_molb = mol * numAtomsInMolecule + a_mol;
170 GMX_ASSERT(a_molb < ssize(molb.posres_xA),
171 "We need a sufficient number of position restraint coordinates");
172 /* Copy the force constants */
173 t_iparams ip = ip_in[iatoms[0]];
174 ip.posres.pos0A[XX] = molb.posres_xA[a_molb][XX];
175 ip.posres.pos0A[YY] = molb.posres_xA[a_molb][YY];
176 ip.posres.pos0A[ZZ] = molb.posres_xA[a_molb][ZZ];
177 if (!molb.posres_xB.empty())
179 ip.posres.pos0B[XX] = molb.posres_xB[a_molb][XX];
180 ip.posres.pos0B[YY] = molb.posres_xB[a_molb][YY];
181 ip.posres.pos0B[ZZ] = molb.posres_xB[a_molb][ZZ];
185 ip.posres.pos0B[XX] = ip.posres.pos0A[XX];
186 ip.posres.pos0B[YY] = ip.posres.pos0A[YY];
187 ip.posres.pos0B[ZZ] = ip.posres.pos0A[ZZ];
189 /* Set the parameter index for idef->iparams_posres */
191 idef->iparams_posres.push_back(ip);
193 GMX_ASSERT(int(idef->iparams_posres.size()) == n + 1,
194 "The index of the parameter type should match n");
197 /*! \brief Store a flat-bottomed position restraint in idef and iatoms, complex because the parameters are different for each entry */
198 static void add_fbposres(int mol,
200 int numAtomsInMolecule,
201 const gmx_molblock_t& molb,
202 gmx::ArrayRef<int> iatoms,
203 const t_iparams* ip_in,
204 InteractionDefinitions* idef)
206 /* This flat-bottom position restraint has not been added yet,
207 * so it's index is the current number of position restraints.
209 const int n = idef->il[F_FBPOSRES].size() / 2;
211 /* Get the position restraint coordinats from the molblock */
212 const int a_molb = mol * numAtomsInMolecule + a_mol;
213 GMX_ASSERT(a_molb < ssize(molb.posres_xA),
214 "We need a sufficient number of position restraint coordinates");
215 /* Copy the force constants */
216 t_iparams ip = ip_in[iatoms[0]];
217 /* Take reference positions from A position of normal posres */
218 ip.fbposres.pos0[XX] = molb.posres_xA[a_molb][XX];
219 ip.fbposres.pos0[YY] = molb.posres_xA[a_molb][YY];
220 ip.fbposres.pos0[ZZ] = molb.posres_xA[a_molb][ZZ];
222 /* Note: no B-type for flat-bottom posres */
224 /* Set the parameter index for idef->iparams_fbposres */
226 idef->iparams_fbposres.push_back(ip);
228 GMX_ASSERT(int(idef->iparams_fbposres.size()) == n + 1,
229 "The index of the parameter type should match n");
232 /*! \brief Store a virtual site interaction, complex because of PBC and recursion */
233 static void add_vsite(const gmx_ga2la_t& ga2la,
234 gmx::ArrayRef<const int> index,
235 gmx::ArrayRef<const int> rtil,
242 const t_iatom* iatoms,
243 InteractionDefinitions* idef)
245 t_iatom tiatoms[1 + MAXATOMLIST];
247 /* Add this interaction to the local topology */
248 add_ifunc_for_vsites(tiatoms, ga2la, nral, bHomeA, a, a_gl, a_mol, iatoms, &idef->il[ftype]);
250 if (iatoms[1 + nral])
252 /* Check for recursion */
253 for (int k = 2; k < 1 + nral; k++)
255 if ((iatoms[1 + nral] & (2 << k)) && (tiatoms[k] < 0))
257 /* This construction atoms is a vsite and not a home atom */
261 "Constructing atom %d of vsite atom %d is a vsite and non-home\n",
265 /* Find the vsite construction */
267 /* Check all interactions assigned to this atom */
268 int j = index[iatoms[k]];
269 while (j < index[iatoms[k] + 1])
271 int ftype_r = rtil[j++];
272 int nral_r = NRAL(ftype_r);
273 if (interaction_function[ftype_r].flags & IF_VSITE)
275 /* Add this vsite (recursion) */
283 a_gl + iatoms[k] - iatoms[1],
288 j += 1 + nral_rt(ftype_r);
295 /*! \brief Returns the squared distance between atoms \p i and \p j */
296 static real dd_dist2(const t_pbc* pbc_null, ArrayRef<const RVec> coordinates, const int i, const int j)
302 pbc_dx_aiuc(pbc_null, coordinates[i], coordinates[j], dx);
306 rvec_sub(coordinates[i], coordinates[j], dx);
312 /*! \brief Append t_idef structures 1 to nsrc in src to *dest */
313 static void combine_idef(InteractionDefinitions* dest, gmx::ArrayRef<const thread_work_t> src)
315 for (int ftype = 0; ftype < F_NRE; ftype++)
318 for (gmx::index s = 1; s < src.ssize(); s++)
320 n += src[s].idef.il[ftype].size();
324 for (gmx::index s = 1; s < src.ssize(); s++)
326 dest->il[ftype].append(src[s].idef.il[ftype]);
329 /* Position restraints need an additional treatment */
330 if (ftype == F_POSRES || ftype == F_FBPOSRES)
332 int nposres = dest->il[ftype].size() / 2;
333 std::vector<t_iparams>& iparams_dest =
334 (ftype == F_POSRES ? dest->iparams_posres : dest->iparams_fbposres);
336 /* Set nposres to the number of original position restraints in dest */
337 for (gmx::index s = 1; s < src.ssize(); s++)
339 nposres -= src[s].idef.il[ftype].size() / 2;
342 for (gmx::index s = 1; s < src.ssize(); s++)
344 const std::vector<t_iparams>& iparams_src =
345 (ftype == F_POSRES ? src[s].idef.iparams_posres : src[s].idef.iparams_fbposres);
346 iparams_dest.insert(iparams_dest.end(), iparams_src.begin(), iparams_src.end());
348 /* Correct the indices into iparams_posres */
349 for (int i = 0; i < src[s].idef.il[ftype].size() / 2; i++)
351 /* Correct the index into iparams_posres */
352 dest->il[ftype].iatoms[nposres * 2] = nposres;
357 int(iparams_dest.size()) == nposres,
358 "The number of parameters should match the number of restraints");
364 //! Options for assigning interactions for atoms
365 enum class InteractionConnectivity
367 Intramolecular, //!< Only intra-molecular interactions
368 Intermolecular //!< Only inter-molecular interactions
371 /*! \brief Determine whether the local domain has responsibility for
372 * any of the bonded interactions for local atom \p atomIndex
373 * and assign those to the local domain.
375 * \returns The total number of bonded interactions for this atom for
376 * which this domain is responsible.
378 template<InteractionConnectivity interactionConnectivity>
379 static inline int assignInteractionsForAtom(const int atomIndex,
380 const int globalAtomIndex,
381 const int atomIndexInMolecule,
382 gmx::ArrayRef<const int> index,
383 gmx::ArrayRef<const int> rtil,
386 const gmx_ga2la_t& ga2la,
387 const gmx_domdec_zones_t* zones,
388 const bool checkDistanceMultiBody,
390 const bool checkDistanceTwoBody,
391 const real cutoffSquared,
392 const t_pbc* pbc_null,
393 ArrayRef<const RVec> coordinates,
394 InteractionDefinitions* idef,
396 const DDBondedChecking ddBondedChecking)
398 gmx::ArrayRef<const DDPairInteractionRanges> iZones = zones->iZones;
400 int numBondedInteractions = 0;
405 t_iatom tiatoms[1 + MAXATOMLIST];
407 const int ftype = rtil[j++];
408 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
409 const int nral = NRAL(ftype);
410 if (interaction_function[ftype].flags & IF_VSITE)
412 GMX_ASSERT(interactionConnectivity == InteractionConnectivity::Intramolecular,
413 "All vsites should be intramolecular");
415 /* The vsite construction goes where the vsite itself is */
436 tiatoms[0] = iatoms[0];
440 GMX_ASSERT(interactionConnectivity == InteractionConnectivity::Intramolecular,
441 "All interactions that involve a single atom are intramolecular");
443 /* Assign single-body interactions to the home zone.
444 * Position restraints are not handled here, but separately.
446 if (iz == 0 && !(ftype == F_POSRES || ftype == F_FBPOSRES))
449 tiatoms[1] = atomIndex;
454 /* This is a two-body interaction, we can assign
455 * analogous to the non-bonded assignments.
457 const int k_gl = (interactionConnectivity == InteractionConnectivity::Intramolecular)
459 /* Get the global index using the offset in the molecule */
460 (globalAtomIndex + iatoms[2] - atomIndexInMolecule)
462 if (const auto* entry = ga2la.find(k_gl))
464 int kz = entry->cell;
469 /* Check zone interaction assignments */
470 bUse = ((iz < iZones.ssize() && iz <= kz && iZones[iz].jZoneRange.isInRange(kz))
471 || (kz < iZones.ssize() && iz > kz && iZones[kz].jZoneRange.isInRange(iz)));
474 GMX_ASSERT(ftype != F_CONSTR || (iz == 0 && kz == 0),
475 "Constraint assigned here should only involve home atoms");
477 tiatoms[1] = atomIndex;
478 tiatoms[2] = entry->la;
479 /* If necessary check the cgcm distance */
480 if (checkDistanceTwoBody
481 && dd_dist2(pbc_null, coordinates, tiatoms[1], tiatoms[2]) >= cutoffSquared)
494 /* Assign this multi-body bonded interaction to
495 * the local domain if we have all the atoms involved
496 * (local or communicated) and the minimum zone shift
497 * in each dimension is zero, for dimensions
498 * with 2 DD cells an extra check may be necessary.
504 for (int k = 1; k <= nral && bUse; k++)
507 (interactionConnectivity == InteractionConnectivity::Intramolecular)
509 /* Get the global index using the offset in the molecule */
510 (globalAtomIndex + iatoms[k] - atomIndexInMolecule)
512 const auto* entry = ga2la.find(k_gl);
513 if (entry == nullptr || entry->cell >= zones->n)
515 /* We do not have this atom of this interaction
516 * locally, or it comes from more than one cell
523 tiatoms[k] = entry->la;
524 for (int d = 0; d < DIM; d++)
526 if (zones->shift[entry->cell][d] == 0)
537 bUse = (bUse && (k_zero[XX] != 0) && (k_zero[YY] != 0) && (k_zero[ZZ] != 0));
538 if (checkDistanceMultiBody)
540 for (int d = 0; (d < DIM && bUse); d++)
542 /* Check if the distance falls within
543 * the cut-off to avoid possible multiple
544 * assignments of bonded interactions.
546 if (rcheck[d] && k_plus[d]
547 && dd_dist2(pbc_null, coordinates, tiatoms[k_zero[d]], tiatoms[k_plus[d]])
557 /* Add this interaction to the local topology */
558 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms + 1);
559 /* Sum so we can check in global_stat
560 * if we have everything.
562 if (ddBondedChecking == DDBondedChecking::All
563 || !(interaction_function[ftype].flags & IF_LIMZERO))
565 numBondedInteractions++;
569 j += 1 + nral_rt(ftype);
572 return numBondedInteractions;
575 /*! \brief Determine whether the local domain has responsibility for
576 * any of the position restraints for local atom \p atomIndex
577 * and assign those to the local domain.
579 * \returns The total number of bonded interactions for this atom for
580 * which this domain is responsible.
582 static inline int assignPositionRestraintsForAtom(const int atomIndex,
584 const int atomIndexInMolecule,
585 const int numAtomsInMolecule,
586 gmx::ArrayRef<const int> rtil,
589 const gmx_molblock_t& molb,
590 const t_iparams* ip_in,
591 InteractionDefinitions* idef)
593 constexpr int nral = 1;
595 int numBondedInteractions = 0;
600 const int ftype = rtil[j++];
601 auto iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
603 if (ftype == F_POSRES || ftype == F_FBPOSRES)
605 std::array<int, 1 + nral> tiatoms = { iatoms[0], atomIndex };
606 if (ftype == F_POSRES)
608 add_posres(mol, atomIndexInMolecule, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
612 add_fbposres(mol, atomIndexInMolecule, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
614 idef->il[ftype].push_back(tiatoms[0], nral, tiatoms.data() + 1);
615 numBondedInteractions++;
617 j += 1 + nral_rt(ftype);
620 return numBondedInteractions;
623 /*! \brief This function looks up and assigns bonded interactions for zone iz.
625 * With thread parallelizing each thread acts on a different atom range:
626 * at_start to at_end.
628 static int make_bondeds_zone(gmx_reverse_top_t* rt,
629 ArrayRef<const int> globalAtomIndices,
630 const gmx_ga2la_t& ga2la,
631 const gmx_domdec_zones_t* zones,
632 const std::vector<gmx_molblock_t>& molb,
633 const bool checkDistanceMultiBody,
635 const bool checkDistanceTwoBody,
636 const real cutoffSquared,
637 const t_pbc* pbc_null,
638 ArrayRef<const RVec> coordinates,
639 const t_iparams* ip_in,
640 InteractionDefinitions* idef,
642 const gmx::Range<int>& atomRange)
647 int atomIndexInMolecule = 0;
649 const auto ddBondedChecking = rt->options().ddBondedChecking;
651 int numBondedInteractions = 0;
653 for (int i : atomRange)
655 /* Get the global atom number */
656 const int globalAtomIndex = globalAtomIndices[i];
657 global_atomnr_to_moltype_ind(
658 rt->molblockIndices(), globalAtomIndex, &mb, &mt, &mol, &atomIndexInMolecule);
659 /* Check all intramolecular interactions assigned to this atom */
660 gmx::ArrayRef<const int> index = rt->interactionListForMoleculeType(mt).index;
661 gmx::ArrayRef<const t_iatom> rtil = rt->interactionListForMoleculeType(mt).il;
663 numBondedInteractions += assignInteractionsForAtom<InteractionConnectivity::Intramolecular>(
669 index[atomIndexInMolecule],
670 index[atomIndexInMolecule + 1],
673 checkDistanceMultiBody,
675 checkDistanceTwoBody,
683 // Assign position restraints, when present, for the home zone
684 if (izone == 0 && rt->hasPositionRestraints())
686 numBondedInteractions += assignPositionRestraintsForAtom(
690 rt->interactionListForMoleculeType(mt).numAtomsInMolecule,
692 index[atomIndexInMolecule],
693 index[atomIndexInMolecule + 1],
699 if (rt->hasIntermolecularInteractions())
701 /* Check all intermolecular interactions assigned to this atom */
702 index = rt->interactionListForIntermolecularInteractions().index;
703 rtil = rt->interactionListForIntermolecularInteractions().il;
705 numBondedInteractions += assignInteractionsForAtom<InteractionConnectivity::Intermolecular>(
711 index[globalAtomIndex],
712 index[globalAtomIndex + 1],
715 checkDistanceMultiBody,
717 checkDistanceTwoBody,
727 return numBondedInteractions;
730 /*! \brief Set the exclusion data for i-zone \p iz */
731 static void make_exclusions_zone(ArrayRef<const int> globalAtomIndices,
732 const gmx_ga2la_t& ga2la,
733 gmx_domdec_zones_t* zones,
734 ArrayRef<const MolblockIndices> molblockIndices,
735 const std::vector<gmx_moltype_t>& moltype,
737 ListOfLists<int>* lexcls,
741 const gmx::ArrayRef<const int> intermolecularExclusionGroup)
743 const auto& jAtomRange = zones->iZones[iz].jAtomRange;
745 const gmx::index oldNumLists = lexcls->ssize();
747 std::vector<int> exclusionsForAtom;
748 for (int at = at_start; at < at_end; at++)
750 exclusionsForAtom.clear();
752 if (GET_CGINFO_EXCL_INTER(cginfo[at]))
759 /* Copy the exclusions from the global top */
760 int a_gl = globalAtomIndices[at];
761 global_atomnr_to_moltype_ind(molblockIndices, a_gl, &mb, &mt, &mol, &a_mol);
762 const auto excls = moltype[mt].excls[a_mol];
763 for (const int aj_mol : excls)
765 if (const auto* jEntry = ga2la.find(a_gl + aj_mol - a_mol))
767 /* This check is not necessary, but it can reduce
768 * the number of exclusions in the list, which in turn
769 * can speed up the pair list construction a bit.
771 if (jAtomRange.isInRange(jEntry->la))
773 exclusionsForAtom.push_back(jEntry->la);
779 bool isExcludedAtom = !intermolecularExclusionGroup.empty()
780 && std::find(intermolecularExclusionGroup.begin(),
781 intermolecularExclusionGroup.end(),
782 globalAtomIndices[at])
783 != intermolecularExclusionGroup.end();
787 for (int qmAtomGlobalIndex : intermolecularExclusionGroup)
789 if (const auto* entry = ga2la.find(qmAtomGlobalIndex))
791 exclusionsForAtom.push_back(entry->la);
796 /* Append the exclusions for this atom to the topology */
797 lexcls->pushBack(exclusionsForAtom);
801 lexcls->ssize() - oldNumLists == at_end - at_start,
802 "The number of exclusion list should match the number of atoms in the range");
805 /*! \brief Generate and store all required local bonded interactions in \p idef and local exclusions in \p lexcls
807 * \returns Total count of bonded interactions in the local topology on this domain */
808 static int make_local_bondeds_excls(gmx_domdec_t* dd,
809 gmx_domdec_zones_t* zones,
810 const gmx_mtop_t& mtop,
812 const bool checkDistanceMultiBody,
814 const gmx_bool checkDistanceTwoBody,
816 const t_pbc* pbc_null,
817 ArrayRef<const RVec> coordinates,
818 InteractionDefinitions* idef,
819 ListOfLists<int>* lexcls)
821 int nzone_bondeds = 0;
823 if (dd->reverse_top->hasInterAtomicInteractions())
825 nzone_bondeds = zones->n;
829 /* Only single charge group (or atom) molecules, so interactions don't
830 * cross zone boundaries and we only need to assign in the home zone.
835 /* We only use exclusions from i-zones to i- and j-zones */
836 const int numIZonesForExclusions = (dd->haveExclusions ? zones->iZones.size() : 0);
838 gmx_reverse_top_t* rt = dd->reverse_top.get();
840 const real cutoffSquared = gmx::square(cutoff);
842 /* Clear the counts */
844 int numBondedInteractions = 0;
848 for (int izone = 0; izone < nzone_bondeds; izone++)
850 const int cg0 = zones->cg_range[izone];
851 const int cg1 = zones->cg_range[izone + 1];
853 gmx::ArrayRef<thread_work_t> threadWorkObjects = rt->threadWorkObjects();
854 const int numThreads = threadWorkObjects.size();
855 #pragma omp parallel for num_threads(numThreads) schedule(static)
856 for (int thread = 0; thread < numThreads; thread++)
860 InteractionDefinitions* idef_t = nullptr;
862 int cg0t = cg0 + ((cg1 - cg0) * thread) / numThreads;
863 int cg1t = cg0 + ((cg1 - cg0) * (thread + 1)) / numThreads;
871 idef_t = &threadWorkObjects[thread].idef;
875 threadWorkObjects[thread].numBondedInteractions =
876 make_bondeds_zone(rt,
877 dd->globalAtomIndices,
881 checkDistanceMultiBody,
883 checkDistanceTwoBody,
887 idef->iparams.data(),
890 gmx::Range<int>(cg0t, cg1t));
892 if (izone < numIZonesForExclusions)
894 ListOfLists<int>* excl_t = nullptr;
897 // Thread 0 stores exclusions directly in the final storage
902 // Threads > 0 store in temporary storage, starting at list index 0
903 excl_t = &threadWorkObjects[thread].excl;
907 /* No charge groups and no distance check required */
908 make_exclusions_zone(dd->globalAtomIndices,
911 rt->molblockIndices(),
918 mtop.intermolecularExclusionGroup);
921 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
924 if (threadWorkObjects.size() > 1)
926 combine_idef(idef, threadWorkObjects);
929 for (const thread_work_t& th_work : threadWorkObjects)
931 numBondedInteractions += th_work.numBondedInteractions;
934 if (izone < numIZonesForExclusions)
936 for (std::size_t th = 1; th < threadWorkObjects.size(); th++)
938 lexcls->appendListOfLists(threadWorkObjects[th].excl);
945 fprintf(debug, "We have %d exclusions\n", lexcls->numElements());
948 return numBondedInteractions;
951 int dd_make_local_top(gmx_domdec_t* dd,
952 gmx_domdec_zones_t* zones,
958 ArrayRef<const RVec> coordinates,
959 const gmx_mtop_t& mtop,
960 gmx_localtop_t* ltop)
964 t_pbc pbc, *pbc_null = nullptr;
968 fprintf(debug, "Making local topology\n");
971 bool checkDistanceMultiBody = false;
972 bool checkDistanceTwoBody = false;
974 if (dd->reverse_top->hasInterAtomicInteractions())
976 /* We need to check to which cell bondeds should be assigned */
977 rc = dd_cutoff_twobody(dd);
980 fprintf(debug, "Two-body bonded cut-off distance is %g\n", rc);
983 /* Should we check distances when assigning bonded interactions? */
984 for (int d = 0; d < DIM; d++)
987 /* Only need to check for dimensions where the part of the box
988 * that is not communicated is smaller than the cut-off.
990 if (d < npbcdim && dd->numCells[d] > 1
991 && (dd->numCells[d] - npulse[d]) * cellsize_min[d] < 2 * rc)
993 if (dd->numCells[d] == 2)
996 checkDistanceMultiBody = TRUE;
998 /* Check for interactions between two atoms,
999 * where we can allow interactions up to the cut-off,
1000 * instead of up to the smallest cell dimension.
1002 checkDistanceTwoBody = TRUE;
1007 "dim %d cellmin %f bonded rcheck[%d] = %d, checkDistanceTwoBody = %s\n",
1012 gmx::boolToString(checkDistanceTwoBody));
1015 if (checkDistanceMultiBody || checkDistanceTwoBody)
1019 pbc_null = set_pbc_dd(&pbc, fr->pbcType, dd->numCells, TRUE, box);
1028 int numBondedInteractionsToReduce = make_local_bondeds_excls(dd,
1032 checkDistanceMultiBody,
1034 checkDistanceTwoBody,
1041 /* The ilist is not sorted yet,
1042 * we can only do this when we have the charge arrays.
1044 ltop->idef.ilsort = ilsortUNKNOWN;
1046 return numBondedInteractionsToReduce;
1049 void dd_sort_local_top(const gmx_domdec_t& dd, const t_mdatoms* mdatoms, gmx_localtop_t* ltop)
1051 if (dd.reverse_top->doSorting())
1053 gmx_sort_ilist_fe(<op->idef, mdatoms->chargeA, mdatoms->chargeB);
1057 ltop->idef.ilsort = ilsortNO_FE;
1061 void dd_init_local_state(const gmx_domdec_t& dd, const t_state* state_global, t_state* state_local)
1063 int buf[NITEM_DD_INIT_LOCAL_STATE];
1067 buf[0] = state_global->flags;
1068 buf[1] = state_global->ngtc;
1069 buf[2] = state_global->nnhpres;
1070 buf[3] = state_global->nhchainlength;
1071 buf[4] = state_global->dfhist ? state_global->dfhist->nlambda : 0;
1073 dd_bcast(&dd, NITEM_DD_INIT_LOCAL_STATE * sizeof(int), buf);
1075 init_gtc_state(state_local, buf[1], buf[2], buf[3]);
1076 init_dfhist_state(state_local, buf[4]);
1077 state_local->flags = buf[0];
1080 /*! \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 */
1081 static void check_link(t_blocka* link, int cg_gl, int cg_gl_j)
1083 bool bFound = false;
1084 for (int k = link->index[cg_gl]; k < link->index[cg_gl + 1]; k++)
1086 GMX_RELEASE_ASSERT(link->a, "Inconsistent NULL pointer while making charge-group links");
1087 if (link->a[k] == cg_gl_j)
1094 GMX_RELEASE_ASSERT(link->a || link->index[cg_gl + 1] + 1 > link->nalloc_a,
1095 "Inconsistent allocation of link");
1096 /* Add this charge group link */
1097 if (link->index[cg_gl + 1] + 1 > link->nalloc_a)
1099 link->nalloc_a = over_alloc_large(link->index[cg_gl + 1] + 1);
1100 srenew(link->a, link->nalloc_a);
1102 link->a[link->index[cg_gl + 1]] = cg_gl_j;
1103 link->index[cg_gl + 1]++;
1107 void makeBondedLinks(gmx_domdec_t* dd, const gmx_mtop_t& mtop, gmx::ArrayRef<cginfo_mb_t> cginfo_mb)
1110 if (!dd->comm->systemInfo.filterBondedCommunication)
1112 /* Only communicate atoms based on cut-off */
1113 dd->comm->bondedLinks = nullptr;
1117 t_blocka* link = nullptr;
1119 /* For each atom make a list of other atoms in the system
1120 * that a linked to it via bonded interactions
1121 * which are also stored in reverse_top.
1124 reverse_ilist_t ril_intermol;
1125 if (mtop.bIntermolecularInteractions)
1129 atoms.nr = mtop.natoms;
1130 atoms.atom = nullptr;
1132 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
1133 "We should have an ilist when intermolecular interactions are on");
1135 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1137 *mtop.intermolecular_ilist, &atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril_intermol);
1141 snew(link->index, mtop.natoms + 1);
1148 for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
1150 const gmx_molblock_t& molb = mtop.molblock[mb];
1155 const gmx_moltype_t& molt = mtop.moltype[molb.type];
1156 /* Make a reverse ilist in which the interactions are linked
1157 * to all atoms, not only the first atom as in gmx_reverse_top.
1158 * The constraints are discarded here.
1160 ReverseTopOptions rtOptions(DDBondedChecking::ExcludeZeroLimit);
1161 reverse_ilist_t ril;
1162 make_reverse_ilist(molt.ilist, &molt.atoms, rtOptions, AtomLinkRule::AllAtomsInBondeds, &ril);
1164 cginfo_mb_t* cgi_mb = &cginfo_mb[mb];
1167 for (mol = 0; mol < (mtop.bIntermolecularInteractions ? molb.nmol : 1); mol++)
1169 for (int a = 0; a < molt.atoms.nr; a++)
1171 int cg_gl = cg_offset + a;
1172 link->index[cg_gl + 1] = link->index[cg_gl];
1173 int i = ril.index[a];
1174 while (i < ril.index[a + 1])
1176 int ftype = ril.il[i++];
1177 int nral = NRAL(ftype);
1178 /* Skip the ifunc index */
1180 for (int j = 0; j < nral; j++)
1182 int aj = ril.il[i + j];
1185 check_link(link, cg_gl, cg_offset + aj);
1188 i += nral_rt(ftype);
1191 if (mtop.bIntermolecularInteractions)
1193 int i = ril_intermol.index[cg_gl];
1194 while (i < ril_intermol.index[cg_gl + 1])
1196 int ftype = ril_intermol.il[i++];
1197 int nral = NRAL(ftype);
1198 /* Skip the ifunc index */
1200 for (int j = 0; j < nral; j++)
1202 /* Here we assume we have no charge groups;
1203 * this has been checked above.
1205 int aj = ril_intermol.il[i + j];
1206 check_link(link, cg_gl, aj);
1208 i += nral_rt(ftype);
1211 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0)
1213 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[a]);
1218 cg_offset += molt.atoms.nr;
1220 int nlink_mol = link->index[cg_offset] - link->index[cg_offset - molt.atoms.nr];
1225 "molecule type '%s' %d atoms has %d atom links through bonded interac.\n",
1231 if (molb.nmol > mol)
1233 /* Copy the data for the rest of the molecules in this block */
1234 link->nalloc_a += (molb.nmol - mol) * nlink_mol;
1235 srenew(link->a, link->nalloc_a);
1236 for (; mol < molb.nmol; mol++)
1238 for (int a = 0; a < molt.atoms.nr; a++)
1240 int cg_gl = cg_offset + a;
1241 link->index[cg_gl + 1] = link->index[cg_gl + 1 - molt.atoms.nr] + nlink_mol;
1242 for (int j = link->index[cg_gl]; j < link->index[cg_gl + 1]; j++)
1244 link->a[j] = link->a[j - nlink_mol] + molt.atoms.nr;
1246 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0
1247 && cg_gl - cgi_mb->cg_start < cgi_mb->cg_mod)
1249 SET_CGINFO_BOND_INTER(cgi_mb->cginfo[cg_gl - cgi_mb->cg_start]);
1253 cg_offset += molt.atoms.nr;
1260 fprintf(debug, "Of the %d atoms %d are linked via bonded interactions\n", mtop.natoms, ncgi);
1263 dd->comm->bondedLinks = link;
1272 } bonded_distance_t;
1274 /*! \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 */
1275 static void update_max_bonded_distance(real r2, int ftype, int a1, int a2, bonded_distance_t* bd)
1286 /*! \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 */
1287 static void bonded_cg_distance_mol(const gmx_moltype_t* molt,
1288 const DDBondedChecking ddBondedChecking,
1290 ArrayRef<const RVec> x,
1291 bonded_distance_t* bd_2b,
1292 bonded_distance_t* bd_mb)
1294 const ReverseTopOptions rtOptions(ddBondedChecking);
1296 for (int ftype = 0; ftype < F_NRE; ftype++)
1298 if (dd_check_ftype(ftype, rtOptions))
1300 const auto& il = molt->ilist[ftype];
1301 int nral = NRAL(ftype);
1304 for (int i = 0; i < il.size(); i += 1 + nral)
1306 for (int ai = 0; ai < nral; ai++)
1308 int atomI = il.iatoms[i + 1 + ai];
1309 for (int aj = ai + 1; aj < nral; aj++)
1311 int atomJ = il.iatoms[i + 1 + aj];
1314 real rij2 = distance2(x[atomI], x[atomJ]);
1316 update_max_bonded_distance(
1317 rij2, ftype, atomI, atomJ, (nral == 2) ? bd_2b : bd_mb);
1327 const auto& excls = molt->excls;
1328 for (gmx::index ai = 0; ai < excls.ssize(); ai++)
1330 for (const int aj : excls[ai])
1334 real rij2 = distance2(x[ai], x[aj]);
1336 /* There is no function type for exclusions, use -1 */
1337 update_max_bonded_distance(rij2, -1, ai, aj, bd_2b);
1344 /*! \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 */
1345 static void bonded_distance_intermol(const InteractionLists& ilists_intermol,
1346 const DDBondedChecking ddBondedChecking,
1347 ArrayRef<const RVec> x,
1350 bonded_distance_t* bd_2b,
1351 bonded_distance_t* bd_mb)
1355 set_pbc(&pbc, pbcType, box);
1357 const ReverseTopOptions rtOptions(ddBondedChecking);
1359 for (int ftype = 0; ftype < F_NRE; ftype++)
1361 if (dd_check_ftype(ftype, rtOptions))
1363 const auto& il = ilists_intermol[ftype];
1364 int nral = NRAL(ftype);
1366 /* No nral>1 check here, since intermol interactions always
1367 * have nral>=2 (and the code is also correct for nral=1).
1369 for (int i = 0; i < il.size(); i += 1 + nral)
1371 for (int ai = 0; ai < nral; ai++)
1373 int atom_i = il.iatoms[i + 1 + ai];
1375 for (int aj = ai + 1; aj < nral; aj++)
1379 int atom_j = il.iatoms[i + 1 + aj];
1381 pbc_dx(&pbc, x[atom_i], x[atom_j], dx);
1383 const real rij2 = norm2(dx);
1385 update_max_bonded_distance(rij2, ftype, atom_i, atom_j, (nral == 2) ? bd_2b : bd_mb);
1393 //! Returns whether \p molt has at least one virtual site
1394 static bool moltypeHasVsite(const gmx_moltype_t& molt)
1396 bool hasVsite = false;
1397 for (int i = 0; i < F_NRE; i++)
1399 if ((interaction_function[i].flags & IF_VSITE) && !molt.ilist[i].empty())
1408 //! Returns coordinates not broken over PBC for a molecule
1409 static void getWholeMoleculeCoordinates(const gmx_moltype_t* molt,
1410 const gmx_ffparams_t* ffparams,
1414 ArrayRef<const RVec> x,
1417 if (pbcType != PbcType::No)
1419 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(x.data()));
1421 shift_x(graph, box, as_rvec_array(x.data()), as_rvec_array(xs.data()));
1422 /* By doing an extra mk_mshift the molecules that are broken
1423 * because they were e.g. imported from another software
1424 * will be made whole again. Such are the healing powers
1427 mk_mshift(nullptr, graph, pbcType, box, as_rvec_array(xs.data()));
1431 /* We copy the coordinates so the original coordinates remain
1432 * unchanged, just to be 100% sure that we do not affect
1433 * binary reproducibility of simulations.
1435 for (int i = 0; i < molt->atoms.nr; i++)
1437 copy_rvec(x[i], xs[i]);
1441 if (moltypeHasVsite(*molt))
1443 gmx::constructVirtualSites(xs, ffparams->iparams, molt->ilist);
1447 void dd_bonded_cg_distance(const gmx::MDLogger& mdlog,
1448 const gmx_mtop_t& mtop,
1449 const t_inputrec& inputrec,
1450 ArrayRef<const RVec> x,
1452 const DDBondedChecking ddBondedChecking,
1456 bonded_distance_t bd_2b = { 0, -1, -1, -1 };
1457 bonded_distance_t bd_mb = { 0, -1, -1, -1 };
1459 bool bExclRequired = inputrecExclForces(&inputrec);
1464 for (const gmx_molblock_t& molb : mtop.molblock)
1466 const gmx_moltype_t& molt = mtop.moltype[molb.type];
1467 if (molt.atoms.nr == 1 || molb.nmol == 0)
1469 at_offset += molb.nmol * molt.atoms.nr;
1474 if (inputrec.pbcType != PbcType::No)
1476 graph = mk_graph_moltype(molt);
1479 std::vector<RVec> xs(molt.atoms.nr);
1480 for (int mol = 0; mol < molb.nmol; mol++)
1482 getWholeMoleculeCoordinates(&molt,
1487 x.subArray(at_offset, molt.atoms.nr),
1490 bonded_distance_t bd_mol_2b = { 0, -1, -1, -1 };
1491 bonded_distance_t bd_mol_mb = { 0, -1, -1, -1 };
1493 bonded_cg_distance_mol(&molt, ddBondedChecking, bExclRequired, xs, &bd_mol_2b, &bd_mol_mb);
1495 /* Process the mol data adding the atom index offset */
1496 update_max_bonded_distance(bd_mol_2b.r2,
1498 at_offset + bd_mol_2b.a1,
1499 at_offset + bd_mol_2b.a2,
1501 update_max_bonded_distance(bd_mol_mb.r2,
1503 at_offset + bd_mol_mb.a1,
1504 at_offset + bd_mol_mb.a2,
1507 at_offset += molt.atoms.nr;
1512 if (mtop.bIntermolecularInteractions)
1514 GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
1515 "We should have an ilist when intermolecular interactions are on");
1517 bonded_distance_intermol(
1518 *mtop.intermolecular_ilist, ddBondedChecking, x, inputrec.pbcType, box, &bd_2b, &bd_mb);
1521 *r_2b = sqrt(bd_2b.r2);
1522 *r_mb = sqrt(bd_mb.r2);
1524 if (*r_2b > 0 || *r_mb > 0)
1526 GMX_LOG(mdlog.info).appendText("Initial maximum distances in bonded interactions:");
1530 .appendTextFormatted(
1531 " two-body bonded interactions: %5.3f nm, %s, atoms %d %d",
1533 (bd_2b.ftype >= 0) ? interaction_function[bd_2b.ftype].longname : "Exclusion",
1540 .appendTextFormatted(
1541 " multi-body bonded interactions: %5.3f nm, %s, atoms %d %d",
1543 interaction_function[bd_mb.ftype].longname,