e8fa082df4d489dafe5119cb261673fe4782541c
[alexxy/gromacs.git] / src / gromacs / domdec / domdec_topology.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2006 - 2014, The GROMACS development team.
5  * Copyright (c) 2015,2016,2017,2018,2019,2020, 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.
9  *
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.
14  *
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.
19  *
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.
24  *
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.
32  *
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.
35  */
36
37 /*! \internal \file
38  *
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.
42  *
43  * \author Berk Hess <hess@kth.se>
44  * \ingroup module_domdec
45  */
46
47 #include "gmxpre.h"
48
49 #include <cassert>
50 #include <cstdlib>
51 #include <cstring>
52
53 #include <algorithm>
54 #include <memory>
55 #include <string>
56
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/mdtypes/commrec.h"
65 #include "gromacs/mdtypes/inputrec.h"
66 #include "gromacs/mdtypes/md_enums.h"
67 #include "gromacs/mdtypes/mdatom.h"
68 #include "gromacs/mdtypes/state.h"
69 #include "gromacs/pbcutil/mshift.h"
70 #include "gromacs/pbcutil/pbc.h"
71 #include "gromacs/topology/ifunc.h"
72 #include "gromacs/topology/mtop_util.h"
73 #include "gromacs/topology/topsort.h"
74 #include "gromacs/utility/cstringutil.h"
75 #include "gromacs/utility/exceptions.h"
76 #include "gromacs/utility/fatalerror.h"
77 #include "gromacs/utility/gmxassert.h"
78 #include "gromacs/utility/listoflists.h"
79 #include "gromacs/utility/logger.h"
80 #include "gromacs/utility/smalloc.h"
81 #include "gromacs/utility/strconvert.h"
82 #include "gromacs/utility/stringstream.h"
83 #include "gromacs/utility/stringutil.h"
84 #include "gromacs/utility/textwriter.h"
85
86 #include "domdec_constraints.h"
87 #include "domdec_internal.h"
88 #include "domdec_vsite.h"
89 #include "dump.h"
90
91 using gmx::ListOfLists;
92
93 /*! \brief The number of integer item in the local state, used for broadcasting of the state */
94 #define NITEM_DD_INIT_LOCAL_STATE 5
95
96 struct reverse_ilist_t
97 {
98     std::vector<int> index;              /* Index for each atom into il          */
99     std::vector<int> il;                 /* ftype|type|a0|...|an|ftype|...       */
100     int              numAtomsInMolecule; /* The number of atoms in this molecule */
101 };
102
103 struct MolblockIndices
104 {
105     int a_start;
106     int a_end;
107     int natoms_mol;
108     int type;
109 };
110
111 /*! \brief Struct for thread local work data for local topology generation */
112 struct thread_work_t
113 {
114     t_idef                    idef;       /**< Partial local topology */
115     std::unique_ptr<VsitePbc> vsitePbc;   /**< vsite PBC structure */
116     int                       nbonded;    /**< The number of bondeds in this struct */
117     ListOfLists<int>          excl;       /**< List of exclusions */
118     int                       excl_count; /**< The total exclusion count for \p excl */
119 };
120
121 /*! \brief Struct for the reverse topology: links bonded interactions to atomsx */
122 struct gmx_reverse_top_t
123 {
124     //! @cond Doxygen_Suppress
125     //! \brief Are there constraints in this revserse top?
126     bool bConstr = false;
127     //! \brief Are there settles in this revserse top?
128     bool bSettle = false;
129     //! \brief All bonded interactions have to be assigned?
130     bool bBCheck = false;
131     //! \brief Are there bondeds/exclusions between atoms?
132     bool bInterAtomicInteractions = false;
133     //! \brief Reverse ilist for all moltypes
134     std::vector<reverse_ilist_t> ril_mt;
135     //! \brief The size of ril_mt[?].index summed over all entries
136     int ril_mt_tot_size = 0;
137     //! \brief The sorting state of bondeds for free energy
138     int ilsort = ilsortUNKNOWN;
139     //! \brief molblock to global atom index for quick lookup of molblocks on atom index
140     std::vector<MolblockIndices> mbi;
141
142     //! \brief Do we have intermolecular interactions?
143     bool bIntermolecularInteractions = false;
144     //! \brief Intermolecular reverse ilist
145     reverse_ilist_t ril_intermol;
146
147     /* Work data structures for multi-threading */
148     //! \brief Thread work array for local topology generation
149     std::vector<thread_work_t> th_work;
150     //! @endcond
151 };
152
153 /*! \brief Returns the number of atom entries for il in gmx_reverse_top_t */
154 static int nral_rt(int ftype)
155 {
156     int nral;
157
158     nral = NRAL(ftype);
159     if (interaction_function[ftype].flags & IF_VSITE)
160     {
161         /* With vsites the reverse topology contains an extra entry
162          * for storing if constructing atoms are vsites.
163          */
164         nral += 1;
165     }
166
167     return nral;
168 }
169
170 /*! \brief Return whether interactions of type \p ftype need to be assigned exactly once */
171 static gmx_bool dd_check_ftype(int ftype, gmx_bool bBCheck, gmx_bool bConstr, gmx_bool bSettle)
172 {
173     return ((((interaction_function[ftype].flags & IF_BOND) != 0U)
174              && ((interaction_function[ftype].flags & IF_VSITE) == 0U)
175              && (bBCheck || ((interaction_function[ftype].flags & IF_LIMZERO) == 0U)))
176             || (bConstr && (ftype == F_CONSTR || ftype == F_CONSTRNC)) || (bSettle && ftype == F_SETTLE));
177 }
178
179 /*! \brief Help print error output when interactions are missing */
180 static std::string print_missing_interactions_mb(t_commrec*               cr,
181                                                  const gmx_reverse_top_t* rt,
182                                                  const char*              moltypename,
183                                                  const reverse_ilist_t*   ril,
184                                                  int                      a_start,
185                                                  int                      a_end,
186                                                  int                      nat_mol,
187                                                  int                      nmol,
188                                                  const t_idef*            idef)
189 {
190     int* assigned;
191     int  nril_mol = ril->index[nat_mol];
192     snew(assigned, nmol * nril_mol);
193     gmx::StringOutputStream stream;
194     gmx::TextWriter         log(&stream);
195
196     gmx::ArrayRef<const int> gatindex = cr->dd->globalAtomIndices;
197     for (int ftype = 0; ftype < F_NRE; ftype++)
198     {
199         if (dd_check_ftype(ftype, rt->bBCheck, rt->bConstr, rt->bSettle))
200         {
201             int            nral = NRAL(ftype);
202             const t_ilist* il   = &idef->il[ftype];
203             const t_iatom* ia   = il->iatoms;
204             for (int i = 0; i < il->nr; i += 1 + nral)
205             {
206                 int a0 = gatindex[ia[1]];
207                 /* Check if this interaction is in
208                  * the currently checked molblock.
209                  */
210                 if (a0 >= a_start && a0 < a_end)
211                 {
212                     int  mol    = (a0 - a_start) / nat_mol;
213                     int  a0_mol = (a0 - a_start) - mol * nat_mol;
214                     int  j_mol  = ril->index[a0_mol];
215                     bool found  = false;
216                     while (j_mol < ril->index[a0_mol + 1] && !found)
217                     {
218                         int j       = mol * nril_mol + j_mol;
219                         int ftype_j = ril->il[j_mol];
220                         /* Here we need to check if this interaction has
221                          * not already been assigned, since we could have
222                          * multiply defined interactions.
223                          */
224                         if (ftype == ftype_j && ia[0] == ril->il[j_mol + 1] && assigned[j] == 0)
225                         {
226                             /* Check the atoms */
227                             found = true;
228                             for (int a = 0; a < nral; a++)
229                             {
230                                 if (gatindex[ia[1 + a]] != a_start + mol * nat_mol + ril->il[j_mol + 2 + a])
231                                 {
232                                     found = false;
233                                 }
234                             }
235                             if (found)
236                             {
237                                 assigned[j] = 1;
238                             }
239                         }
240                         j_mol += 2 + nral_rt(ftype_j);
241                     }
242                     if (!found)
243                     {
244                         gmx_incons("Some interactions seem to be assigned multiple times");
245                     }
246                 }
247                 ia += 1 + nral;
248             }
249         }
250     }
251
252     gmx_sumi(nmol * nril_mol, assigned, cr);
253
254     int nprint = 10;
255     int i      = 0;
256     for (int mol = 0; mol < nmol; mol++)
257     {
258         int j_mol = 0;
259         while (j_mol < nril_mol)
260         {
261             int ftype = ril->il[j_mol];
262             int nral  = NRAL(ftype);
263             int j     = mol * nril_mol + j_mol;
264             if (assigned[j] == 0 && !(interaction_function[ftype].flags & IF_VSITE))
265             {
266                 if (DDMASTER(cr->dd))
267                 {
268                     if (i == 0)
269                     {
270                         log.writeLineFormatted("Molecule type '%s'", moltypename);
271                         log.writeLineFormatted(
272                                 "the first %d missing interactions, except for exclusions:", nprint);
273                     }
274                     log.writeStringFormatted("%20s atoms", interaction_function[ftype].longname);
275                     int a;
276                     for (a = 0; a < nral; a++)
277                     {
278                         log.writeStringFormatted("%5d", ril->il[j_mol + 2 + a] + 1);
279                     }
280                     while (a < 4)
281                     {
282                         log.writeString("     ");
283                         a++;
284                     }
285                     log.writeString(" global");
286                     for (a = 0; a < nral; a++)
287                     {
288                         log.writeStringFormatted(
289                                 "%6d", a_start + mol * nat_mol + ril->il[j_mol + 2 + a] + 1);
290                     }
291                     log.ensureLineBreak();
292                 }
293                 i++;
294                 if (i >= nprint)
295                 {
296                     break;
297                 }
298             }
299             j_mol += 2 + nral_rt(ftype);
300         }
301     }
302
303     sfree(assigned);
304     return stream.toString();
305 }
306
307 /*! \brief Help print error output when interactions are missing */
308 static void print_missing_interactions_atoms(const gmx::MDLogger& mdlog,
309                                              t_commrec*           cr,
310                                              const gmx_mtop_t*    mtop,
311                                              const t_idef*        idef)
312 {
313     const gmx_reverse_top_t* rt = cr->dd->reverse_top;
314
315     /* Print the atoms in the missing interactions per molblock */
316     int a_end = 0;
317     for (const gmx_molblock_t& molb : mtop->molblock)
318     {
319         const gmx_moltype_t& moltype = mtop->moltype[molb.type];
320         int                  a_start = a_end;
321         a_end                        = a_start + molb.nmol * moltype.atoms.nr;
322
323         GMX_LOG(mdlog.warning)
324                 .appendText(print_missing_interactions_mb(cr, rt, *(moltype.name),
325                                                           &rt->ril_mt[molb.type], a_start, a_end,
326                                                           moltype.atoms.nr, molb.nmol, idef));
327     }
328 }
329
330 void dd_print_missing_interactions(const gmx::MDLogger&  mdlog,
331                                    t_commrec*            cr,
332                                    int                   local_count,
333                                    const gmx_mtop_t*     top_global,
334                                    const gmx_localtop_t* top_local,
335                                    const rvec*           x,
336                                    const matrix          box)
337 {
338     int           ndiff_tot, cl[F_NRE], n, ndiff, rest_global, rest_local;
339     int           ftype, nral;
340     gmx_domdec_t* dd;
341
342     dd = cr->dd;
343
344     GMX_LOG(mdlog.warning)
345             .appendText(
346                     "Not all bonded interactions have been properly assigned to the domain "
347                     "decomposition cells");
348
349     ndiff_tot = local_count - dd->nbonded_global;
350
351     for (ftype = 0; ftype < F_NRE; ftype++)
352     {
353         nral      = NRAL(ftype);
354         cl[ftype] = top_local->idef.il[ftype].nr / (1 + nral);
355     }
356
357     gmx_sumi(F_NRE, cl, cr);
358
359     if (DDMASTER(dd))
360     {
361         GMX_LOG(mdlog.warning).appendText("A list of missing interactions:");
362         rest_global = dd->nbonded_global;
363         rest_local  = local_count;
364         for (ftype = 0; ftype < F_NRE; ftype++)
365         {
366             /* In the reverse and local top all constraints are merged
367              * into F_CONSTR. So in the if statement we skip F_CONSTRNC
368              * and add these constraints when doing F_CONSTR.
369              */
370             if (((interaction_function[ftype].flags & IF_BOND)
371                  && (dd->reverse_top->bBCheck || !(interaction_function[ftype].flags & IF_LIMZERO)))
372                 || (dd->reverse_top->bConstr && ftype == F_CONSTR)
373                 || (dd->reverse_top->bSettle && ftype == F_SETTLE))
374             {
375                 n = gmx_mtop_ftype_count(top_global, ftype);
376                 if (ftype == F_CONSTR)
377                 {
378                     n += gmx_mtop_ftype_count(top_global, F_CONSTRNC);
379                 }
380                 ndiff = cl[ftype] - n;
381                 if (ndiff != 0)
382                 {
383                     GMX_LOG(mdlog.warning)
384                             .appendTextFormatted("%20s of %6d missing %6d",
385                                                  interaction_function[ftype].longname, n, -ndiff);
386                 }
387                 rest_global -= n;
388                 rest_local -= cl[ftype];
389             }
390         }
391
392         ndiff = rest_local - rest_global;
393         if (ndiff != 0)
394         {
395             GMX_LOG(mdlog.warning).appendTextFormatted("%20s of %6d missing %6d", "exclusions", rest_global, -ndiff);
396         }
397     }
398
399     print_missing_interactions_atoms(mdlog, cr, top_global, &top_local->idef);
400     write_dd_pdb("dd_dump_err", 0, "dump", top_global, cr, -1, x, box);
401
402     std::string errorMessage;
403
404     if (ndiff_tot > 0)
405     {
406         errorMessage =
407                 "One or more interactions were assigned to multiple domains of the domain "
408                 "decompostion. Please report this bug.";
409     }
410     else
411     {
412         errorMessage = gmx::formatString(
413                 "%d of the %d bonded interactions could not be calculated because some atoms "
414                 "involved moved further apart than the multi-body cut-off distance (%g nm) or the "
415                 "two-body cut-off distance (%g nm), see option -rdd, for pairs and tabulated bonds "
416                 "also see option -ddcheck",
417                 -ndiff_tot, cr->dd->nbonded_global, dd_cutoff_multibody(dd), dd_cutoff_twobody(dd));
418     }
419     gmx_fatal_collective(FARGS, cr->mpi_comm_mygroup, MASTER(cr), "%s", errorMessage.c_str());
420 }
421
422 /*! \brief Return global topology molecule information for global atom index \p i_gl */
423 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)
424 {
425     const MolblockIndices* mbi   = rt->mbi.data();
426     int                    start = 0;
427     int                    end   = rt->mbi.size(); /* exclusive */
428     int                    mid;
429
430     /* binary search for molblock_ind */
431     while (TRUE)
432     {
433         mid = (start + end) / 2;
434         if (i_gl >= mbi[mid].a_end)
435         {
436             start = mid + 1;
437         }
438         else if (i_gl < mbi[mid].a_start)
439         {
440             end = mid;
441         }
442         else
443         {
444             break;
445         }
446     }
447
448     *mb = mid;
449     mbi += mid;
450
451     *mt    = mbi->type;
452     *mol   = (i_gl - mbi->a_start) / mbi->natoms_mol;
453     *i_mol = (i_gl - mbi->a_start) - (*mol) * mbi->natoms_mol;
454 }
455
456 /*! \brief Returns the maximum number of exclusions per atom */
457 static int getMaxNumExclusionsPerAtom(const ListOfLists<int>& excls)
458 {
459     int maxNumExcls = 0;
460     for (gmx::index at = 0; at < excls.ssize(); at++)
461     {
462         const auto list     = excls[at];
463         const int  numExcls = list.ssize();
464
465         GMX_RELEASE_ASSERT(numExcls != 1 || list[0] == at,
466                            "With 1 exclusion we expect a self-exclusion");
467
468         maxNumExcls = std::max(maxNumExcls, numExcls);
469     }
470
471     return maxNumExcls;
472 }
473
474 /*! \brief Run the reverse ilist generation and store it in r_il when \p bAssign = TRUE */
475 static int low_make_reverse_ilist(const InteractionLists&  il_mt,
476                                   const t_atom*            atom,
477                                   int*                     count,
478                                   gmx_bool                 bConstr,
479                                   gmx_bool                 bSettle,
480                                   gmx_bool                 bBCheck,
481                                   gmx::ArrayRef<const int> r_index,
482                                   gmx::ArrayRef<int>       r_il,
483                                   gmx_bool                 bLinkToAllAtoms,
484                                   gmx_bool                 bAssign)
485 {
486     int ftype, j, nlink, link;
487     int a;
488     int nint;
489
490     nint = 0;
491     for (ftype = 0; ftype < F_NRE; ftype++)
492     {
493         if ((interaction_function[ftype].flags & (IF_BOND | IF_VSITE))
494             || (bConstr && (ftype == F_CONSTR || ftype == F_CONSTRNC)) || (bSettle && ftype == F_SETTLE))
495         {
496             const bool  bVSite = ((interaction_function[ftype].flags & IF_VSITE) != 0U);
497             const int   nral   = NRAL(ftype);
498             const auto& il     = il_mt[ftype];
499             for (int i = 0; i < il.size(); i += 1 + nral)
500             {
501                 const int* ia = il.iatoms.data() + i;
502                 if (bLinkToAllAtoms)
503                 {
504                     if (bVSite)
505                     {
506                         /* We don't need the virtual sites for the cg-links */
507                         nlink = 0;
508                     }
509                     else
510                     {
511                         nlink = nral;
512                     }
513                 }
514                 else
515                 {
516                     /* Couple to the first atom in the interaction */
517                     nlink = 1;
518                 }
519                 for (link = 0; link < nlink; link++)
520                 {
521                     a = ia[1 + link];
522                     if (bAssign)
523                     {
524                         GMX_ASSERT(!r_il.empty(), "with bAssign not allowed to be empty");
525                         GMX_ASSERT(!r_index.empty(), "with bAssign not allowed to be empty");
526                         r_il[r_index[a] + count[a]]     = (ftype == F_CONSTRNC ? F_CONSTR : ftype);
527                         r_il[r_index[a] + count[a] + 1] = ia[0];
528                         for (j = 1; j < 1 + nral; j++)
529                         {
530                             /* Store the molecular atom number */
531                             r_il[r_index[a] + count[a] + 1 + j] = ia[j];
532                         }
533                     }
534                     if (interaction_function[ftype].flags & IF_VSITE)
535                     {
536                         if (bAssign)
537                         {
538                             /* Add an entry to iatoms for storing
539                              * which of the constructing atoms are
540                              * vsites again.
541                              */
542                             r_il[r_index[a] + count[a] + 2 + nral] = 0;
543                             for (j = 2; j < 1 + nral; j++)
544                             {
545                                 if (atom[ia[j]].ptype == eptVSite)
546                                 {
547                                     r_il[r_index[a] + count[a] + 2 + nral] |= (2 << j);
548                                 }
549                             }
550                         }
551                     }
552                     else
553                     {
554                         /* We do not count vsites since they are always
555                          * uniquely assigned and can be assigned
556                          * to multiple nodes with recursive vsites.
557                          */
558                         if (bBCheck || !(interaction_function[ftype].flags & IF_LIMZERO))
559                         {
560                             nint++;
561                         }
562                     }
563                     count[a] += 2 + nral_rt(ftype);
564                 }
565             }
566         }
567     }
568
569     return nint;
570 }
571
572 /*! \brief Make the reverse ilist: a list of bonded interactions linked to atoms */
573 static int make_reverse_ilist(const InteractionLists& ilist,
574                               const t_atoms*          atoms,
575                               gmx_bool                bConstr,
576                               gmx_bool                bSettle,
577                               gmx_bool                bBCheck,
578                               gmx_bool                bLinkToAllAtoms,
579                               reverse_ilist_t*        ril_mt)
580 {
581     int nat_mt, *count, i, nint_mt;
582
583     /* Count the interactions */
584     nat_mt = atoms->nr;
585     snew(count, nat_mt);
586     low_make_reverse_ilist(ilist, atoms->atom, count, bConstr, bSettle, bBCheck, {}, {},
587                            bLinkToAllAtoms, FALSE);
588
589     ril_mt->index.push_back(0);
590     for (i = 0; i < nat_mt; i++)
591     {
592         ril_mt->index.push_back(ril_mt->index[i] + count[i]);
593         count[i] = 0;
594     }
595     ril_mt->il.resize(ril_mt->index[nat_mt]);
596
597     /* Store the interactions */
598     nint_mt = low_make_reverse_ilist(ilist, atoms->atom, count, bConstr, bSettle, bBCheck,
599                                      ril_mt->index, ril_mt->il, bLinkToAllAtoms, TRUE);
600
601     sfree(count);
602
603     ril_mt->numAtomsInMolecule = atoms->nr;
604
605     return nint_mt;
606 }
607
608 /*! \brief Generate the reverse topology */
609 static gmx_reverse_top_t make_reverse_top(const gmx_mtop_t* mtop,
610                                           gmx_bool          bFE,
611                                           gmx_bool          bConstr,
612                                           gmx_bool          bSettle,
613                                           gmx_bool          bBCheck,
614                                           int*              nint)
615 {
616     gmx_reverse_top_t rt;
617
618     /* Should we include constraints (for SHAKE) in rt? */
619     rt.bConstr = bConstr;
620     rt.bSettle = bSettle;
621     rt.bBCheck = bBCheck;
622
623     rt.bInterAtomicInteractions = mtop->bIntermolecularInteractions;
624     rt.ril_mt.resize(mtop->moltype.size());
625     rt.ril_mt_tot_size = 0;
626     std::vector<int> nint_mt;
627     for (size_t mt = 0; mt < mtop->moltype.size(); mt++)
628     {
629         const gmx_moltype_t& molt = mtop->moltype[mt];
630         if (molt.atoms.nr > 1)
631         {
632             rt.bInterAtomicInteractions = true;
633         }
634
635         /* Make the atom to interaction list for this molecule type */
636         int numberOfInteractions = make_reverse_ilist(
637                 molt.ilist, &molt.atoms, rt.bConstr, rt.bSettle, rt.bBCheck, FALSE, &rt.ril_mt[mt]);
638         nint_mt.push_back(numberOfInteractions);
639
640         rt.ril_mt_tot_size += rt.ril_mt[mt].index[molt.atoms.nr];
641     }
642     if (debug)
643     {
644         fprintf(debug, "The total size of the atom to interaction index is %d integers\n",
645                 rt.ril_mt_tot_size);
646     }
647
648     *nint = 0;
649     for (const gmx_molblock_t& molblock : mtop->molblock)
650     {
651         *nint += molblock.nmol * nint_mt[molblock.type];
652     }
653
654     /* Make an intermolecular reverse top, if necessary */
655     rt.bIntermolecularInteractions = mtop->bIntermolecularInteractions;
656     if (rt.bIntermolecularInteractions)
657     {
658         t_atoms atoms_global;
659
660         atoms_global.nr   = mtop->natoms;
661         atoms_global.atom = nullptr; /* Only used with virtual sites */
662
663         GMX_RELEASE_ASSERT(mtop->intermolecular_ilist,
664                            "We should have an ilist when intermolecular interactions are on");
665
666         *nint += make_reverse_ilist(*mtop->intermolecular_ilist, &atoms_global, rt.bConstr,
667                                     rt.bSettle, rt.bBCheck, FALSE, &rt.ril_intermol);
668     }
669
670     if (bFE && gmx_mtop_bondeds_free_energy(mtop))
671     {
672         rt.ilsort = ilsortFE_UNSORTED;
673     }
674     else
675     {
676         rt.ilsort = ilsortNO_FE;
677     }
678
679     /* Make a molblock index for fast searching */
680     int i = 0;
681     for (size_t mb = 0; mb < mtop->molblock.size(); mb++)
682     {
683         const gmx_molblock_t& molb           = mtop->molblock[mb];
684         const int             numAtomsPerMol = mtop->moltype[molb.type].atoms.nr;
685         MolblockIndices       mbi;
686         mbi.a_start = i;
687         i += molb.nmol * numAtomsPerMol;
688         mbi.a_end      = i;
689         mbi.natoms_mol = numAtomsPerMol;
690         mbi.type       = molb.type;
691         rt.mbi.push_back(mbi);
692     }
693
694     rt.th_work.resize(gmx_omp_nthreads_get(emntDomdec));
695
696     return rt;
697 }
698
699 void dd_make_reverse_top(FILE*              fplog,
700                          gmx_domdec_t*      dd,
701                          const gmx_mtop_t*  mtop,
702                          const gmx_vsite_t* vsite,
703                          const t_inputrec*  ir,
704                          gmx_bool           bBCheck)
705 {
706     if (fplog)
707     {
708         fprintf(fplog, "\nLinking all bonded interactions to atoms\n");
709     }
710
711     /* If normal and/or settle constraints act only within charge groups,
712      * we can store them in the reverse top and simply assign them to domains.
713      * Otherwise we need to assign them to multiple domains and set up
714      * the parallel version constraint algorithm(s).
715      */
716
717     dd->reverse_top = new gmx_reverse_top_t;
718     *dd->reverse_top =
719             make_reverse_top(mtop, ir->efep != efepNO, !dd->comm->systemInfo.haveSplitConstraints,
720                              !dd->comm->systemInfo.haveSplitSettles, bBCheck, &dd->nbonded_global);
721
722     dd->haveExclusions = false;
723     for (const gmx_molblock_t& molb : mtop->molblock)
724     {
725         const int maxNumExclusionsPerAtom = getMaxNumExclusionsPerAtom(mtop->moltype[molb.type].excls);
726         // We checked above that max 1 exclusion means only self exclusions
727         if (maxNumExclusionsPerAtom > 1)
728         {
729             dd->haveExclusions = true;
730         }
731     }
732
733     if (vsite && vsite->numInterUpdategroupVsites > 0)
734     {
735         if (fplog)
736         {
737             fprintf(fplog,
738                     "There are %d inter update-group virtual sites,\n"
739                     "will an extra communication step for selected coordinates and forces\n",
740                     vsite->numInterUpdategroupVsites);
741         }
742         init_domdec_vsites(dd, vsite->numInterUpdategroupVsites);
743     }
744
745     if (dd->comm->systemInfo.haveSplitConstraints || dd->comm->systemInfo.haveSplitSettles)
746     {
747         init_domdec_constraints(dd, mtop);
748     }
749     if (fplog)
750     {
751         fprintf(fplog, "\n");
752     }
753 }
754
755 /*! \brief Store a vsite interaction at the end of \p il
756  *
757  * This routine is very similar to add_ifunc, but vsites interactions
758  * have more work to do than other kinds of interactions, and the
759  * complex way nral (and thus vector contents) depends on ftype
760  * confuses static analysis tools unless we fuse the vsite
761  * atom-indexing organization code with the ifunc-adding code, so that
762  * they can see that nral is the same value. */
763 static inline void add_ifunc_for_vsites(t_iatom*           tiatoms,
764                                         const gmx_ga2la_t& ga2la,
765                                         int                nral,
766                                         gmx_bool           bHomeA,
767                                         int                a,
768                                         int                a_gl,
769                                         int                a_mol,
770                                         const t_iatom*     iatoms,
771                                         t_ilist*           il)
772 {
773     t_iatom* liatoms;
774
775     if (il->nr + 1 + nral > il->nalloc)
776     {
777         il->nalloc = over_alloc_large(il->nr + 1 + nral);
778         srenew(il->iatoms, il->nalloc);
779     }
780     liatoms = il->iatoms + il->nr;
781     il->nr += 1 + nral;
782
783     /* Copy the type */
784     tiatoms[0] = iatoms[0];
785
786     if (bHomeA)
787     {
788         /* We know the local index of the first atom */
789         tiatoms[1] = a;
790     }
791     else
792     {
793         /* Convert later in make_local_vsites */
794         tiatoms[1] = -a_gl - 1;
795     }
796
797     for (int k = 2; k < 1 + nral; k++)
798     {
799         int ak_gl = a_gl + iatoms[k] - a_mol;
800         if (const int* homeIndex = ga2la.findHome(ak_gl))
801         {
802             tiatoms[k] = *homeIndex;
803         }
804         else
805         {
806             /* Copy the global index, convert later in make_local_vsites */
807             tiatoms[k] = -(ak_gl + 1);
808         }
809         // Note that ga2la_get_home always sets the third parameter if
810         // it returns TRUE
811     }
812     for (int k = 0; k < 1 + nral; k++)
813     {
814         liatoms[k] = tiatoms[k];
815     }
816 }
817
818 /*! \brief Store a bonded interaction at the end of \p il */
819 static inline void add_ifunc(int nral, const t_iatom* tiatoms, t_ilist* il)
820 {
821     t_iatom* liatoms;
822     int      k;
823
824     if (il->nr + 1 + nral > il->nalloc)
825     {
826         il->nalloc = over_alloc_large(il->nr + 1 + nral);
827         srenew(il->iatoms, il->nalloc);
828     }
829     liatoms = il->iatoms + il->nr;
830     for (k = 0; k <= nral; k++)
831     {
832         liatoms[k] = tiatoms[k];
833     }
834     il->nr += 1 + nral;
835 }
836
837 /*! \brief Store a position restraint in idef and iatoms, complex because the parameters are different for each entry */
838 static void add_posres(int                   mol,
839                        int                   a_mol,
840                        int                   numAtomsInMolecule,
841                        const gmx_molblock_t* molb,
842                        t_iatom*              iatoms,
843                        const t_iparams*      ip_in,
844                        t_idef*               idef)
845 {
846     int        n, a_molb;
847     t_iparams* ip;
848
849     /* This position restraint has not been added yet,
850      * so it's index is the current number of position restraints.
851      */
852     n = idef->il[F_POSRES].nr / 2;
853     if (n + 1 > idef->iparams_posres_nalloc)
854     {
855         idef->iparams_posres_nalloc = over_alloc_dd(n + 1);
856         srenew(idef->iparams_posres, idef->iparams_posres_nalloc);
857     }
858     ip = &idef->iparams_posres[n];
859     /* Copy the force constants */
860     *ip = ip_in[iatoms[0]];
861
862     /* Get the position restraint coordinates from the molblock */
863     a_molb = mol * numAtomsInMolecule + a_mol;
864     GMX_ASSERT(a_molb < ssize(molb->posres_xA),
865                "We need a sufficient number of position restraint coordinates");
866     ip->posres.pos0A[XX] = molb->posres_xA[a_molb][XX];
867     ip->posres.pos0A[YY] = molb->posres_xA[a_molb][YY];
868     ip->posres.pos0A[ZZ] = molb->posres_xA[a_molb][ZZ];
869     if (!molb->posres_xB.empty())
870     {
871         ip->posres.pos0B[XX] = molb->posres_xB[a_molb][XX];
872         ip->posres.pos0B[YY] = molb->posres_xB[a_molb][YY];
873         ip->posres.pos0B[ZZ] = molb->posres_xB[a_molb][ZZ];
874     }
875     else
876     {
877         ip->posres.pos0B[XX] = ip->posres.pos0A[XX];
878         ip->posres.pos0B[YY] = ip->posres.pos0A[YY];
879         ip->posres.pos0B[ZZ] = ip->posres.pos0A[ZZ];
880     }
881     /* Set the parameter index for idef->iparams_posre */
882     iatoms[0] = n;
883 }
884
885 /*! \brief Store a flat-bottomed position restraint in idef and iatoms, complex because the parameters are different for each entry */
886 static void add_fbposres(int                   mol,
887                          int                   a_mol,
888                          int                   numAtomsInMolecule,
889                          const gmx_molblock_t* molb,
890                          t_iatom*              iatoms,
891                          const t_iparams*      ip_in,
892                          t_idef*               idef)
893 {
894     int        n, a_molb;
895     t_iparams* ip;
896
897     /* This flat-bottom position restraint has not been added yet,
898      * so it's index is the current number of position restraints.
899      */
900     n = idef->il[F_FBPOSRES].nr / 2;
901     if (n + 1 > idef->iparams_fbposres_nalloc)
902     {
903         idef->iparams_fbposres_nalloc = over_alloc_dd(n + 1);
904         srenew(idef->iparams_fbposres, idef->iparams_fbposres_nalloc);
905     }
906     ip = &idef->iparams_fbposres[n];
907     /* Copy the force constants */
908     *ip = ip_in[iatoms[0]];
909
910     /* Get the position restraint coordinats from the molblock */
911     a_molb = mol * numAtomsInMolecule + a_mol;
912     GMX_ASSERT(a_molb < ssize(molb->posres_xA),
913                "We need a sufficient number of position restraint coordinates");
914     /* Take reference positions from A position of normal posres */
915     ip->fbposres.pos0[XX] = molb->posres_xA[a_molb][XX];
916     ip->fbposres.pos0[YY] = molb->posres_xA[a_molb][YY];
917     ip->fbposres.pos0[ZZ] = molb->posres_xA[a_molb][ZZ];
918
919     /* Note: no B-type for flat-bottom posres */
920
921     /* Set the parameter index for idef->iparams_posre */
922     iatoms[0] = n;
923 }
924
925 /*! \brief Store a virtual site interaction, complex because of PBC and recursion */
926 static void add_vsite(const gmx_ga2la_t&       ga2la,
927                       gmx::ArrayRef<const int> index,
928                       gmx::ArrayRef<const int> rtil,
929                       int                      ftype,
930                       int                      nral,
931                       gmx_bool                 bHomeA,
932                       int                      a,
933                       int                      a_gl,
934                       int                      a_mol,
935                       const t_iatom*           iatoms,
936                       t_idef*                  idef)
937 {
938     int     k;
939     t_iatom tiatoms[1 + MAXATOMLIST];
940     int     j, ftype_r, nral_r;
941
942     /* Add this interaction to the local topology */
943     add_ifunc_for_vsites(tiatoms, ga2la, nral, bHomeA, a, a_gl, a_mol, iatoms, &idef->il[ftype]);
944
945     if (iatoms[1 + nral])
946     {
947         /* Check for recursion */
948         for (k = 2; k < 1 + nral; k++)
949         {
950             if ((iatoms[1 + nral] & (2 << k)) && (tiatoms[k] < 0))
951             {
952                 /* This construction atoms is a vsite and not a home atom */
953                 if (gmx_debug_at)
954                 {
955                     fprintf(debug, "Constructing atom %d of vsite atom %d is a vsite and non-home\n",
956                             iatoms[k] + 1, a_mol + 1);
957                 }
958                 /* Find the vsite construction */
959
960                 /* Check all interactions assigned to this atom */
961                 j = index[iatoms[k]];
962                 while (j < index[iatoms[k] + 1])
963                 {
964                     ftype_r = rtil[j++];
965                     nral_r  = NRAL(ftype_r);
966                     if (interaction_function[ftype_r].flags & IF_VSITE)
967                     {
968                         /* Add this vsite (recursion) */
969                         add_vsite(ga2la, index, rtil, ftype_r, nral_r, FALSE, -1,
970                                   a_gl + iatoms[k] - iatoms[1], iatoms[k], rtil.data() + j, idef);
971                     }
972                     j += 1 + nral_rt(ftype_r);
973                 }
974             }
975         }
976     }
977 }
978
979 /*! \brief Returns the squared distance between atoms \p i and \p j */
980 static real dd_dist2(t_pbc* pbc_null, const rvec* x, const int i, int j)
981 {
982     rvec dx;
983
984     if (pbc_null)
985     {
986         pbc_dx_aiuc(pbc_null, x[i], x[j], dx);
987     }
988     else
989     {
990         rvec_sub(x[i], x[j], dx);
991     }
992
993     return norm2(dx);
994 }
995
996 /*! \brief Append t_idef structures 1 to nsrc in src to *dest */
997 static void combine_idef(t_idef* dest, gmx::ArrayRef<const thread_work_t> src)
998 {
999     int ftype;
1000
1001     for (ftype = 0; ftype < F_NRE; ftype++)
1002     {
1003         int n = 0;
1004         for (gmx::index s = 1; s < src.ssize(); s++)
1005         {
1006             n += src[s].idef.il[ftype].nr;
1007         }
1008         if (n > 0)
1009         {
1010             t_ilist* ild;
1011
1012             ild = &dest->il[ftype];
1013
1014             if (ild->nr + n > ild->nalloc)
1015             {
1016                 ild->nalloc = over_alloc_large(ild->nr + n);
1017                 srenew(ild->iatoms, ild->nalloc);
1018             }
1019
1020             for (gmx::index s = 1; s < src.ssize(); s++)
1021             {
1022                 const t_ilist& ils = src[s].idef.il[ftype];
1023
1024                 for (int i = 0; i < ils.nr; i++)
1025                 {
1026                     ild->iatoms[ild->nr + i] = ils.iatoms[i];
1027                 }
1028
1029                 ild->nr += ils.nr;
1030             }
1031
1032             /* Position restraints need an additional treatment */
1033             if (ftype == F_POSRES || ftype == F_FBPOSRES)
1034             {
1035                 int nposres = dest->il[ftype].nr / 2;
1036                 // TODO: Simplify this code using std::vector
1037                 t_iparams*& iparams_dest =
1038                         (ftype == F_POSRES ? dest->iparams_posres : dest->iparams_fbposres);
1039                 int& posres_nalloc = (ftype == F_POSRES ? dest->iparams_posres_nalloc
1040                                                         : dest->iparams_fbposres_nalloc);
1041                 if (nposres > posres_nalloc)
1042                 {
1043                     posres_nalloc = over_alloc_large(nposres);
1044                     srenew(iparams_dest, posres_nalloc);
1045                 }
1046
1047                 /* Set nposres to the number of original position restraints in dest */
1048                 for (gmx::index s = 1; s < src.ssize(); s++)
1049                 {
1050                     nposres -= src[s].idef.il[ftype].nr / 2;
1051                 }
1052
1053                 for (gmx::index s = 1; s < src.ssize(); s++)
1054                 {
1055                     const t_iparams* iparams_src = (ftype == F_POSRES ? src[s].idef.iparams_posres
1056                                                                       : src[s].idef.iparams_fbposres);
1057
1058                     for (int i = 0; i < src[s].idef.il[ftype].nr / 2; i++)
1059                     {
1060                         /* Correct the index into iparams_posres */
1061                         dest->il[ftype].iatoms[nposres * 2] = nposres;
1062                         /* Copy the position restraint force parameters */
1063                         iparams_dest[nposres] = iparams_src[i];
1064                         nposres++;
1065                     }
1066                 }
1067             }
1068         }
1069     }
1070 }
1071
1072 /*! \brief Check and when available assign bonded interactions for local atom i
1073  */
1074 static inline void check_assign_interactions_atom(int                       i,
1075                                                   int                       i_gl,
1076                                                   int                       mol,
1077                                                   int                       i_mol,
1078                                                   int                       numAtomsInMolecule,
1079                                                   gmx::ArrayRef<const int>  index,
1080                                                   gmx::ArrayRef<const int>  rtil,
1081                                                   gmx_bool                  bInterMolInteractions,
1082                                                   int                       ind_start,
1083                                                   int                       ind_end,
1084                                                   const gmx_domdec_t*       dd,
1085                                                   const gmx_domdec_zones_t* zones,
1086                                                   const gmx_molblock_t*     molb,
1087                                                   gmx_bool                  bRCheckMB,
1088                                                   const ivec                rcheck,
1089                                                   gmx_bool                  bRCheck2B,
1090                                                   real                      rc2,
1091                                                   t_pbc*                    pbc_null,
1092                                                   rvec*                     cg_cm,
1093                                                   const t_iparams*          ip_in,
1094                                                   t_idef*                   idef,
1095                                                   int                       iz,
1096                                                   gmx_bool                  bBCheck,
1097                                                   int*                      nbonded_local)
1098 {
1099     gmx::ArrayRef<const DDPairInteractionRanges> iZones = zones->iZones;
1100
1101     int j = ind_start;
1102     while (j < ind_end)
1103     {
1104         t_iatom tiatoms[1 + MAXATOMLIST];
1105
1106         const int ftype  = rtil[j++];
1107         auto      iatoms = gmx::constArrayRefFromArray(rtil.data() + j, rtil.size() - j);
1108         const int nral   = NRAL(ftype);
1109         if (interaction_function[ftype].flags & IF_VSITE)
1110         {
1111             assert(!bInterMolInteractions);
1112             /* The vsite construction goes where the vsite itself is */
1113             if (iz == 0)
1114             {
1115                 add_vsite(*dd->ga2la, index, rtil, ftype, nral, TRUE, i, i_gl, i_mol, iatoms.data(), idef);
1116             }
1117             j += 1 + nral + 2;
1118         }
1119         else
1120         {
1121             gmx_bool bUse;
1122
1123             /* Copy the type */
1124             tiatoms[0] = iatoms[0];
1125
1126             if (nral == 1)
1127             {
1128                 assert(!bInterMolInteractions);
1129                 /* Assign single-body interactions to the home zone */
1130                 if (iz == 0)
1131                 {
1132                     bUse       = TRUE;
1133                     tiatoms[1] = i;
1134                     if (ftype == F_POSRES)
1135                     {
1136                         add_posres(mol, i_mol, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1137                     }
1138                     else if (ftype == F_FBPOSRES)
1139                     {
1140                         add_fbposres(mol, i_mol, numAtomsInMolecule, molb, tiatoms, ip_in, idef);
1141                     }
1142                 }
1143                 else
1144                 {
1145                     bUse = FALSE;
1146                 }
1147             }
1148             else if (nral == 2)
1149             {
1150                 /* This is a two-body interaction, we can assign
1151                  * analogous to the non-bonded assignments.
1152                  */
1153                 int k_gl;
1154
1155                 if (!bInterMolInteractions)
1156                 {
1157                     /* Get the global index using the offset in the molecule */
1158                     k_gl = i_gl + iatoms[2] - i_mol;
1159                 }
1160                 else
1161                 {
1162                     k_gl = iatoms[2];
1163                 }
1164                 if (const auto* entry = dd->ga2la->find(k_gl))
1165                 {
1166                     int kz = entry->cell;
1167                     if (kz >= zones->n)
1168                     {
1169                         kz -= zones->n;
1170                     }
1171                     /* Check zone interaction assignments */
1172                     bUse = ((iz < iZones.ssize() && iz <= kz && iZones[iz].jZoneRange.isInRange(kz))
1173                             || (kz < iZones.ssize() && iz > kz && iZones[kz].jZoneRange.isInRange(iz)));
1174                     if (bUse)
1175                     {
1176                         GMX_ASSERT(ftype != F_CONSTR || (iz == 0 && kz == 0),
1177                                    "Constraint assigned here should only involve home atoms");
1178
1179                         tiatoms[1] = i;
1180                         tiatoms[2] = entry->la;
1181                         /* If necessary check the cgcm distance */
1182                         if (bRCheck2B && dd_dist2(pbc_null, cg_cm, tiatoms[1], tiatoms[2]) >= rc2)
1183                         {
1184                             bUse = FALSE;
1185                         }
1186                     }
1187                 }
1188                 else
1189                 {
1190                     bUse = false;
1191                 }
1192             }
1193             else
1194             {
1195                 /* Assign this multi-body bonded interaction to
1196                  * the local node if we have all the atoms involved
1197                  * (local or communicated) and the minimum zone shift
1198                  * in each dimension is zero, for dimensions
1199                  * with 2 DD cells an extra check may be necessary.
1200                  */
1201                 ivec k_zero, k_plus;
1202                 int  k;
1203
1204                 bUse = TRUE;
1205                 clear_ivec(k_zero);
1206                 clear_ivec(k_plus);
1207                 for (k = 1; k <= nral && bUse; k++)
1208                 {
1209                     int k_gl;
1210                     if (!bInterMolInteractions)
1211                     {
1212                         /* Get the global index using the offset in the molecule */
1213                         k_gl = i_gl + iatoms[k] - i_mol;
1214                     }
1215                     else
1216                     {
1217                         k_gl = iatoms[k];
1218                     }
1219                     const auto* entry = dd->ga2la->find(k_gl);
1220                     if (entry == nullptr || entry->cell >= zones->n)
1221                     {
1222                         /* We do not have this atom of this interaction
1223                          * locally, or it comes from more than one cell
1224                          * away.
1225                          */
1226                         bUse = FALSE;
1227                     }
1228                     else
1229                     {
1230                         int d;
1231
1232                         tiatoms[k] = entry->la;
1233                         for (d = 0; d < DIM; d++)
1234                         {
1235                             if (zones->shift[entry->cell][d] == 0)
1236                             {
1237                                 k_zero[d] = k;
1238                             }
1239                             else
1240                             {
1241                                 k_plus[d] = k;
1242                             }
1243                         }
1244                     }
1245                 }
1246                 bUse = (bUse && (k_zero[XX] != 0) && (k_zero[YY] != 0) && (k_zero[ZZ] != 0));
1247                 if (bRCheckMB)
1248                 {
1249                     int d;
1250
1251                     for (d = 0; (d < DIM && bUse); d++)
1252                     {
1253                         /* Check if the cg_cm distance falls within
1254                          * the cut-off to avoid possible multiple
1255                          * assignments of bonded interactions.
1256                          */
1257                         if (rcheck[d] && k_plus[d]
1258                             && dd_dist2(pbc_null, cg_cm, tiatoms[k_zero[d]], tiatoms[k_plus[d]]) >= rc2)
1259                         {
1260                             bUse = FALSE;
1261                         }
1262                     }
1263                 }
1264             }
1265             if (bUse)
1266             {
1267                 /* Add this interaction to the local topology */
1268                 add_ifunc(nral, tiatoms, &idef->il[ftype]);
1269                 /* Sum so we can check in global_stat
1270                  * if we have everything.
1271                  */
1272                 if (bBCheck || !(interaction_function[ftype].flags & IF_LIMZERO))
1273                 {
1274                     (*nbonded_local)++;
1275                 }
1276             }
1277             j += 1 + nral;
1278         }
1279     }
1280 }
1281
1282 /*! \brief This function looks up and assigns bonded interactions for zone iz.
1283  *
1284  * With thread parallelizing each thread acts on a different atom range:
1285  * at_start to at_end.
1286  */
1287 static int make_bondeds_zone(gmx_domdec_t*                      dd,
1288                              const gmx_domdec_zones_t*          zones,
1289                              const std::vector<gmx_molblock_t>& molb,
1290                              gmx_bool                           bRCheckMB,
1291                              ivec                               rcheck,
1292                              gmx_bool                           bRCheck2B,
1293                              real                               rc2,
1294                              t_pbc*                             pbc_null,
1295                              rvec*                              cg_cm,
1296                              const t_iparams*                   ip_in,
1297                              t_idef*                            idef,
1298                              int                                izone,
1299                              const gmx::Range<int>&             atomRange)
1300 {
1301     int                mb, mt, mol, i_mol;
1302     gmx_bool           bBCheck;
1303     gmx_reverse_top_t* rt;
1304     int                nbonded_local;
1305
1306     rt = dd->reverse_top;
1307
1308     bBCheck = rt->bBCheck;
1309
1310     nbonded_local = 0;
1311
1312     for (int i : atomRange)
1313     {
1314         /* Get the global atom number */
1315         const int i_gl = dd->globalAtomIndices[i];
1316         global_atomnr_to_moltype_ind(rt, i_gl, &mb, &mt, &mol, &i_mol);
1317         /* Check all intramolecular interactions assigned to this atom */
1318         gmx::ArrayRef<const int>     index = rt->ril_mt[mt].index;
1319         gmx::ArrayRef<const t_iatom> rtil  = rt->ril_mt[mt].il;
1320
1321         check_assign_interactions_atom(i, i_gl, mol, i_mol, rt->ril_mt[mt].numAtomsInMolecule,
1322                                        index, rtil, FALSE, index[i_mol], index[i_mol + 1], dd,
1323                                        zones, &molb[mb], bRCheckMB, rcheck, bRCheck2B, rc2,
1324                                        pbc_null, cg_cm, ip_in, idef, izone, bBCheck, &nbonded_local);
1325
1326
1327         if (rt->bIntermolecularInteractions)
1328         {
1329             /* Check all intermolecular interactions assigned to this atom */
1330             index = rt->ril_intermol.index;
1331             rtil  = rt->ril_intermol.il;
1332
1333             check_assign_interactions_atom(i, i_gl, mol, i_mol, rt->ril_mt[mt].numAtomsInMolecule,
1334                                            index, rtil, TRUE, index[i_gl], index[i_gl + 1], dd, zones,
1335                                            &molb[mb], bRCheckMB, rcheck, bRCheck2B, rc2, pbc_null,
1336                                            cg_cm, ip_in, idef, izone, bBCheck, &nbonded_local);
1337         }
1338     }
1339
1340     return nbonded_local;
1341 }
1342
1343 /*! \brief Set the exclusion data for i-zone \p iz */
1344 static void make_exclusions_zone(gmx_domdec_t*                     dd,
1345                                  gmx_domdec_zones_t*               zones,
1346                                  const std::vector<gmx_moltype_t>& moltype,
1347                                  const int*                        cginfo,
1348                                  ListOfLists<int>*                 lexcls,
1349                                  int                               iz,
1350                                  int                               at_start,
1351                                  int                               at_end,
1352                                  const gmx::ArrayRef<const int>    intermolecularExclusionGroup)
1353 {
1354     const gmx_ga2la_t& ga2la = *dd->ga2la;
1355
1356     const auto& jAtomRange = zones->iZones[iz].jAtomRange;
1357
1358     const gmx::index oldNumLists = lexcls->ssize();
1359
1360     std::vector<int> exclusionsForAtom;
1361     for (int at = at_start; at < at_end; at++)
1362     {
1363         exclusionsForAtom.clear();
1364
1365         if (GET_CGINFO_EXCL_INTER(cginfo[at]))
1366         {
1367             int a_gl, mb, mt, mol, a_mol;
1368
1369             /* Copy the exclusions from the global top */
1370             a_gl = dd->globalAtomIndices[at];
1371             global_atomnr_to_moltype_ind(dd->reverse_top, a_gl, &mb, &mt, &mol, &a_mol);
1372             const auto excls = moltype[mt].excls[a_mol];
1373             for (const int aj_mol : excls)
1374             {
1375                 if (const auto* jEntry = ga2la.find(a_gl + aj_mol - a_mol))
1376                 {
1377                     /* This check is not necessary, but it can reduce
1378                      * the number of exclusions in the list, which in turn
1379                      * can speed up the pair list construction a bit.
1380                      */
1381                     if (jAtomRange.isInRange(jEntry->la))
1382                     {
1383                         exclusionsForAtom.push_back(jEntry->la);
1384                     }
1385                 }
1386             }
1387         }
1388
1389         bool isExcludedAtom = !intermolecularExclusionGroup.empty()
1390                               && std::find(intermolecularExclusionGroup.begin(),
1391                                            intermolecularExclusionGroup.end(), dd->globalAtomIndices[at])
1392                                          != intermolecularExclusionGroup.end();
1393
1394         if (isExcludedAtom)
1395         {
1396             for (int qmAtomGlobalIndex : intermolecularExclusionGroup)
1397             {
1398                 if (const auto* entry = dd->ga2la->find(qmAtomGlobalIndex))
1399                 {
1400                     exclusionsForAtom.push_back(entry->la);
1401                 }
1402             }
1403         }
1404
1405         /* Append the exclusions for this atom to the topology */
1406         lexcls->pushBack(exclusionsForAtom);
1407     }
1408
1409     GMX_RELEASE_ASSERT(
1410             lexcls->ssize() - oldNumLists == at_end - at_start,
1411             "The number of exclusion list should match the number of atoms in the range");
1412 }
1413
1414 /*! \brief Clear a t_idef struct */
1415 static void clear_idef(t_idef* idef)
1416 {
1417     int ftype;
1418
1419     /* Clear the counts */
1420     for (ftype = 0; ftype < F_NRE; ftype++)
1421     {
1422         idef->il[ftype].nr = 0;
1423     }
1424 }
1425
1426 /*! \brief Generate and store all required local bonded interactions in \p idef and local exclusions in \p lexcls */
1427 static int make_local_bondeds_excls(gmx_domdec_t*       dd,
1428                                     gmx_domdec_zones_t* zones,
1429                                     const gmx_mtop_t*   mtop,
1430                                     const int*          cginfo,
1431                                     gmx_bool            bRCheckMB,
1432                                     ivec                rcheck,
1433                                     gmx_bool            bRCheck2B,
1434                                     real                rc,
1435                                     t_pbc*              pbc_null,
1436                                     rvec*               cg_cm,
1437                                     t_idef*             idef,
1438                                     ListOfLists<int>*   lexcls,
1439                                     int*                excl_count)
1440 {
1441     int                nzone_bondeds;
1442     int                cg0, cg1;
1443     real               rc2;
1444     int                nbonded_local;
1445     gmx_reverse_top_t* rt;
1446
1447     if (dd->reverse_top->bInterAtomicInteractions)
1448     {
1449         nzone_bondeds = zones->n;
1450     }
1451     else
1452     {
1453         /* Only single charge group (or atom) molecules, so interactions don't
1454          * cross zone boundaries and we only need to assign in the home zone.
1455          */
1456         nzone_bondeds = 1;
1457     }
1458
1459     /* We only use exclusions from i-zones to i- and j-zones */
1460     const int numIZonesForExclusions = (dd->haveExclusions ? zones->iZones.size() : 0);
1461
1462     rt = dd->reverse_top;
1463
1464     rc2 = rc * rc;
1465
1466     /* Clear the counts */
1467     clear_idef(idef);
1468     nbonded_local = 0;
1469
1470     lexcls->clear();
1471     *excl_count = 0;
1472
1473     for (int izone = 0; izone < nzone_bondeds; izone++)
1474     {
1475         cg0 = zones->cg_range[izone];
1476         cg1 = zones->cg_range[izone + 1];
1477
1478         const int numThreads = rt->th_work.size();
1479 #pragma omp parallel for num_threads(numThreads) schedule(static)
1480         for (int thread = 0; thread < numThreads; thread++)
1481         {
1482             try
1483             {
1484                 int     cg0t, cg1t;
1485                 t_idef* idef_t;
1486
1487                 cg0t = cg0 + ((cg1 - cg0) * thread) / numThreads;
1488                 cg1t = cg0 + ((cg1 - cg0) * (thread + 1)) / numThreads;
1489
1490                 if (thread == 0)
1491                 {
1492                     idef_t = idef;
1493                 }
1494                 else
1495                 {
1496                     idef_t = &rt->th_work[thread].idef;
1497                     clear_idef(idef_t);
1498                 }
1499
1500                 rt->th_work[thread].nbonded = make_bondeds_zone(
1501                         dd, zones, mtop->molblock, bRCheckMB, rcheck, bRCheck2B, rc2, pbc_null,
1502                         cg_cm, idef->iparams, idef_t, izone, gmx::Range<int>(cg0t, cg1t));
1503
1504                 if (izone < numIZonesForExclusions)
1505                 {
1506                     ListOfLists<int>* excl_t;
1507                     if (thread == 0)
1508                     {
1509                         // Thread 0 stores exclusions directly in the final storage
1510                         excl_t = lexcls;
1511                     }
1512                     else
1513                     {
1514                         // Threads > 0 store in temporary storage, starting at list index 0
1515                         excl_t = &rt->th_work[thread].excl;
1516                         excl_t->clear();
1517                     }
1518
1519                     /* No charge groups and no distance check required */
1520                     make_exclusions_zone(dd, zones, mtop->moltype, cginfo, excl_t, izone, cg0t,
1521                                          cg1t, mtop->intermolecularExclusionGroup);
1522                 }
1523             }
1524             GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1525         }
1526
1527         if (rt->th_work.size() > 1)
1528         {
1529             combine_idef(idef, rt->th_work);
1530         }
1531
1532         for (const thread_work_t& th_work : rt->th_work)
1533         {
1534             nbonded_local += th_work.nbonded;
1535         }
1536
1537         if (izone < numIZonesForExclusions)
1538         {
1539             for (std::size_t th = 1; th < rt->th_work.size(); th++)
1540             {
1541                 lexcls->appendListOfLists(rt->th_work[th].excl);
1542             }
1543             for (const thread_work_t& th_work : rt->th_work)
1544             {
1545                 *excl_count += th_work.excl_count;
1546             }
1547         }
1548     }
1549
1550     if (debug)
1551     {
1552         fprintf(debug, "We have %d exclusions, check count %d\n", lexcls->numElements(), *excl_count);
1553     }
1554
1555     return nbonded_local;
1556 }
1557
1558 void dd_make_local_top(gmx_domdec_t*       dd,
1559                        gmx_domdec_zones_t* zones,
1560                        int                 npbcdim,
1561                        matrix              box,
1562                        rvec                cellsize_min,
1563                        const ivec          npulse,
1564                        t_forcerec*         fr,
1565                        rvec*               cgcm_or_x,
1566                        const gmx_mtop_t&   mtop,
1567                        gmx_localtop_t*     ltop)
1568 {
1569     gmx_bool bRCheckMB, bRCheck2B;
1570     real     rc = -1;
1571     ivec     rcheck;
1572     int      d, nexcl;
1573     t_pbc    pbc, *pbc_null = nullptr;
1574
1575     if (debug)
1576     {
1577         fprintf(debug, "Making local topology\n");
1578     }
1579
1580     bRCheckMB = FALSE;
1581     bRCheck2B = FALSE;
1582
1583     if (dd->reverse_top->bInterAtomicInteractions)
1584     {
1585         /* We need to check to which cell bondeds should be assigned */
1586         rc = dd_cutoff_twobody(dd);
1587         if (debug)
1588         {
1589             fprintf(debug, "Two-body bonded cut-off distance is %g\n", rc);
1590         }
1591
1592         /* Should we check cg_cm distances when assigning bonded interactions? */
1593         for (d = 0; d < DIM; d++)
1594         {
1595             rcheck[d] = FALSE;
1596             /* Only need to check for dimensions where the part of the box
1597              * that is not communicated is smaller than the cut-off.
1598              */
1599             if (d < npbcdim && dd->numCells[d] > 1
1600                 && (dd->numCells[d] - npulse[d]) * cellsize_min[d] < 2 * rc)
1601             {
1602                 if (dd->numCells[d] == 2)
1603                 {
1604                     rcheck[d] = TRUE;
1605                     bRCheckMB = TRUE;
1606                 }
1607                 /* Check for interactions between two atoms,
1608                  * where we can allow interactions up to the cut-off,
1609                  * instead of up to the smallest cell dimension.
1610                  */
1611                 bRCheck2B = TRUE;
1612             }
1613             if (debug)
1614             {
1615                 fprintf(debug, "dim %d cellmin %f bonded rcheck[%d] = %d, bRCheck2B = %s\n", d,
1616                         cellsize_min[d], d, rcheck[d], gmx::boolToString(bRCheck2B));
1617             }
1618         }
1619         if (bRCheckMB || bRCheck2B)
1620         {
1621             if (fr->bMolPBC)
1622             {
1623                 pbc_null = set_pbc_dd(&pbc, fr->pbcType, dd->numCells, TRUE, box);
1624             }
1625             else
1626             {
1627                 pbc_null = nullptr;
1628             }
1629         }
1630     }
1631
1632     dd->nbonded_local = make_local_bondeds_excls(dd, zones, &mtop, fr->cginfo.data(), bRCheckMB,
1633                                                  rcheck, bRCheck2B, rc, pbc_null, cgcm_or_x,
1634                                                  &ltop->idef, &ltop->excls, &nexcl);
1635
1636     /* The ilist is not sorted yet,
1637      * we can only do this when we have the charge arrays.
1638      */
1639     ltop->idef.ilsort = ilsortUNKNOWN;
1640
1641     ltop->atomtypes = mtop.atomtypes;
1642 }
1643
1644 void dd_sort_local_top(gmx_domdec_t* dd, const t_mdatoms* mdatoms, gmx_localtop_t* ltop)
1645 {
1646     if (dd->reverse_top->ilsort == ilsortNO_FE)
1647     {
1648         ltop->idef.ilsort = ilsortNO_FE;
1649     }
1650     else
1651     {
1652         gmx_sort_ilist_fe(&ltop->idef, mdatoms->chargeA, mdatoms->chargeB);
1653     }
1654 }
1655
1656 void dd_init_local_top(const gmx_mtop_t& top_global, gmx_localtop_t* top)
1657 {
1658     /* TODO: Get rid of the const casts below, e.g. by using a reference */
1659     top->idef.ntypes     = top_global.ffparams.numTypes();
1660     top->idef.atnr       = top_global.ffparams.atnr;
1661     top->idef.functype   = const_cast<t_functype*>(top_global.ffparams.functype.data());
1662     top->idef.iparams    = const_cast<t_iparams*>(top_global.ffparams.iparams.data());
1663     top->idef.fudgeQQ    = top_global.ffparams.fudgeQQ;
1664     top->idef.cmap_grid  = new gmx_cmap_t;
1665     *top->idef.cmap_grid = top_global.ffparams.cmap_grid;
1666
1667     top->idef.ilsort        = ilsortUNKNOWN;
1668     top->useInDomainDecomp_ = true;
1669 }
1670
1671 void dd_init_local_state(gmx_domdec_t* dd, const t_state* state_global, t_state* state_local)
1672 {
1673     int buf[NITEM_DD_INIT_LOCAL_STATE];
1674
1675     if (DDMASTER(dd))
1676     {
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;
1682     }
1683     dd_bcast(dd, NITEM_DD_INIT_LOCAL_STATE * sizeof(int), buf);
1684
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];
1688 }
1689
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)
1692 {
1693     int      k;
1694     gmx_bool bFound;
1695
1696     bFound = FALSE;
1697     for (k = link->index[cg_gl]; k < link->index[cg_gl + 1]; k++)
1698     {
1699         GMX_RELEASE_ASSERT(link->a, "Inconsistent NULL pointer while making charge-group links");
1700         if (link->a[k] == cg_gl_j)
1701         {
1702             bFound = TRUE;
1703         }
1704     }
1705     if (!bFound)
1706     {
1707         GMX_RELEASE_ASSERT(link->a || link->index[cg_gl + 1] + 1 > link->nalloc_a,
1708                            "Inconsistent allocation of link");
1709         /* Add this charge group link */
1710         if (link->index[cg_gl + 1] + 1 > link->nalloc_a)
1711         {
1712             link->nalloc_a = over_alloc_large(link->index[cg_gl + 1] + 1);
1713             srenew(link->a, link->nalloc_a);
1714         }
1715         link->a[link->index[cg_gl + 1]] = cg_gl_j;
1716         link->index[cg_gl + 1]++;
1717     }
1718 }
1719
1720 t_blocka* makeBondedLinks(const gmx_mtop_t& mtop, gmx::ArrayRef<cginfo_mb_t> cginfo_mb)
1721 {
1722     t_blocka*    link;
1723     cginfo_mb_t* cgi_mb;
1724
1725     /* For each atom make a list of other atoms in the system
1726      * that a linked to it via bonded interactions
1727      * which are also stored in reverse_top.
1728      */
1729
1730     reverse_ilist_t ril_intermol;
1731     if (mtop.bIntermolecularInteractions)
1732     {
1733         t_atoms atoms;
1734
1735         atoms.nr   = mtop.natoms;
1736         atoms.atom = nullptr;
1737
1738         GMX_RELEASE_ASSERT(mtop.intermolecular_ilist,
1739                            "We should have an ilist when intermolecular interactions are on");
1740
1741         make_reverse_ilist(*mtop.intermolecular_ilist, &atoms, FALSE, FALSE, FALSE, TRUE, &ril_intermol);
1742     }
1743
1744     snew(link, 1);
1745     snew(link->index, mtop.natoms + 1);
1746     link->nalloc_a = 0;
1747     link->a        = nullptr;
1748
1749     link->index[0] = 0;
1750     int cg_offset  = 0;
1751     int ncgi       = 0;
1752     for (size_t mb = 0; mb < mtop.molblock.size(); mb++)
1753     {
1754         const gmx_molblock_t& molb = mtop.molblock[mb];
1755         if (molb.nmol == 0)
1756         {
1757             continue;
1758         }
1759         const gmx_moltype_t& molt = mtop.moltype[molb.type];
1760         /* Make a reverse ilist in which the interactions are linked
1761          * to all atoms, not only the first atom as in gmx_reverse_top.
1762          * The constraints are discarded here.
1763          */
1764         reverse_ilist_t ril;
1765         make_reverse_ilist(molt.ilist, &molt.atoms, FALSE, FALSE, FALSE, TRUE, &ril);
1766
1767         cgi_mb = &cginfo_mb[mb];
1768
1769         int mol;
1770         for (mol = 0; mol < (mtop.bIntermolecularInteractions ? molb.nmol : 1); mol++)
1771         {
1772             for (int a = 0; a < molt.atoms.nr; a++)
1773             {
1774                 int cg_gl              = cg_offset + a;
1775                 link->index[cg_gl + 1] = link->index[cg_gl];
1776                 int i                  = ril.index[a];
1777                 while (i < ril.index[a + 1])
1778                 {
1779                     int ftype = ril.il[i++];
1780                     int nral  = NRAL(ftype);
1781                     /* Skip the ifunc index */
1782                     i++;
1783                     for (int j = 0; j < nral; j++)
1784                     {
1785                         int aj = ril.il[i + j];
1786                         if (aj != a)
1787                         {
1788                             check_link(link, cg_gl, cg_offset + aj);
1789                         }
1790                     }
1791                     i += nral_rt(ftype);
1792                 }
1793
1794                 if (mtop.bIntermolecularInteractions)
1795                 {
1796                     int i = ril_intermol.index[cg_gl];
1797                     while (i < ril_intermol.index[cg_gl + 1])
1798                     {
1799                         int ftype = ril_intermol.il[i++];
1800                         int nral  = NRAL(ftype);
1801                         /* Skip the ifunc index */
1802                         i++;
1803                         for (int j = 0; j < nral; j++)
1804                         {
1805                             /* Here we assume we have no charge groups;
1806                              * this has been checked above.
1807                              */
1808                             int aj = ril_intermol.il[i + j];
1809                             check_link(link, cg_gl, aj);
1810                         }
1811                         i += nral_rt(ftype);
1812                     }
1813                 }
1814                 if (link->index[cg_gl + 1] - link->index[cg_gl] > 0)
1815                 {
1816                     SET_CGINFO_BOND_INTER(cgi_mb->cginfo[a]);
1817                     ncgi++;
1818                 }
1819             }
1820
1821             cg_offset += molt.atoms.nr;
1822         }
1823         int nlink_mol = link->index[cg_offset] - link->index[cg_offset - molt.atoms.nr];
1824
1825         if (debug)
1826         {
1827             fprintf(debug, "molecule type '%s' %d atoms has %d atom links through bonded interac.\n",
1828                     *molt.name, molt.atoms.nr, nlink_mol);
1829         }
1830
1831         if (molb.nmol > mol)
1832         {
1833             /* Copy the data for the rest of the molecules in this block */
1834             link->nalloc_a += (molb.nmol - mol) * nlink_mol;
1835             srenew(link->a, link->nalloc_a);
1836             for (; mol < molb.nmol; mol++)
1837             {
1838                 for (int a = 0; a < molt.atoms.nr; a++)
1839                 {
1840                     int cg_gl              = cg_offset + a;
1841                     link->index[cg_gl + 1] = link->index[cg_gl + 1 - molt.atoms.nr] + nlink_mol;
1842                     for (int j = link->index[cg_gl]; j < link->index[cg_gl + 1]; j++)
1843                     {
1844                         link->a[j] = link->a[j - nlink_mol] + molt.atoms.nr;
1845                     }
1846                     if (link->index[cg_gl + 1] - link->index[cg_gl] > 0
1847                         && cg_gl - cgi_mb->cg_start < cgi_mb->cg_mod)
1848                     {
1849                         SET_CGINFO_BOND_INTER(cgi_mb->cginfo[cg_gl - cgi_mb->cg_start]);
1850                         ncgi++;
1851                     }
1852                 }
1853                 cg_offset += molt.atoms.nr;
1854             }
1855         }
1856     }
1857
1858     if (debug)
1859     {
1860         fprintf(debug, "Of the %d atoms %d are linked via bonded interactions\n", mtop.natoms, ncgi);
1861     }
1862
1863     return link;
1864 }
1865
1866 typedef struct
1867 {
1868     real r2;
1869     int  ftype;
1870     int  a1;
1871     int  a2;
1872 } bonded_distance_t;
1873
1874 /*! \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 */
1875 static void update_max_bonded_distance(real r2, int ftype, int a1, int a2, bonded_distance_t* bd)
1876 {
1877     if (r2 > bd->r2)
1878     {
1879         bd->r2    = r2;
1880         bd->ftype = ftype;
1881         bd->a1    = a1;
1882         bd->a2    = a2;
1883     }
1884 }
1885
1886 /*! \brief Set the distance, function type and atom indices for the longest distance between charge-groups of molecule type \p molt for two-body and multi-body bonded interactions */
1887 static void bonded_cg_distance_mol(const gmx_moltype_t* molt,
1888                                    gmx_bool             bBCheck,
1889                                    gmx_bool             bExcl,
1890                                    rvec*                cg_cm,
1891                                    bonded_distance_t*   bd_2b,
1892                                    bonded_distance_t*   bd_mb)
1893 {
1894     for (int ftype = 0; ftype < F_NRE; ftype++)
1895     {
1896         if (dd_check_ftype(ftype, bBCheck, FALSE, FALSE))
1897         {
1898             const auto& il   = molt->ilist[ftype];
1899             int         nral = NRAL(ftype);
1900             if (nral > 1)
1901             {
1902                 for (int i = 0; i < il.size(); i += 1 + nral)
1903                 {
1904                     for (int ai = 0; ai < nral; ai++)
1905                     {
1906                         int atomI = il.iatoms[i + 1 + ai];
1907                         for (int aj = ai + 1; aj < nral; aj++)
1908                         {
1909                             int atomJ = il.iatoms[i + 1 + aj];
1910                             if (atomI != atomJ)
1911                             {
1912                                 real rij2 = distance2(cg_cm[atomI], cg_cm[atomJ]);
1913
1914                                 update_max_bonded_distance(rij2, ftype, atomI, atomJ,
1915                                                            (nral == 2) ? bd_2b : bd_mb);
1916                             }
1917                         }
1918                     }
1919                 }
1920             }
1921         }
1922     }
1923     if (bExcl)
1924     {
1925         const auto& excls = molt->excls;
1926         for (gmx::index ai = 0; ai < excls.ssize(); ai++)
1927         {
1928             for (const int aj : excls[ai])
1929             {
1930                 if (ai != aj)
1931                 {
1932                     real rij2 = distance2(cg_cm[ai], cg_cm[aj]);
1933
1934                     /* There is no function type for exclusions, use -1 */
1935                     update_max_bonded_distance(rij2, -1, ai, aj, bd_2b);
1936                 }
1937             }
1938         }
1939     }
1940 }
1941
1942 /*! \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 */
1943 static void bonded_distance_intermol(const InteractionLists& ilists_intermol,
1944                                      gmx_bool                bBCheck,
1945                                      const rvec*             x,
1946                                      PbcType                 pbcType,
1947                                      const matrix            box,
1948                                      bonded_distance_t*      bd_2b,
1949                                      bonded_distance_t*      bd_mb)
1950 {
1951     t_pbc pbc;
1952
1953     set_pbc(&pbc, pbcType, box);
1954
1955     for (int ftype = 0; ftype < F_NRE; ftype++)
1956     {
1957         if (dd_check_ftype(ftype, bBCheck, FALSE, FALSE))
1958         {
1959             const auto& il   = ilists_intermol[ftype];
1960             int         nral = NRAL(ftype);
1961
1962             /* No nral>1 check here, since intermol interactions always
1963              * have nral>=2 (and the code is also correct for nral=1).
1964              */
1965             for (int i = 0; i < il.size(); i += 1 + nral)
1966             {
1967                 for (int ai = 0; ai < nral; ai++)
1968                 {
1969                     int atom_i = il.iatoms[i + 1 + ai];
1970
1971                     for (int aj = ai + 1; aj < nral; aj++)
1972                     {
1973                         rvec dx;
1974                         real rij2;
1975
1976                         int atom_j = il.iatoms[i + 1 + aj];
1977
1978                         pbc_dx(&pbc, x[atom_i], x[atom_j], dx);
1979
1980                         rij2 = norm2(dx);
1981
1982                         update_max_bonded_distance(rij2, ftype, atom_i, atom_j, (nral == 2) ? bd_2b : bd_mb);
1983                     }
1984                 }
1985             }
1986         }
1987     }
1988 }
1989
1990 //! Returns whether \p molt has at least one virtual site
1991 static bool moltypeHasVsite(const gmx_moltype_t& molt)
1992 {
1993     bool hasVsite = false;
1994     for (int i = 0; i < F_NRE; i++)
1995     {
1996         if ((interaction_function[i].flags & IF_VSITE) && molt.ilist[i].size() > 0)
1997         {
1998             hasVsite = true;
1999         }
2000     }
2001
2002     return hasVsite;
2003 }
2004
2005 //! Returns coordinates not broken over PBC for a molecule
2006 static void getWholeMoleculeCoordinates(const gmx_moltype_t*  molt,
2007                                         const gmx_ffparams_t* ffparams,
2008                                         PbcType               pbcType,
2009                                         t_graph*              graph,
2010                                         const matrix          box,
2011                                         const rvec*           x,
2012                                         rvec*                 xs)
2013 {
2014     int n, i;
2015
2016     if (pbcType != PbcType::No)
2017     {
2018         mk_mshift(nullptr, graph, pbcType, box, x);
2019
2020         shift_x(graph, box, x, xs);
2021         /* By doing an extra mk_mshift the molecules that are broken
2022          * because they were e.g. imported from another software
2023          * will be made whole again. Such are the healing powers
2024          * of GROMACS.
2025          */
2026         mk_mshift(nullptr, graph, pbcType, box, xs);
2027     }
2028     else
2029     {
2030         /* We copy the coordinates so the original coordinates remain
2031          * unchanged, just to be 100% sure that we do not affect
2032          * binary reproducibility of simulations.
2033          */
2034         n = molt->atoms.nr;
2035         for (i = 0; i < n; i++)
2036         {
2037             copy_rvec(x[i], xs[i]);
2038         }
2039     }
2040
2041     if (moltypeHasVsite(*molt))
2042     {
2043         /* Convert to old, deprecated format */
2044         t_ilist ilist[F_NRE];
2045         for (int ftype = 0; ftype < F_NRE; ftype++)
2046         {
2047             if (interaction_function[ftype].flags & IF_VSITE)
2048             {
2049                 ilist[ftype].nr     = molt->ilist[ftype].size();
2050                 ilist[ftype].iatoms = const_cast<int*>(molt->ilist[ftype].iatoms.data());
2051             }
2052         }
2053
2054         construct_vsites(nullptr, xs, 0.0, nullptr, ffparams->iparams.data(), ilist, PbcType::No,
2055                          TRUE, nullptr, nullptr);
2056     }
2057 }
2058
2059 void dd_bonded_cg_distance(const gmx::MDLogger& mdlog,
2060                            const gmx_mtop_t*    mtop,
2061                            const t_inputrec*    ir,
2062                            const rvec*          x,
2063                            const matrix         box,
2064                            gmx_bool             bBCheck,
2065                            real*                r_2b,
2066                            real*                r_mb)
2067 {
2068     gmx_bool          bExclRequired;
2069     int               at_offset;
2070     t_graph           graph;
2071     rvec*             xs;
2072     bonded_distance_t bd_2b = { 0, -1, -1, -1 };
2073     bonded_distance_t bd_mb = { 0, -1, -1, -1 };
2074
2075     bExclRequired = inputrecExclForces(ir);
2076
2077     *r_2b     = 0;
2078     *r_mb     = 0;
2079     at_offset = 0;
2080     for (const gmx_molblock_t& molb : mtop->molblock)
2081     {
2082         const gmx_moltype_t& molt = mtop->moltype[molb.type];
2083         if (molt.atoms.nr == 1 || molb.nmol == 0)
2084         {
2085             at_offset += molb.nmol * molt.atoms.nr;
2086         }
2087         else
2088         {
2089             if (ir->pbcType != PbcType::No)
2090             {
2091                 mk_graph_moltype(molt, &graph);
2092             }
2093
2094             snew(xs, molt.atoms.nr);
2095             for (int mol = 0; mol < molb.nmol; mol++)
2096             {
2097                 getWholeMoleculeCoordinates(&molt, &mtop->ffparams, ir->pbcType, &graph, box,
2098                                             x + at_offset, xs);
2099
2100                 bonded_distance_t bd_mol_2b = { 0, -1, -1, -1 };
2101                 bonded_distance_t bd_mol_mb = { 0, -1, -1, -1 };
2102
2103                 bonded_cg_distance_mol(&molt, bBCheck, bExclRequired, xs, &bd_mol_2b, &bd_mol_mb);
2104
2105                 /* Process the mol data adding the atom index offset */
2106                 update_max_bonded_distance(bd_mol_2b.r2, bd_mol_2b.ftype, at_offset + bd_mol_2b.a1,
2107                                            at_offset + bd_mol_2b.a2, &bd_2b);
2108                 update_max_bonded_distance(bd_mol_mb.r2, bd_mol_mb.ftype, at_offset + bd_mol_mb.a1,
2109                                            at_offset + bd_mol_mb.a2, &bd_mb);
2110
2111                 at_offset += molt.atoms.nr;
2112             }
2113             sfree(xs);
2114             if (ir->pbcType != PbcType::No)
2115             {
2116                 done_graph(&graph);
2117             }
2118         }
2119     }
2120
2121     if (mtop->bIntermolecularInteractions)
2122     {
2123         GMX_RELEASE_ASSERT(mtop->intermolecular_ilist,
2124                            "We should have an ilist when intermolecular interactions are on");
2125
2126         bonded_distance_intermol(*mtop->intermolecular_ilist, bBCheck, x, ir->pbcType, box, &bd_2b, &bd_mb);
2127     }
2128
2129     *r_2b = sqrt(bd_2b.r2);
2130     *r_mb = sqrt(bd_mb.r2);
2131
2132     if (*r_2b > 0 || *r_mb > 0)
2133     {
2134         GMX_LOG(mdlog.info).appendText("Initial maximum distances in bonded interactions:");
2135         if (*r_2b > 0)
2136         {
2137             GMX_LOG(mdlog.info)
2138                     .appendTextFormatted(
2139                             "    two-body bonded interactions: %5.3f nm, %s, atoms %d %d", *r_2b,
2140                             (bd_2b.ftype >= 0) ? interaction_function[bd_2b.ftype].longname : "Exclusion",
2141                             bd_2b.a1 + 1, bd_2b.a2 + 1);
2142         }
2143         if (*r_mb > 0)
2144         {
2145             GMX_LOG(mdlog.info)
2146                     .appendTextFormatted(
2147                             "  multi-body bonded interactions: %5.3f nm, %s, atoms %d %d", *r_mb,
2148                             interaction_function[bd_mb.ftype].longname, bd_mb.a1 + 1, bd_mb.a2 + 1);
2149         }
2150     }
2151 }