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