Move domdec/partition into gmx namespace; minor cleanup
[alexxy/gromacs.git] / src / gromacs / domdec / partition.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  *
37  * \brief This file defines functions for mdrun to call to make a new
38  * domain decomposition, and check it.
39  *
40  * \author Berk Hess <hess@kth.se>
41  * \ingroup module_domdec
42  */
43
44 #include "gmxpre.h"
45
46 #include "partition.h"
47
48 #include "config.h"
49
50 #include <cassert>
51 #include <cstdio>
52
53 #include <algorithm>
54
55 #include "gromacs/domdec/collect.h"
56 #include "gromacs/domdec/dlb.h"
57 #include "gromacs/domdec/dlbtiming.h"
58 #include "gromacs/domdec/domdec.h"
59 #include "gromacs/domdec/domdec_network.h"
60 #include "gromacs/domdec/ga2la.h"
61 #include "gromacs/domdec/localatomsetmanager.h"
62 #include "gromacs/domdec/mdsetup.h"
63 #include "gromacs/domdec/nsgrid.h"
64 #include "gromacs/ewald/pme_pp.h"
65 #include "gromacs/gmxlib/network.h"
66 #include "gromacs/gmxlib/nrnb.h"
67 #include "gromacs/imd/imd.h"
68 #include "gromacs/math/functions.h"
69 #include "gromacs/math/vec.h"
70 #include "gromacs/mdlib/forcerec.h"
71 #include "gromacs/mdlib/gmx_omp_nthreads.h"
72 #include "gromacs/mdlib/mdatoms.h"
73 #include "gromacs/mdlib/vsite.h"
74 #include "gromacs/mdtypes/commrec.h"
75 #include "gromacs/mdtypes/forcerec.h"
76 #include "gromacs/mdtypes/inputrec.h"
77 #include "gromacs/mdtypes/md_enums.h"
78 #include "gromacs/mdtypes/mdatom.h"
79 #include "gromacs/mdtypes/nblist.h"
80 #include "gromacs/mdtypes/state.h"
81 #include "gromacs/nbnxm/nbnxm.h"
82 #include "gromacs/pulling/pull.h"
83 #include "gromacs/timing/wallcycle.h"
84 #include "gromacs/topology/mtop_util.h"
85 #include "gromacs/topology/topology.h"
86 #include "gromacs/utility/cstringutil.h"
87 #include "gromacs/utility/fatalerror.h"
88 #include "gromacs/utility/logger.h"
89 #include "gromacs/utility/real.h"
90 #include "gromacs/utility/smalloc.h"
91 #include "gromacs/utility/strconvert.h"
92 #include "gromacs/utility/stringstream.h"
93 #include "gromacs/utility/stringutil.h"
94 #include "gromacs/utility/textwriter.h"
95
96 #include "box.h"
97 #include "cellsizes.h"
98 #include "distribute.h"
99 #include "domdec_constraints.h"
100 #include "domdec_internal.h"
101 #include "domdec_vsite.h"
102 #include "dump.h"
103 #include "redistribute.h"
104 #include "utility.h"
105
106 /*! \brief Turn on DLB when the load imbalance causes this amount of total loss.
107  *
108  * There is a bit of overhead with DLB and it's difficult to achieve
109  * a load imbalance of less than 2% with DLB.
110  */
111 #define DD_PERF_LOSS_DLB_ON 0.02
112
113 //! Warn about imbalance due to PP or PP/PME load imbalance at this loss.
114 #define DD_PERF_LOSS_WARN 0.05
115
116
117 //! Debug helper printing a DD zone
118 static void print_ddzone(FILE* fp, int d, int i, int j, gmx_ddzone_t* zone)
119 {
120     fprintf(fp,
121             "zone d0 %d d1 %d d2 %d  min0 %6.3f max1 %6.3f mch0 %6.3f mch1 %6.3f p1_0 %6.3f p1_1 "
122             "%6.3f\n",
123             d,
124             i,
125             j,
126             zone->min0,
127             zone->max1,
128             zone->mch0,
129             zone->mch0,
130             zone->p1_0,
131             zone->p1_1);
132 }
133
134 /*! \brief Using the home grid size as input in cell_ns_x0 and cell_ns_x1
135  * takes the extremes over all home and remote zones in the halo
136  * and returns the results in cell_ns_x0 and cell_ns_x1.
137  * Note: only used with the group cut-off scheme.
138  */
139 static void dd_move_cellx(gmx_domdec_t* dd, const gmx_ddbox_t* ddbox, rvec cell_ns_x0, rvec cell_ns_x1)
140 {
141     constexpr int      c_ddZoneCommMaxNumZones = 5;
142     gmx_ddzone_t       buf_s[c_ddZoneCommMaxNumZones];
143     gmx_ddzone_t       buf_r[c_ddZoneCommMaxNumZones];
144     gmx_ddzone_t       buf_e[c_ddZoneCommMaxNumZones];
145     gmx_domdec_comm_t* comm = dd->comm;
146
147     rvec extr_s[2];
148     rvec extr_r[2];
149     for (int d = 1; d < dd->ndim; d++)
150     {
151         int           dim = dd->dim[d];
152         gmx_ddzone_t& zp  = (d == 1) ? comm->zone_d1[0] : comm->zone_d2[0][0];
153
154         /* Copy the base sizes of the home zone */
155         zp.min0    = cell_ns_x0[dim];
156         zp.max1    = cell_ns_x1[dim];
157         zp.min1    = cell_ns_x1[dim];
158         zp.mch0    = cell_ns_x0[dim];
159         zp.mch1    = cell_ns_x1[dim];
160         zp.p1_0    = cell_ns_x0[dim];
161         zp.p1_1    = cell_ns_x1[dim];
162         zp.dataSet = 1;
163     }
164
165     gmx::ArrayRef<DDCellsizesWithDlb> cellsizes = comm->cellsizesWithDlb;
166
167     /* Loop backward over the dimensions and aggregate the extremes
168      * of the cell sizes.
169      */
170     for (int d = dd->ndim - 2; d >= 0; d--)
171     {
172         const int  dim      = dd->dim[d];
173         const bool applyPbc = (dim < ddbox->npbcdim);
174
175         /* Use an rvec to store two reals */
176         extr_s[d][0] = cellsizes[d + 1].fracLower;
177         extr_s[d][1] = cellsizes[d + 1].fracUpper;
178         extr_s[d][2] = cellsizes[d + 1].fracUpper;
179
180         int pos = 0;
181         GMX_ASSERT(pos < c_ddZoneCommMaxNumZones, "The buffers should be sufficiently large");
182         /* Store the extremes in the backward sending buffer,
183          * so they get updated separately from the forward communication.
184          */
185         for (int d1 = d; d1 < dd->ndim - 1; d1++)
186         {
187             gmx_ddzone_t& buf = buf_s[pos];
188
189             /* We invert the order to be able to use the same loop for buf_e */
190             buf.min0 = extr_s[d1][1];
191             buf.max1 = extr_s[d1][0];
192             buf.min1 = extr_s[d1][2];
193             buf.mch0 = 0;
194             buf.mch1 = 0;
195             /* Store the cell corner of the dimension we communicate along */
196             buf.p1_0    = comm->cell_x0[dim];
197             buf.p1_1    = 0;
198             buf.dataSet = 1;
199             pos++;
200         }
201
202         buf_s[pos] = (dd->ndim == 2) ? comm->zone_d1[0] : comm->zone_d2[0][0];
203         pos++;
204
205         if (dd->ndim == 3 && d == 0)
206         {
207             buf_s[pos] = comm->zone_d2[0][1];
208             pos++;
209             buf_s[pos] = comm->zone_d1[0];
210             pos++;
211         }
212
213         /* We only need to communicate the extremes
214          * in the forward direction
215          */
216         int numPulses = comm->cd[d].numPulses();
217         int numPulsesMin;
218         if (applyPbc)
219         {
220             /* Take the minimum to avoid double communication */
221             numPulsesMin = std::min(numPulses, dd->numCells[dim] - 1 - numPulses);
222         }
223         else
224         {
225             /* Without PBC we should really not communicate over
226              * the boundaries, but implementing that complicates
227              * the communication setup and therefore we simply
228              * do all communication, but ignore some data.
229              */
230             numPulsesMin = numPulses;
231         }
232         for (int pulse = 0; pulse < numPulsesMin; pulse++)
233         {
234             /* Communicate the extremes forward */
235             bool receiveValidData = (applyPbc || dd->ci[dim] > 0);
236
237             int numElements = dd->ndim - d - 1;
238             ddSendrecv(dd, d, dddirForward, extr_s + d, numElements, extr_r + d, numElements);
239
240             if (receiveValidData)
241             {
242                 for (int d1 = d; d1 < dd->ndim - 1; d1++)
243                 {
244                     extr_s[d1][0] = std::max(extr_s[d1][0], extr_r[d1][0]);
245                     extr_s[d1][1] = std::min(extr_s[d1][1], extr_r[d1][1]);
246                     extr_s[d1][2] = std::min(extr_s[d1][2], extr_r[d1][2]);
247                 }
248             }
249         }
250
251         const int numElementsInBuffer = pos;
252         for (int pulse = 0; pulse < numPulses; pulse++)
253         {
254             /* Communicate all the zone information backward */
255             bool receiveValidData = (applyPbc || dd->ci[dim] < dd->numCells[dim] - 1);
256
257             static_assert(
258                     sizeof(gmx_ddzone_t) == c_ddzoneNumReals * sizeof(real),
259                     "Here we expect gmx_ddzone_t to consist of c_ddzoneNumReals reals (only)");
260
261             int numReals = numElementsInBuffer * c_ddzoneNumReals;
262             ddSendrecv(dd,
263                        d,
264                        dddirBackward,
265                        gmx::arrayRefFromArray(&buf_s[0].min0, numReals),
266                        gmx::arrayRefFromArray(&buf_r[0].min0, numReals));
267
268             rvec dh = { 0 };
269             if (pulse > 0)
270             {
271                 for (int d1 = d + 1; d1 < dd->ndim; d1++)
272                 {
273                     /* Determine the decrease of maximum required
274                      * communication height along d1 due to the distance along d,
275                      * this avoids a lot of useless atom communication.
276                      */
277                     real dist_d = comm->cell_x1[dim] - buf_r[0].p1_0;
278
279                     real c;
280                     if (ddbox->tric_dir[dim])
281                     {
282                         /* c is the off-diagonal coupling between the cell planes
283                          * along directions d and d1.
284                          */
285                         c = ddbox->v[dim][dd->dim[d1]][dim];
286                     }
287                     else
288                     {
289                         c = 0;
290                     }
291                     real det = (1 + c * c) * gmx::square(comm->systemInfo.cutoff) - dist_d * dist_d;
292                     if (det > 0)
293                     {
294                         dh[d1] = comm->systemInfo.cutoff - (c * dist_d + std::sqrt(det)) / (1 + c * c);
295                     }
296                     else
297                     {
298                         /* A negative value signals out of range */
299                         dh[d1] = -1;
300                     }
301                 }
302             }
303
304             /* Accumulate the extremes over all pulses */
305             for (int i = 0; i < numElementsInBuffer; i++)
306             {
307                 if (pulse == 0)
308                 {
309                     buf_e[i] = buf_r[i];
310                 }
311                 else
312                 {
313                     if (receiveValidData)
314                     {
315                         buf_e[i].min0 = std::min(buf_e[i].min0, buf_r[i].min0);
316                         buf_e[i].max1 = std::max(buf_e[i].max1, buf_r[i].max1);
317                         buf_e[i].min1 = std::min(buf_e[i].min1, buf_r[i].min1);
318                     }
319
320                     int d1;
321                     if (dd->ndim == 3 && d == 0 && i == numElementsInBuffer - 1)
322                     {
323                         d1 = 1;
324                     }
325                     else
326                     {
327                         d1 = d + 1;
328                     }
329                     if (receiveValidData && dh[d1] >= 0)
330                     {
331                         buf_e[i].mch0 = std::max(buf_e[i].mch0, buf_r[i].mch0 - dh[d1]);
332                         buf_e[i].mch1 = std::max(buf_e[i].mch1, buf_r[i].mch1 - dh[d1]);
333                     }
334                 }
335                 /* Copy the received buffer to the send buffer,
336                  * to pass the data through with the next pulse.
337                  */
338                 buf_s[i] = buf_r[i];
339             }
340             if (((applyPbc || dd->ci[dim] + numPulses < dd->numCells[dim]) && pulse == numPulses - 1)
341                 || (!applyPbc && dd->ci[dim] + 1 + pulse == dd->numCells[dim] - 1))
342             {
343                 /* Store the extremes */
344                 int pos = 0;
345
346                 for (int d1 = d; d1 < dd->ndim - 1; d1++)
347                 {
348                     extr_s[d1][1] = std::min(extr_s[d1][1], buf_e[pos].min0);
349                     extr_s[d1][0] = std::max(extr_s[d1][0], buf_e[pos].max1);
350                     extr_s[d1][2] = std::min(extr_s[d1][2], buf_e[pos].min1);
351                     pos++;
352                 }
353
354                 if (d == 1 || (d == 0 && dd->ndim == 3))
355                 {
356                     for (int i = d; i < 2; i++)
357                     {
358                         comm->zone_d2[1 - d][i] = buf_e[pos];
359                         pos++;
360                     }
361                 }
362                 if (d == 0)
363                 {
364                     comm->zone_d1[1] = buf_e[pos];
365                     pos++;
366                 }
367             }
368             else
369             {
370                 if (d == 1 || (d == 0 && dd->ndim == 3))
371                 {
372                     for (int i = d; i < 2; i++)
373                     {
374                         comm->zone_d2[1 - d][i].dataSet = 0;
375                     }
376                 }
377                 if (d == 0)
378                 {
379                     comm->zone_d1[1].dataSet = 0;
380                 }
381             }
382         }
383     }
384
385     if (dd->ndim >= 2)
386     {
387         int dim = dd->dim[1];
388         for (int i = 0; i < 2; i++)
389         {
390             if (comm->zone_d1[i].dataSet != 0)
391             {
392                 if (debug)
393                 {
394                     print_ddzone(debug, 1, i, 0, &comm->zone_d1[i]);
395                 }
396                 cell_ns_x0[dim] = std::min(cell_ns_x0[dim], comm->zone_d1[i].min0);
397                 cell_ns_x1[dim] = std::max(cell_ns_x1[dim], comm->zone_d1[i].max1);
398             }
399         }
400     }
401     if (dd->ndim >= 3)
402     {
403         int dim = dd->dim[2];
404         for (int i = 0; i < 2; i++)
405         {
406             for (int j = 0; j < 2; j++)
407             {
408                 if (comm->zone_d2[i][j].dataSet != 0)
409                 {
410                     if (debug)
411                     {
412                         print_ddzone(debug, 2, i, j, &comm->zone_d2[i][j]);
413                     }
414                     cell_ns_x0[dim] = std::min(cell_ns_x0[dim], comm->zone_d2[i][j].min0);
415                     cell_ns_x1[dim] = std::max(cell_ns_x1[dim], comm->zone_d2[i][j].max1);
416                 }
417             }
418         }
419     }
420     for (int d = 1; d < dd->ndim; d++)
421     {
422         cellsizes[d].fracLowerMax = extr_s[d - 1][0];
423         cellsizes[d].fracUpperMin = extr_s[d - 1][1];
424         if (debug)
425         {
426             fprintf(debug,
427                     "Cell fraction d %d, max0 %f, min1 %f\n",
428                     d,
429                     cellsizes[d].fracLowerMax,
430                     cellsizes[d].fracUpperMin);
431         }
432     }
433 }
434
435 //! Sets the charge-group zones to be equal to the home zone.
436 static void set_zones_ncg_home(gmx_domdec_t* dd)
437 {
438     gmx_domdec_zones_t* zones;
439     int                 i;
440
441     zones = &dd->comm->zones;
442
443     zones->cg_range[0] = 0;
444     for (i = 1; i < zones->n + 1; i++)
445     {
446         zones->cg_range[i] = dd->ncg_home;
447     }
448     /* zone_ncg1[0] should always be equal to ncg_home */
449     dd->comm->zone_ncg1[0] = dd->ncg_home;
450 }
451
452 //! Restore atom groups for the charge groups.
453 static void restoreAtomGroups(gmx_domdec_t* dd, const t_state* state)
454 {
455     gmx::ArrayRef<const int> atomGroupsState = state->cg_gl;
456
457     std::vector<int>& globalAtomGroupIndices = dd->globalAtomGroupIndices;
458
459     globalAtomGroupIndices.resize(atomGroupsState.size());
460
461     /* Copy back the global charge group indices from state
462      * and rebuild the local charge group to atom index.
463      */
464     for (gmx::index i = 0; i < atomGroupsState.ssize(); i++)
465     {
466         globalAtomGroupIndices[i] = atomGroupsState[i];
467     }
468
469     dd->ncg_home = atomGroupsState.size();
470     dd->comm->atomRanges.setEnd(DDAtomRanges::Type::Home, atomGroupsState.ssize());
471
472     set_zones_ncg_home(dd);
473 }
474
475 //! Sets the cginfo structures.
476 static void dd_set_cginfo(gmx::ArrayRef<const int> index_gl, int cg0, int cg1, t_forcerec* fr)
477 {
478     if (fr != nullptr)
479     {
480         gmx::ArrayRef<cginfo_mb_t> cginfo_mb = fr->cginfo_mb;
481         gmx::ArrayRef<int>         cginfo    = fr->cginfo;
482
483         for (int cg = cg0; cg < cg1; cg++)
484         {
485             cginfo[cg] = ddcginfo(cginfo_mb, index_gl[cg]);
486         }
487     }
488 }
489
490 //! Makes the mappings between global and local atom indices during DD repartioning.
491 static void make_dd_indices(gmx_domdec_t* dd, const int atomStart)
492 {
493     const int                numZones               = dd->comm->zones.n;
494     gmx::ArrayRef<const int> zone2cg                = dd->comm->zones.cg_range;
495     gmx::ArrayRef<const int> zone_ncg1              = dd->comm->zone_ncg1;
496     gmx::ArrayRef<const int> globalAtomGroupIndices = dd->globalAtomGroupIndices;
497
498     std::vector<int>& globalAtomIndices = dd->globalAtomIndices;
499     gmx_ga2la_t&      ga2la             = *dd->ga2la;
500
501     if (zone2cg[1] != dd->ncg_home)
502     {
503         gmx_incons("dd->ncg_zone is not up to date");
504     }
505
506     /* Make the local to global and global to local atom index */
507     int a = atomStart;
508     globalAtomIndices.resize(a);
509     for (int zone = 0; zone < numZones; zone++)
510     {
511         int cg0;
512         if (zone == 0)
513         {
514             cg0 = atomStart;
515         }
516         else
517         {
518             cg0 = zone2cg[zone];
519         }
520         int cg1    = zone2cg[zone + 1];
521         int cg1_p1 = cg0 + zone_ncg1[zone];
522
523         for (int cg = cg0; cg < cg1; cg++)
524         {
525             int zone1 = zone;
526             if (cg >= cg1_p1)
527             {
528                 /* Signal that this cg is from more than one pulse away */
529                 zone1 += numZones;
530             }
531             int cg_gl = globalAtomGroupIndices[cg];
532             globalAtomIndices.push_back(cg_gl);
533             ga2la.insert(cg_gl, { a, zone1 });
534             a++;
535         }
536     }
537 }
538
539 //! Checks whether global and local atom indices are consistent.
540 static void check_index_consistency(const gmx_domdec_t* dd, int natoms_sys, const char* where)
541 {
542     int nerr = 0;
543
544     const int numAtomsInZones = dd->comm->atomRanges.end(DDAtomRanges::Type::Zones);
545
546     if (dd->comm->ddSettings.DD_debug > 1)
547     {
548         std::vector<int> have(natoms_sys);
549         for (int a = 0; a < numAtomsInZones; a++)
550         {
551             int globalAtomIndex = dd->globalAtomIndices[a];
552             if (have[globalAtomIndex] > 0)
553             {
554                 fprintf(stderr,
555                         "DD rank %d: global atom %d occurs twice: index %d and %d\n",
556                         dd->rank,
557                         globalAtomIndex + 1,
558                         have[globalAtomIndex],
559                         a + 1);
560             }
561             else
562             {
563                 have[globalAtomIndex] = a + 1;
564             }
565         }
566     }
567
568     std::vector<int> have(numAtomsInZones);
569
570     int ngl = 0;
571     for (int i = 0; i < natoms_sys; i++)
572     {
573         if (const auto entry = dd->ga2la->find(i))
574         {
575             const int a = entry->la;
576             if (a >= numAtomsInZones)
577             {
578                 fprintf(stderr,
579                         "DD rank %d: global atom %d marked as local atom %d, which is larger than "
580                         "nat_tot (%d)\n",
581                         dd->rank,
582                         i + 1,
583                         a + 1,
584                         numAtomsInZones);
585                 nerr++;
586             }
587             else
588             {
589                 have[a] = 1;
590                 if (dd->globalAtomIndices[a] != i)
591                 {
592                     fprintf(stderr,
593                             "DD rank %d: global atom %d marked as local atom %d, which has global "
594                             "atom index %d\n",
595                             dd->rank,
596                             i + 1,
597                             a + 1,
598                             dd->globalAtomIndices[a] + 1);
599                     nerr++;
600                 }
601             }
602             ngl++;
603         }
604     }
605     if (ngl != numAtomsInZones)
606     {
607         fprintf(stderr, "DD rank %d, %s: %d global atom indices, %d local atoms\n", dd->rank, where, ngl, numAtomsInZones);
608     }
609     for (int a = 0; a < numAtomsInZones; a++)
610     {
611         if (have[a] == 0)
612         {
613             fprintf(stderr,
614                     "DD rank %d, %s: local atom %d, global %d has no global index\n",
615                     dd->rank,
616                     where,
617                     a + 1,
618                     dd->globalAtomIndices[a] + 1);
619         }
620     }
621
622     if (nerr > 0)
623     {
624         gmx_fatal(FARGS, "DD rank %d, %s: %d atom(group) index inconsistencies", dd->rank, where, nerr);
625     }
626 }
627
628 //! Clear all DD global state indices
629 static void clearDDStateIndices(gmx_domdec_t* dd, const bool keepLocalAtomIndices)
630 {
631     gmx_ga2la_t& ga2la = *dd->ga2la;
632
633     if (!keepLocalAtomIndices)
634     {
635         /* Clear the whole list without the overhead of searching */
636         ga2la.clear();
637     }
638     else
639     {
640         const int numAtomsInZones = dd->comm->atomRanges.end(DDAtomRanges::Type::Zones);
641         for (int i = 0; i < numAtomsInZones; i++)
642         {
643             ga2la.erase(dd->globalAtomIndices[i]);
644         }
645     }
646
647     dd_clear_local_vsite_indices(dd);
648
649     if (dd->constraints)
650     {
651         dd_clear_local_constraint_indices(dd);
652     }
653 }
654
655 //! Return the duration of force calculations on this rank.
656 static float dd_force_load(gmx_domdec_comm_t* comm)
657 {
658     float load;
659
660     if (comm->ddSettings.eFlop)
661     {
662         load = comm->flop;
663         if (comm->ddSettings.eFlop > 1)
664         {
665             load *= 1.0 + (comm->ddSettings.eFlop - 1) * (0.1 * rand() / RAND_MAX - 0.05);
666         }
667     }
668     else
669     {
670         load = comm->cycl[ddCyclF];
671         if (comm->cycl_n[ddCyclF] > 1)
672         {
673             /* Subtract the maximum of the last n cycle counts
674              * to get rid of possible high counts due to other sources,
675              * for instance system activity, that would otherwise
676              * affect the dynamic load balancing.
677              */
678             load -= comm->cycl_max[ddCyclF];
679         }
680
681 #if GMX_MPI
682         if (comm->cycl_n[ddCyclWaitGPU] && comm->nrank_gpu_shared > 1)
683         {
684             float gpu_wait, gpu_wait_sum;
685
686             gpu_wait = comm->cycl[ddCyclWaitGPU];
687             if (comm->cycl_n[ddCyclF] > 1)
688             {
689                 /* We should remove the WaitGPU time of the same MD step
690                  * as the one with the maximum F time, since the F time
691                  * and the wait time are not independent.
692                  * Furthermore, the step for the max F time should be chosen
693                  * the same on all ranks that share the same GPU.
694                  * But to keep the code simple, we remove the average instead.
695                  * The main reason for artificially long times at some steps
696                  * is spurious CPU activity or MPI time, so we don't expect
697                  * that changes in the GPU wait time matter a lot here.
698                  */
699                 gpu_wait *= (comm->cycl_n[ddCyclF] - 1) / static_cast<float>(comm->cycl_n[ddCyclF]);
700             }
701             /* Sum the wait times over the ranks that share the same GPU */
702             MPI_Allreduce(&gpu_wait, &gpu_wait_sum, 1, MPI_FLOAT, MPI_SUM, comm->mpi_comm_gpu_shared);
703             /* Replace the wait time by the average over the ranks */
704             load += -gpu_wait + gpu_wait_sum / comm->nrank_gpu_shared;
705         }
706 #endif
707     }
708
709     return load;
710 }
711
712 //! Runs cell size checks and communicates the boundaries.
713 static void comm_dd_ns_cell_sizes(gmx_domdec_t* dd, gmx_ddbox_t* ddbox, rvec cell_ns_x0, rvec cell_ns_x1, int64_t step)
714 {
715     gmx_domdec_comm_t* comm;
716     int                dim_ind, dim;
717
718     comm = dd->comm;
719
720     for (dim_ind = 0; dim_ind < dd->ndim; dim_ind++)
721     {
722         dim = dd->dim[dim_ind];
723
724         /* Without PBC we don't have restrictions on the outer cells */
725         if (!(dim >= ddbox->npbcdim && (dd->ci[dim] == 0 || dd->ci[dim] == dd->numCells[dim] - 1))
726             && isDlbOn(comm)
727             && (comm->cell_x1[dim] - comm->cell_x0[dim]) * ddbox->skew_fac[dim] < comm->cellsize_min[dim])
728         {
729             char buf[22];
730             gmx_fatal(FARGS,
731                       "step %s: The %c-size (%f) times the triclinic skew factor (%f) is smaller "
732                       "than the smallest allowed cell size (%f) for domain decomposition grid cell "
733                       "%d %d %d",
734                       gmx_step_str(step, buf),
735                       dim2char(dim),
736                       comm->cell_x1[dim] - comm->cell_x0[dim],
737                       ddbox->skew_fac[dim],
738                       dd->comm->cellsize_min[dim],
739                       dd->ci[XX],
740                       dd->ci[YY],
741                       dd->ci[ZZ]);
742         }
743     }
744
745     if ((isDlbOn(dd->comm) && dd->ndim > 1) || ddbox->nboundeddim < DIM)
746     {
747         /* Communicate the boundaries and update cell_ns_x0/1 */
748         dd_move_cellx(dd, ddbox, cell_ns_x0, cell_ns_x1);
749         if (isDlbOn(dd->comm) && dd->ndim > 1)
750         {
751             gmx::check_grid_jump(step, dd, dd->comm->systemInfo.cutoff, ddbox, TRUE);
752         }
753     }
754 }
755
756 //! Compute and communicate to determine the load distribution across PP ranks.
757 static void get_load_distribution(gmx_domdec_t* dd, gmx_wallcycle_t wcycle)
758 {
759     gmx_domdec_comm_t* comm;
760     domdec_load_t*     load;
761     float              cell_frac = 0, sbuf[DD_NLOAD_MAX];
762     gmx_bool           bSepPME;
763
764     if (debug)
765     {
766         fprintf(debug, "get_load_distribution start\n");
767     }
768
769     wallcycle_start(wcycle, ewcDDCOMMLOAD);
770
771     comm = dd->comm;
772
773     bSepPME = (dd->pme_nodeid >= 0);
774
775     if (dd->ndim == 0 && bSepPME)
776     {
777         /* Without decomposition, but with PME nodes, we need the load */
778         comm->load[0].mdf = comm->cycl[ddCyclPPduringPME];
779         comm->load[0].pme = comm->cycl[ddCyclPME];
780     }
781
782     // Either we have DLB off, or we have it on and the array is large enough
783     GMX_ASSERT(!isDlbOn(dd->comm) || static_cast<int>(dd->comm->cellsizesWithDlb.size()) == dd->ndim,
784                "DLB cell sizes data not set up properly ");
785     for (int d = dd->ndim - 1; d >= 0; d--)
786     {
787         const int dim = dd->dim[d];
788         /* Check if we participate in the communication in this dimension */
789         if (d == dd->ndim - 1 || (dd->ci[dd->dim[d + 1]] == 0 && dd->ci[dd->dim[dd->ndim - 1]] == 0))
790         {
791             load = &comm->load[d];
792             if (isDlbOn(dd->comm))
793             {
794                 cell_frac = comm->cellsizesWithDlb[d].fracUpper - comm->cellsizesWithDlb[d].fracLower;
795             }
796             int pos = 0;
797             if (d == dd->ndim - 1)
798             {
799                 sbuf[pos++] = dd_force_load(comm);
800                 sbuf[pos++] = sbuf[0];
801                 if (isDlbOn(dd->comm))
802                 {
803                     sbuf[pos++] = sbuf[0];
804                     sbuf[pos++] = cell_frac;
805                     if (d > 0)
806                     {
807                         sbuf[pos++] = comm->cellsizesWithDlb[d].fracLowerMax;
808                         sbuf[pos++] = comm->cellsizesWithDlb[d].fracUpperMin;
809                     }
810                 }
811                 if (bSepPME)
812                 {
813                     sbuf[pos++] = comm->cycl[ddCyclPPduringPME];
814                     sbuf[pos++] = comm->cycl[ddCyclPME];
815                 }
816             }
817             else
818             {
819                 sbuf[pos++] = comm->load[d + 1].sum;
820                 sbuf[pos++] = comm->load[d + 1].max;
821                 if (isDlbOn(dd->comm))
822                 {
823                     sbuf[pos++] = comm->load[d + 1].sum_m;
824                     sbuf[pos++] = comm->load[d + 1].cvol_min * cell_frac;
825                     sbuf[pos++] = comm->load[d + 1].flags;
826                     if (d > 0)
827                     {
828                         sbuf[pos++] = comm->cellsizesWithDlb[d].fracLowerMax;
829                         sbuf[pos++] = comm->cellsizesWithDlb[d].fracUpperMin;
830                     }
831                 }
832                 if (bSepPME)
833                 {
834                     sbuf[pos++] = comm->load[d + 1].mdf;
835                     sbuf[pos++] = comm->load[d + 1].pme;
836                 }
837             }
838             load->nload = pos;
839             /* Communicate a row in DD direction d.
840              * The communicators are setup such that the root always has rank 0.
841              */
842 #if GMX_MPI
843             MPI_Gather(sbuf,
844                        load->nload * sizeof(float),
845                        MPI_BYTE,
846                        load->load,
847                        load->nload * sizeof(float),
848                        MPI_BYTE,
849                        0,
850                        comm->mpi_comm_load[d]);
851 #endif
852             if (dd->ci[dim] == dd->master_ci[dim])
853             {
854                 /* We are the master along this row, process this row */
855                 RowMaster* rowMaster = nullptr;
856
857                 if (isDlbOn(comm))
858                 {
859                     rowMaster = comm->cellsizesWithDlb[d].rowMaster.get();
860                 }
861                 load->sum      = 0;
862                 load->max      = 0;
863                 load->sum_m    = 0;
864                 load->cvol_min = 1;
865                 load->flags    = 0;
866                 load->mdf      = 0;
867                 load->pme      = 0;
868                 int pos        = 0;
869                 for (int i = 0; i < dd->numCells[dim]; i++)
870                 {
871                     load->sum += load->load[pos++];
872                     load->max = std::max(load->max, load->load[pos]);
873                     pos++;
874                     if (isDlbOn(dd->comm))
875                     {
876                         if (rowMaster->dlbIsLimited)
877                         {
878                             /* This direction could not be load balanced properly,
879                              * therefore we need to use the maximum iso the average load.
880                              */
881                             load->sum_m = std::max(load->sum_m, load->load[pos]);
882                         }
883                         else
884                         {
885                             load->sum_m += load->load[pos];
886                         }
887                         pos++;
888                         load->cvol_min = std::min(load->cvol_min, load->load[pos]);
889                         pos++;
890                         if (d < dd->ndim - 1)
891                         {
892                             load->flags = gmx::roundToInt(load->load[pos++]);
893                         }
894                         if (d > 0)
895                         {
896                             rowMaster->bounds[i].cellFracLowerMax = load->load[pos++];
897                             rowMaster->bounds[i].cellFracUpperMin = load->load[pos++];
898                         }
899                     }
900                     if (bSepPME)
901                     {
902                         load->mdf = std::max(load->mdf, load->load[pos]);
903                         pos++;
904                         load->pme = std::max(load->pme, load->load[pos]);
905                         pos++;
906                     }
907                 }
908                 if (isDlbOn(comm) && rowMaster->dlbIsLimited)
909                 {
910                     load->sum_m *= dd->numCells[dim];
911                     load->flags |= (1 << d);
912                 }
913             }
914         }
915     }
916
917     if (DDMASTER(dd))
918     {
919         comm->nload += dd_load_count(comm);
920         comm->load_step += comm->cycl[ddCyclStep];
921         comm->load_sum += comm->load[0].sum;
922         comm->load_max += comm->load[0].max;
923         if (isDlbOn(comm))
924         {
925             for (int d = 0; d < dd->ndim; d++)
926             {
927                 if (comm->load[0].flags & (1 << d))
928                 {
929                     comm->load_lim[d]++;
930                 }
931             }
932         }
933         if (bSepPME)
934         {
935             comm->load_mdf += comm->load[0].mdf;
936             comm->load_pme += comm->load[0].pme;
937         }
938     }
939
940     wallcycle_stop(wcycle, ewcDDCOMMLOAD);
941
942     if (debug)
943     {
944         fprintf(debug, "get_load_distribution finished\n");
945     }
946 }
947
948 /*! \brief Return the relative performance loss on the total run time
949  * due to the force calculation load imbalance. */
950 static float dd_force_load_fraction(gmx_domdec_t* dd)
951 {
952     if (dd->comm->nload > 0 && dd->comm->load_step > 0)
953     {
954         return dd->comm->load_sum / (dd->comm->load_step * dd->nnodes);
955     }
956     else
957     {
958         return 0;
959     }
960 }
961
962 /*! \brief Return the relative performance loss on the total run time
963  * due to the force calculation load imbalance. */
964 static float dd_force_imb_perf_loss(gmx_domdec_t* dd)
965 {
966     if (dd->comm->nload > 0 && dd->comm->load_step > 0)
967     {
968         return (dd->comm->load_max * dd->nnodes - dd->comm->load_sum) / (dd->comm->load_step * dd->nnodes);
969     }
970     else
971     {
972         return 0;
973     }
974 }
975
976 //! Print load-balance report e.g. at the end of a run.
977 static void print_dd_load_av(FILE* fplog, gmx_domdec_t* dd)
978 {
979     gmx_domdec_comm_t* comm = dd->comm;
980
981     /* Only the master rank prints loads and only if we measured loads */
982     if (!DDMASTER(dd) || comm->nload == 0)
983     {
984         return;
985     }
986
987     char buf[STRLEN];
988     int  numPpRanks  = dd->nnodes;
989     int  numPmeRanks = (comm->ddRankSetup.usePmeOnlyRanks ? comm->ddRankSetup.numRanksDoingPme : 0);
990     int  numRanks    = numPpRanks + numPmeRanks;
991     float lossFraction = 0;
992
993     /* Print the average load imbalance and performance loss */
994     if (dd->nnodes > 1 && comm->load_sum > 0)
995     {
996         float imbalance = comm->load_max * numPpRanks / comm->load_sum - 1;
997         lossFraction    = dd_force_imb_perf_loss(dd);
998
999         std::string msg = "\nDynamic load balancing report:\n";
1000         std::string dlbStateStr;
1001
1002         switch (dd->comm->dlbState)
1003         {
1004             case DlbState::offUser:
1005                 dlbStateStr = "DLB was off during the run per user request.";
1006                 break;
1007             case DlbState::offForever:
1008                 /* Currectly this can happen due to performance loss observed, cell size
1009                  * limitations or incompatibility with other settings observed during
1010                  * determineInitialDlbState(). */
1011                 dlbStateStr = "DLB got disabled because it was unsuitable to use.";
1012                 break;
1013             case DlbState::offCanTurnOn:
1014                 dlbStateStr = "DLB was off during the run due to low measured imbalance.";
1015                 break;
1016             case DlbState::offTemporarilyLocked:
1017                 dlbStateStr =
1018                         "DLB was locked at the end of the run due to unfinished PP-PME "
1019                         "balancing.";
1020                 break;
1021             case DlbState::onCanTurnOff:
1022                 dlbStateStr = "DLB was turned on during the run due to measured imbalance.";
1023                 break;
1024             case DlbState::onUser:
1025                 dlbStateStr = "DLB was permanently on during the run per user request.";
1026                 break;
1027             default: GMX_ASSERT(false, "Undocumented DLB state");
1028         }
1029
1030         msg += " " + dlbStateStr + "\n";
1031         msg += gmx::formatString(" Average load imbalance: %.1f%%.\n", imbalance * 100);
1032         msg += gmx::formatString(
1033                 " The balanceable part of the MD step is %d%%, load imbalance is computed from "
1034                 "this.\n",
1035                 gmx::roundToInt(dd_force_load_fraction(dd) * 100));
1036         msg += gmx::formatString(
1037                 " Part of the total run time spent waiting due to load imbalance: %.1f%%.\n",
1038                 lossFraction * 100);
1039         fprintf(fplog, "%s", msg.c_str());
1040         fprintf(stderr, "\n%s", msg.c_str());
1041     }
1042
1043     /* Print during what percentage of steps the  load balancing was limited */
1044     bool dlbWasLimited = false;
1045     if (isDlbOn(comm))
1046     {
1047         sprintf(buf, " Steps where the load balancing was limited by -rdd, -rcon and/or -dds:");
1048         for (int d = 0; d < dd->ndim; d++)
1049         {
1050             int limitPercentage = (200 * comm->load_lim[d] + 1) / (2 * comm->nload);
1051             sprintf(buf + strlen(buf), " %c %d %%", dim2char(dd->dim[d]), limitPercentage);
1052             if (limitPercentage >= 50)
1053             {
1054                 dlbWasLimited = true;
1055             }
1056         }
1057         sprintf(buf + strlen(buf), "\n");
1058         fprintf(fplog, "%s", buf);
1059         fprintf(stderr, "%s", buf);
1060     }
1061
1062     /* Print the performance loss due to separate PME - PP rank imbalance */
1063     float lossFractionPme = 0;
1064     if (numPmeRanks > 0 && comm->load_mdf > 0 && comm->load_step > 0)
1065     {
1066         float pmeForceRatio = comm->load_pme / comm->load_mdf;
1067         lossFractionPme     = (comm->load_pme - comm->load_mdf) / comm->load_step;
1068         if (lossFractionPme <= 0)
1069         {
1070             lossFractionPme *= numPmeRanks / static_cast<float>(numRanks);
1071         }
1072         else
1073         {
1074             lossFractionPme *= numPpRanks / static_cast<float>(numRanks);
1075         }
1076         sprintf(buf, " Average PME mesh/force load: %5.3f\n", pmeForceRatio);
1077         fprintf(fplog, "%s", buf);
1078         fprintf(stderr, "%s", buf);
1079         sprintf(buf,
1080                 " Part of the total run time spent waiting due to PP/PME imbalance: %.1f %%\n",
1081                 std::fabs(lossFractionPme) * 100);
1082         fprintf(fplog, "%s", buf);
1083         fprintf(stderr, "%s", buf);
1084     }
1085     fprintf(fplog, "\n");
1086     fprintf(stderr, "\n");
1087
1088     if ((lossFraction >= DD_PERF_LOSS_WARN) && (dd->comm->dlbState != DlbState::offTemporarilyLocked))
1089     {
1090         std::string message = gmx::formatString(
1091                 "NOTE: %.1f %% of the available CPU time was lost due to load imbalance\n"
1092                 "      in the domain decomposition.\n",
1093                 lossFraction * 100);
1094
1095         bool hadSuggestion = false;
1096         if (dd->comm->dlbState == DlbState::offUser)
1097         {
1098             message += "      You might want to allow dynamic load balancing (option -dlb auto.)\n";
1099             hadSuggestion = true;
1100         }
1101         else if (dd->comm->dlbState == DlbState::offCanTurnOn)
1102         {
1103             message +=
1104                     "      Dynamic load balancing was automatically disabled, but it might be "
1105                     "beneficial to manually tuning it on (option -dlb on.)\n";
1106             hadSuggestion = true;
1107         }
1108         else if (dlbWasLimited)
1109         {
1110             message +=
1111                     "      You might want to decrease the cell size limit (options -rdd, -rcon "
1112                     "and/or -dds).\n";
1113             hadSuggestion = true;
1114         }
1115         message += gmx::formatString(
1116                 "      You can %sconsider manually changing the decomposition (option -dd);\n"
1117                 "      e.g. by using fewer domains along the box dimension in which there is\n"
1118                 "      considerable inhomogeneity in the simulated system.",
1119                 hadSuggestion ? "also " : "");
1120
1121         fprintf(fplog, "%s\n", message.c_str());
1122         fprintf(stderr, "%s\n", message.c_str());
1123     }
1124     if (numPmeRanks > 0 && std::fabs(lossFractionPme) >= DD_PERF_LOSS_WARN)
1125     {
1126         sprintf(buf,
1127                 "NOTE: %.1f %% performance was lost because the PME ranks\n"
1128                 "      had %s work to do than the PP ranks.\n"
1129                 "      You might want to %s the number of PME ranks\n"
1130                 "      or %s the cut-off and the grid spacing.\n",
1131                 std::fabs(lossFractionPme * 100),
1132                 (lossFractionPme < 0) ? "less" : "more",
1133                 (lossFractionPme < 0) ? "decrease" : "increase",
1134                 (lossFractionPme < 0) ? "decrease" : "increase");
1135         fprintf(fplog, "%s\n", buf);
1136         fprintf(stderr, "%s\n", buf);
1137     }
1138 }
1139
1140 //! Return the minimum communication volume.
1141 static float dd_vol_min(gmx_domdec_t* dd)
1142 {
1143     return dd->comm->load[0].cvol_min * dd->nnodes;
1144 }
1145
1146 //! Return the DD load flags.
1147 static int dd_load_flags(gmx_domdec_t* dd)
1148 {
1149     return dd->comm->load[0].flags;
1150 }
1151
1152 //! Return the reported load imbalance in force calculations.
1153 static float dd_f_imbal(gmx_domdec_t* dd)
1154 {
1155     if (dd->comm->load[0].sum > 0)
1156     {
1157         return dd->comm->load[0].max * dd->nnodes / dd->comm->load[0].sum - 1.0F;
1158     }
1159     else
1160     {
1161         /* Something is wrong in the cycle counting, report no load imbalance */
1162         return 0.0F;
1163     }
1164 }
1165
1166 //! Returns DD load balance report.
1167 static std::string dd_print_load(gmx_domdec_t* dd, int64_t step)
1168 {
1169     gmx::StringOutputStream stream;
1170     gmx::TextWriter         log(&stream);
1171
1172     int flags = dd_load_flags(dd);
1173     if (flags)
1174     {
1175         log.writeString("DD  load balancing is limited by minimum cell size in dimension");
1176         for (int d = 0; d < dd->ndim; d++)
1177         {
1178             if (flags & (1 << d))
1179             {
1180                 log.writeStringFormatted(" %c", dim2char(dd->dim[d]));
1181             }
1182         }
1183         log.ensureLineBreak();
1184     }
1185     log.writeString("DD  step " + gmx::toString(step));
1186     if (isDlbOn(dd->comm))
1187     {
1188         log.writeStringFormatted("  vol min/aver %5.3f%c", dd_vol_min(dd), flags ? '!' : ' ');
1189     }
1190     if (dd->nnodes > 1)
1191     {
1192         log.writeStringFormatted(" load imb.: force %4.1f%%", dd_f_imbal(dd) * 100);
1193     }
1194     if (dd->comm->cycl_n[ddCyclPME])
1195     {
1196         log.writeStringFormatted("  pme mesh/force %5.3f", dd_pme_f_ratio(dd));
1197     }
1198     log.ensureLineBreak();
1199     return stream.toString();
1200 }
1201
1202 //! Prints DD load balance report in mdrun verbose mode.
1203 static void dd_print_load_verbose(gmx_domdec_t* dd)
1204 {
1205     if (isDlbOn(dd->comm))
1206     {
1207         fprintf(stderr, "vol %4.2f%c ", dd_vol_min(dd), dd_load_flags(dd) ? '!' : ' ');
1208     }
1209     if (dd->nnodes > 1)
1210     {
1211         fprintf(stderr, "imb F %2d%% ", gmx::roundToInt(dd_f_imbal(dd) * 100));
1212     }
1213     if (dd->comm->cycl_n[ddCyclPME])
1214     {
1215         fprintf(stderr, "pme/F %4.2f ", dd_pme_f_ratio(dd));
1216     }
1217 }
1218
1219 //! Turns on dynamic load balancing if possible and needed.
1220 static void turn_on_dlb(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t step)
1221 {
1222     gmx_domdec_comm_t* comm = dd->comm;
1223
1224     real cellsize_min = comm->cellsize_min[dd->dim[0]];
1225     for (int d = 1; d < dd->ndim; d++)
1226     {
1227         cellsize_min = std::min(cellsize_min, comm->cellsize_min[dd->dim[d]]);
1228     }
1229
1230     /* Turn off DLB if we're too close to the cell size limit. */
1231     if (cellsize_min < comm->cellsize_limit * 1.05)
1232     {
1233         GMX_LOG(mdlog.info)
1234                 .appendTextFormatted(
1235                         "step %s Measured %.1f %% performance loss due to load imbalance, "
1236                         "but the minimum cell size is smaller than 1.05 times the cell size limit. "
1237                         "Will no longer try dynamic load balancing.",
1238                         gmx::toString(step).c_str(),
1239                         dd_force_imb_perf_loss(dd) * 100);
1240
1241         comm->dlbState = DlbState::offForever;
1242         return;
1243     }
1244
1245     GMX_LOG(mdlog.info)
1246             .appendTextFormatted(
1247                     "step %s Turning on dynamic load balancing, because the performance loss due "
1248                     "to load imbalance is %.1f %%.",
1249                     gmx::toString(step).c_str(),
1250                     dd_force_imb_perf_loss(dd) * 100);
1251     comm->dlbState = DlbState::onCanTurnOff;
1252
1253     /* Store the non-DLB performance, so we can check if DLB actually
1254      * improves performance.
1255      */
1256     GMX_RELEASE_ASSERT(comm->cycl_n[ddCyclStep] > 0,
1257                        "When we turned on DLB, we should have measured cycles");
1258     comm->cyclesPerStepBeforeDLB = comm->cycl[ddCyclStep] / comm->cycl_n[ddCyclStep];
1259
1260     set_dlb_limits(dd);
1261
1262     /* We can set the required cell size info here,
1263      * so we do not need to communicate this.
1264      * The grid is completely uniform.
1265      */
1266     for (int d = 0; d < dd->ndim; d++)
1267     {
1268         RowMaster* rowMaster = comm->cellsizesWithDlb[d].rowMaster.get();
1269
1270         if (rowMaster)
1271         {
1272             comm->load[d].sum_m = comm->load[d].sum;
1273
1274             int nc = dd->numCells[dd->dim[d]];
1275             for (int i = 0; i < nc; i++)
1276             {
1277                 rowMaster->cellFrac[i] = i / static_cast<real>(nc);
1278                 if (d > 0)
1279                 {
1280                     rowMaster->bounds[i].cellFracLowerMax = i / static_cast<real>(nc);
1281                     rowMaster->bounds[i].cellFracUpperMin = (i + 1) / static_cast<real>(nc);
1282                 }
1283             }
1284             rowMaster->cellFrac[nc] = 1.0;
1285         }
1286     }
1287 }
1288
1289 //! Turns off dynamic load balancing (but leave it able to turn back on).
1290 static void turn_off_dlb(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t step)
1291 {
1292     GMX_LOG(mdlog.info)
1293             .appendText(
1294                     "step " + gmx::toString(step)
1295                     + " Turning off dynamic load balancing, because it is degrading performance.");
1296     dd->comm->dlbState                     = DlbState::offCanTurnOn;
1297     dd->comm->haveTurnedOffDlb             = true;
1298     dd->comm->ddPartioningCountFirstDlbOff = dd->ddp_count;
1299 }
1300
1301 //! Turns off dynamic load balancing permanently.
1302 static void turn_off_dlb_forever(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t step)
1303 {
1304     GMX_RELEASE_ASSERT(dd->comm->dlbState == DlbState::offCanTurnOn,
1305                        "Can only turn off DLB forever when it was in the can-turn-on state");
1306     GMX_LOG(mdlog.info)
1307             .appendText(
1308                     "step " + gmx::toString(step)
1309                     + " Will no longer try dynamic load balancing, as it degraded performance.");
1310     dd->comm->dlbState = DlbState::offForever;
1311 }
1312
1313 void set_dd_dlb_max_cutoff(t_commrec* cr, real cutoff)
1314 {
1315     gmx_domdec_comm_t* comm;
1316
1317     comm = cr->dd->comm;
1318
1319     /* Turn on the DLB limiting (might have been on already) */
1320     comm->bPMELoadBalDLBLimits = TRUE;
1321
1322     /* Change the cut-off limit */
1323     comm->PMELoadBal_max_cutoff = cutoff;
1324
1325     if (debug)
1326     {
1327         fprintf(debug,
1328                 "PME load balancing set a limit to the DLB staggering such that a %f cut-off will "
1329                 "continue to fit\n",
1330                 comm->PMELoadBal_max_cutoff);
1331     }
1332 }
1333
1334 //! Merge atom buffers.
1335 static void merge_cg_buffers(int                            ncell,
1336                              gmx_domdec_comm_dim_t*         cd,
1337                              int                            pulse,
1338                              int*                           ncg_cell,
1339                              gmx::ArrayRef<int>             index_gl,
1340                              const int*                     recv_i,
1341                              gmx::ArrayRef<gmx::RVec>       x,
1342                              gmx::ArrayRef<const gmx::RVec> recv_vr,
1343                              gmx::ArrayRef<cginfo_mb_t>     cginfo_mb,
1344                              gmx::ArrayRef<int>             cginfo)
1345 {
1346     gmx_domdec_ind_t *ind, *ind_p;
1347     int               p, cell, c, cg, cg0, cg1, cg_gl;
1348     int               shift;
1349
1350     ind = &cd->ind[pulse];
1351
1352     /* First correct the already stored data */
1353     shift = ind->nrecv[ncell];
1354     for (cell = ncell - 1; cell >= 0; cell--)
1355     {
1356         shift -= ind->nrecv[cell];
1357         if (shift > 0)
1358         {
1359             /* Move the cg's present from previous grid pulses */
1360             cg0 = ncg_cell[ncell + cell];
1361             cg1 = ncg_cell[ncell + cell + 1];
1362             for (cg = cg1 - 1; cg >= cg0; cg--)
1363             {
1364                 index_gl[cg + shift] = index_gl[cg];
1365                 x[cg + shift]        = x[cg];
1366                 cginfo[cg + shift]   = cginfo[cg];
1367             }
1368             /* Correct the already stored send indices for the shift */
1369             for (p = 1; p <= pulse; p++)
1370             {
1371                 ind_p = &cd->ind[p];
1372                 cg0   = 0;
1373                 for (c = 0; c < cell; c++)
1374                 {
1375                     cg0 += ind_p->nsend[c];
1376                 }
1377                 cg1 = cg0 + ind_p->nsend[cell];
1378                 for (cg = cg0; cg < cg1; cg++)
1379                 {
1380                     ind_p->index[cg] += shift;
1381                 }
1382             }
1383         }
1384     }
1385
1386     /* Merge in the communicated buffers */
1387     shift = 0;
1388     cg0   = 0;
1389     for (cell = 0; cell < ncell; cell++)
1390     {
1391         cg1 = ncg_cell[ncell + cell + 1] + shift;
1392         for (cg = 0; cg < ind->nrecv[cell]; cg++)
1393         {
1394             /* Copy this atom from the buffer */
1395             index_gl[cg1] = recv_i[cg0];
1396             x[cg1]        = recv_vr[cg0];
1397             /* Copy information */
1398             cg_gl       = index_gl[cg1];
1399             cginfo[cg1] = ddcginfo(cginfo_mb, cg_gl);
1400             cg0++;
1401             cg1++;
1402         }
1403         shift += ind->nrecv[cell];
1404         ncg_cell[ncell + cell + 1] = cg1;
1405     }
1406 }
1407
1408 //! Makes a range partitioning for the atom groups wthin a cell
1409 static void make_cell2at_index(gmx_domdec_comm_dim_t* cd, int nzone, int atomGroupStart)
1410 {
1411     /* Store the atom block boundaries for easy copying of communication buffers
1412      */
1413     int g = atomGroupStart;
1414     for (int zone = 0; zone < nzone; zone++)
1415     {
1416         for (gmx_domdec_ind_t& ind : cd->ind)
1417         {
1418             ind.cell2at0[zone] = g;
1419             g += ind.nrecv[zone];
1420             ind.cell2at1[zone] = g;
1421         }
1422     }
1423 }
1424
1425 //! Returns whether a link is missing.
1426 static gmx_bool missing_link(const t_blocka& link, const int globalAtomIndex, const gmx_ga2la_t& ga2la)
1427 {
1428     for (int i = link.index[globalAtomIndex]; i < link.index[globalAtomIndex + 1]; i++)
1429     {
1430         if (!ga2la.findHome(link.a[i]))
1431         {
1432             return true;
1433         }
1434     }
1435
1436     return false;
1437 }
1438
1439 //! Domain corners for communication, a maximum of 4 i-zones see a j domain
1440 typedef struct
1441 {
1442     //! The corners for the non-bonded communication.
1443     real c[DIM][4];
1444     //! Corner for rounding.
1445     real cr0;
1446     //! Corners for rounding.
1447     real cr1[4];
1448     //! Corners for bounded communication.
1449     real bc[DIM];
1450     //! Corner for rounding for bonded communication.
1451     real bcr1;
1452 } dd_corners_t;
1453
1454 //! Determine the corners of the domain(s) we are communicating with.
1455 static void set_dd_corners(const gmx_domdec_t* dd, int dim0, int dim1, int dim2, gmx_bool bDistMB, dd_corners_t* c)
1456 {
1457     const gmx_domdec_comm_t*  comm;
1458     const gmx_domdec_zones_t* zones;
1459
1460     comm = dd->comm;
1461
1462     zones = &comm->zones;
1463
1464     /* Keep the compiler happy */
1465     c->cr0  = 0;
1466     c->bcr1 = 0;
1467
1468     /* The first dimension is equal for all cells */
1469     c->c[0][0] = comm->cell_x0[dim0];
1470     if (bDistMB)
1471     {
1472         c->bc[0] = c->c[0][0];
1473     }
1474     if (dd->ndim >= 2)
1475     {
1476         dim1 = dd->dim[1];
1477         /* This cell row is only seen from the first row */
1478         c->c[1][0] = comm->cell_x0[dim1];
1479         /* All rows can see this row */
1480         c->c[1][1] = comm->cell_x0[dim1];
1481         if (isDlbOn(dd->comm))
1482         {
1483             c->c[1][1] = std::max(comm->cell_x0[dim1], comm->zone_d1[1].mch0);
1484             if (bDistMB)
1485             {
1486                 /* For the multi-body distance we need the maximum */
1487                 c->bc[1] = std::max(comm->cell_x0[dim1], comm->zone_d1[1].p1_0);
1488             }
1489         }
1490         /* Set the upper-right corner for rounding */
1491         c->cr0 = comm->cell_x1[dim0];
1492
1493         if (dd->ndim >= 3)
1494         {
1495             dim2 = dd->dim[2];
1496             for (int j = 0; j < 4; j++)
1497             {
1498                 c->c[2][j] = comm->cell_x0[dim2];
1499             }
1500             if (isDlbOn(dd->comm))
1501             {
1502                 /* Use the maximum of the i-cells that see a j-cell */
1503                 for (const auto& iZone : zones->iZones)
1504                 {
1505                     const int iZoneIndex = iZone.iZoneIndex;
1506                     for (int jZone : iZone.jZoneRange)
1507                     {
1508                         if (jZone >= 4)
1509                         {
1510                             c->c[2][jZone - 4] = std::max(
1511                                     c->c[2][jZone - 4],
1512                                     comm->zone_d2[zones->shift[iZoneIndex][dim0]][zones->shift[iZoneIndex][dim1]]
1513                                             .mch0);
1514                         }
1515                     }
1516                 }
1517                 if (bDistMB)
1518                 {
1519                     /* For the multi-body distance we need the maximum */
1520                     c->bc[2] = comm->cell_x0[dim2];
1521                     for (int i = 0; i < 2; i++)
1522                     {
1523                         for (int j = 0; j < 2; j++)
1524                         {
1525                             c->bc[2] = std::max(c->bc[2], comm->zone_d2[i][j].p1_0);
1526                         }
1527                     }
1528                 }
1529             }
1530
1531             /* Set the upper-right corner for rounding */
1532             /* Cell (0,0,0) and cell (1,0,0) can see cell 4 (0,1,1)
1533              * Only cell (0,0,0) can see cell 7 (1,1,1)
1534              */
1535             c->cr1[0] = comm->cell_x1[dim1];
1536             c->cr1[3] = comm->cell_x1[dim1];
1537             if (isDlbOn(dd->comm))
1538             {
1539                 c->cr1[0] = std::max(comm->cell_x1[dim1], comm->zone_d1[1].mch1);
1540                 if (bDistMB)
1541                 {
1542                     /* For the multi-body distance we need the maximum */
1543                     c->bcr1 = std::max(comm->cell_x1[dim1], comm->zone_d1[1].p1_1);
1544                 }
1545             }
1546         }
1547     }
1548 }
1549
1550 /*! \brief Add the atom groups we need to send in this pulse from this
1551  * zone to \p localAtomGroups and \p work. */
1552 static void get_zone_pulse_cgs(gmx_domdec_t*            dd,
1553                                int                      zonei,
1554                                int                      zone,
1555                                int                      cg0,
1556                                int                      cg1,
1557                                gmx::ArrayRef<const int> globalAtomGroupIndices,
1558                                int                      dim,
1559                                int                      dim_ind,
1560                                int                      dim0,
1561                                int                      dim1,
1562                                int                      dim2,
1563                                real                     r_comm2,
1564                                real                     r_bcomm2,
1565                                matrix                   box,
1566                                bool                     distanceIsTriclinic,
1567                                rvec*                    normal,
1568                                real                     skew_fac2_d,
1569                                real                     skew_fac_01,
1570                                rvec*                    v_d,
1571                                rvec*                    v_0,
1572                                rvec*                    v_1,
1573                                const dd_corners_t*      c,
1574                                const rvec               sf2_round,
1575                                gmx_bool                 bDistBonded,
1576                                gmx_bool                 bBondComm,
1577                                gmx_bool                 bDist2B,
1578                                gmx_bool                 bDistMB,
1579                                rvec*                    cg_cm,
1580                                gmx::ArrayRef<const int> cginfo,
1581                                std::vector<int>*        localAtomGroups,
1582                                dd_comm_setup_work_t*    work)
1583 {
1584     gmx_domdec_comm_t* comm;
1585     gmx_bool           bScrew;
1586     gmx_bool           bDistMB_pulse;
1587     int                cg, i;
1588     real               r2, rb2, r, tric_sh;
1589     rvec               rn, rb;
1590     int                dimd;
1591     int                nsend_z, nat;
1592
1593     comm = dd->comm;
1594
1595     bScrew = (dd->unitCellInfo.haveScrewPBC && dim == XX);
1596
1597     bDistMB_pulse = (bDistMB && bDistBonded);
1598
1599     /* Unpack the work data */
1600     std::vector<int>&       ibuf = work->atomGroupBuffer;
1601     std::vector<gmx::RVec>& vbuf = work->positionBuffer;
1602     nsend_z                      = 0;
1603     nat                          = work->nat;
1604
1605     for (cg = cg0; cg < cg1; cg++)
1606     {
1607         r2  = 0;
1608         rb2 = 0;
1609         if (!distanceIsTriclinic)
1610         {
1611             /* Rectangular direction, easy */
1612             r = cg_cm[cg][dim] - c->c[dim_ind][zone];
1613             if (r > 0)
1614             {
1615                 r2 += r * r;
1616             }
1617             if (bDistMB_pulse)
1618             {
1619                 r = cg_cm[cg][dim] - c->bc[dim_ind];
1620                 if (r > 0)
1621                 {
1622                     rb2 += r * r;
1623                 }
1624             }
1625             /* Rounding gives at most a 16% reduction
1626              * in communicated atoms
1627              */
1628             if (dim_ind >= 1 && (zonei == 1 || zonei == 2))
1629             {
1630                 r = cg_cm[cg][dim0] - c->cr0;
1631                 /* This is the first dimension, so always r >= 0 */
1632                 r2 += r * r;
1633                 if (bDistMB_pulse)
1634                 {
1635                     rb2 += r * r;
1636                 }
1637             }
1638             if (dim_ind == 2 && (zonei == 2 || zonei == 3))
1639             {
1640                 r = cg_cm[cg][dim1] - c->cr1[zone];
1641                 if (r > 0)
1642                 {
1643                     r2 += r * r;
1644                 }
1645                 if (bDistMB_pulse)
1646                 {
1647                     r = cg_cm[cg][dim1] - c->bcr1;
1648                     if (r > 0)
1649                     {
1650                         rb2 += r * r;
1651                     }
1652                 }
1653             }
1654         }
1655         else
1656         {
1657             /* Triclinic direction, more complicated */
1658             clear_rvec(rn);
1659             clear_rvec(rb);
1660             /* Rounding, conservative as the skew_fac multiplication
1661              * will slightly underestimate the distance.
1662              */
1663             if (dim_ind >= 1 && (zonei == 1 || zonei == 2))
1664             {
1665                 rn[dim0] = cg_cm[cg][dim0] - c->cr0;
1666                 for (i = dim0 + 1; i < DIM; i++)
1667                 {
1668                     rn[dim0] -= cg_cm[cg][i] * v_0[i][dim0];
1669                 }
1670                 r2 = rn[dim0] * rn[dim0] * sf2_round[dim0];
1671                 if (bDistMB_pulse)
1672                 {
1673                     rb[dim0] = rn[dim0];
1674                     rb2      = r2;
1675                 }
1676                 /* Take care that the cell planes along dim0 might not
1677                  * be orthogonal to those along dim1 and dim2.
1678                  */
1679                 for (i = 1; i <= dim_ind; i++)
1680                 {
1681                     dimd = dd->dim[i];
1682                     if (normal[dim0][dimd] > 0)
1683                     {
1684                         rn[dimd] -= rn[dim0] * normal[dim0][dimd];
1685                         if (bDistMB_pulse)
1686                         {
1687                             rb[dimd] -= rb[dim0] * normal[dim0][dimd];
1688                         }
1689                     }
1690                 }
1691             }
1692             if (dim_ind == 2 && (zonei == 2 || zonei == 3))
1693             {
1694                 GMX_ASSERT(dim1 >= 0 && dim1 < DIM, "Must have a valid dimension index");
1695                 rn[dim1] += cg_cm[cg][dim1] - c->cr1[zone];
1696                 tric_sh = 0;
1697                 for (i = dim1 + 1; i < DIM; i++)
1698                 {
1699                     tric_sh -= cg_cm[cg][i] * v_1[i][dim1];
1700                 }
1701                 rn[dim1] += tric_sh;
1702                 if (rn[dim1] > 0)
1703                 {
1704                     r2 += rn[dim1] * rn[dim1] * sf2_round[dim1];
1705                     /* Take care of coupling of the distances
1706                      * to the planes along dim0 and dim1 through dim2.
1707                      */
1708                     r2 -= rn[dim0] * rn[dim1] * skew_fac_01;
1709                     /* Take care that the cell planes along dim1
1710                      * might not be orthogonal to that along dim2.
1711                      */
1712                     if (normal[dim1][dim2] > 0)
1713                     {
1714                         rn[dim2] -= rn[dim1] * normal[dim1][dim2];
1715                     }
1716                 }
1717                 if (bDistMB_pulse)
1718                 {
1719                     rb[dim1] += cg_cm[cg][dim1] - c->bcr1 + tric_sh;
1720                     if (rb[dim1] > 0)
1721                     {
1722                         rb2 += rb[dim1] * rb[dim1] * sf2_round[dim1];
1723                         /* Take care of coupling of the distances
1724                          * to the planes along dim0 and dim1 through dim2.
1725                          */
1726                         rb2 -= rb[dim0] * rb[dim1] * skew_fac_01;
1727                         /* Take care that the cell planes along dim1
1728                          * might not be orthogonal to that along dim2.
1729                          */
1730                         if (normal[dim1][dim2] > 0)
1731                         {
1732                             rb[dim2] -= rb[dim1] * normal[dim1][dim2];
1733                         }
1734                     }
1735                 }
1736             }
1737             /* The distance along the communication direction */
1738             rn[dim] += cg_cm[cg][dim] - c->c[dim_ind][zone];
1739             tric_sh = 0;
1740             for (i = dim + 1; i < DIM; i++)
1741             {
1742                 tric_sh -= cg_cm[cg][i] * v_d[i][dim];
1743             }
1744             rn[dim] += tric_sh;
1745             if (rn[dim] > 0)
1746             {
1747                 r2 += rn[dim] * rn[dim] * skew_fac2_d;
1748                 /* Take care of coupling of the distances
1749                  * to the planes along dim0 and dim1 through dim2.
1750                  */
1751                 if (dim_ind == 1 && zonei == 1)
1752                 {
1753                     r2 -= rn[dim0] * rn[dim] * skew_fac_01;
1754                 }
1755             }
1756             if (bDistMB_pulse)
1757             {
1758                 clear_rvec(rb);
1759                 GMX_ASSERT(dim >= 0 && dim < DIM, "Must have a valid dimension index");
1760                 rb[dim] += cg_cm[cg][dim] - c->bc[dim_ind] + tric_sh;
1761                 if (rb[dim] > 0)
1762                 {
1763                     rb2 += rb[dim] * rb[dim] * skew_fac2_d;
1764                     /* Take care of coupling of the distances
1765                      * to the planes along dim0 and dim1 through dim2.
1766                      */
1767                     if (dim_ind == 1 && zonei == 1)
1768                     {
1769                         rb2 -= rb[dim0] * rb[dim] * skew_fac_01;
1770                     }
1771                 }
1772             }
1773         }
1774
1775         if (r2 < r_comm2
1776             || (bDistBonded && ((bDistMB && rb2 < r_bcomm2) || (bDist2B && r2 < r_bcomm2))
1777                 && (!bBondComm
1778                     || (GET_CGINFO_BOND_INTER(cginfo[cg])
1779                         && missing_link(*comm->bondedLinks, globalAtomGroupIndices[cg], *dd->ga2la)))))
1780         {
1781             /* Store the local and global atom group indices and position */
1782             localAtomGroups->push_back(cg);
1783             ibuf.push_back(globalAtomGroupIndices[cg]);
1784             nsend_z++;
1785
1786             rvec posPbc;
1787             if (dd->ci[dim] == 0)
1788             {
1789                 /* Correct cg_cm for pbc */
1790                 rvec_add(cg_cm[cg], box[dim], posPbc);
1791                 if (bScrew)
1792                 {
1793                     posPbc[YY] = box[YY][YY] - posPbc[YY];
1794                     posPbc[ZZ] = box[ZZ][ZZ] - posPbc[ZZ];
1795                 }
1796             }
1797             else
1798             {
1799                 copy_rvec(cg_cm[cg], posPbc);
1800             }
1801             vbuf.emplace_back(posPbc[XX], posPbc[YY], posPbc[ZZ]);
1802
1803             nat += 1;
1804         }
1805     }
1806
1807     work->nat        = nat;
1808     work->nsend_zone = nsend_z;
1809 }
1810
1811 //! Clear data.
1812 static void clearCommSetupData(dd_comm_setup_work_t* work)
1813 {
1814     work->localAtomGroupBuffer.clear();
1815     work->atomGroupBuffer.clear();
1816     work->positionBuffer.clear();
1817     work->nat        = 0;
1818     work->nsend_zone = 0;
1819 }
1820
1821 //! Prepare DD communication.
1822 static void setup_dd_communication(gmx_domdec_t* dd, matrix box, gmx_ddbox_t* ddbox, t_forcerec* fr, t_state* state)
1823 {
1824     int                    dim_ind, dim, dim0, dim1, dim2, dimd, nat_tot;
1825     int                    nzone, nzone_send, zone, zonei, cg0, cg1;
1826     int                    c;
1827     int *                  zone_cg_range, pos_cg;
1828     gmx_domdec_comm_t*     comm;
1829     gmx_domdec_zones_t*    zones;
1830     gmx_domdec_comm_dim_t* cd;
1831     gmx_bool               bBondComm, bDist2B, bDistMB, bDistBonded;
1832     dd_corners_t           corners;
1833     rvec *                 normal, *v_d, *v_0 = nullptr, *v_1 = nullptr;
1834     real                   skew_fac2_d, skew_fac_01;
1835     rvec                   sf2_round;
1836
1837     if (debug)
1838     {
1839         fprintf(debug, "Setting up DD communication\n");
1840     }
1841
1842     comm = dd->comm;
1843
1844     if (comm->dth.empty())
1845     {
1846         /* Initialize the thread data.
1847          * This can not be done in init_domain_decomposition,
1848          * as the numbers of threads is determined later.
1849          */
1850         int numThreads = gmx_omp_nthreads_get(emntDomdec);
1851         comm->dth.resize(numThreads);
1852     }
1853
1854     bBondComm = comm->systemInfo.filterBondedCommunication;
1855
1856     /* Do we need to determine extra distances for multi-body bondeds? */
1857     bDistMB = (comm->systemInfo.haveInterDomainMultiBodyBondeds && isDlbOn(dd->comm) && dd->ndim > 1);
1858
1859     /* Do we need to determine extra distances for only two-body bondeds? */
1860     bDist2B = (bBondComm && !bDistMB);
1861
1862     const real r_comm2 =
1863             gmx::square(domainToDomainIntoAtomToDomainCutoff(comm->systemInfo, comm->systemInfo.cutoff));
1864     const real r_bcomm2 =
1865             gmx::square(domainToDomainIntoAtomToDomainCutoff(comm->systemInfo, comm->cutoff_mbody));
1866
1867     if (debug)
1868     {
1869         fprintf(debug, "bBondComm %s, r_bc %f\n", gmx::boolToString(bBondComm), std::sqrt(r_bcomm2));
1870     }
1871
1872     zones = &comm->zones;
1873
1874     dim0 = dd->dim[0];
1875     dim1 = (dd->ndim >= 2 ? dd->dim[1] : -1);
1876     dim2 = (dd->ndim >= 3 ? dd->dim[2] : -1);
1877
1878     set_dd_corners(dd, dim0, dim1, dim2, bDistMB, &corners);
1879
1880     /* Triclinic stuff */
1881     normal      = ddbox->normal;
1882     skew_fac_01 = 0;
1883     if (dd->ndim >= 2)
1884     {
1885         v_0 = ddbox->v[dim0];
1886         if (ddbox->tric_dir[dim0] && ddbox->tric_dir[dim1])
1887         {
1888             /* Determine the coupling coefficient for the distances
1889              * to the cell planes along dim0 and dim1 through dim2.
1890              * This is required for correct rounding.
1891              */
1892             skew_fac_01 = ddbox->v[dim0][dim1 + 1][dim0] * ddbox->v[dim1][dim1 + 1][dim1];
1893             if (debug)
1894             {
1895                 fprintf(debug, "\nskew_fac_01 %f\n", skew_fac_01);
1896             }
1897         }
1898     }
1899     if (dd->ndim >= 3)
1900     {
1901         v_1 = ddbox->v[dim1];
1902     }
1903
1904     zone_cg_range                        = zones->cg_range.data();
1905     gmx::ArrayRef<cginfo_mb_t> cginfo_mb = fr->cginfo_mb;
1906
1907     zone_cg_range[0]   = 0;
1908     zone_cg_range[1]   = dd->ncg_home;
1909     comm->zone_ncg1[0] = dd->ncg_home;
1910     pos_cg             = dd->ncg_home;
1911
1912     nat_tot = comm->atomRanges.numHomeAtoms();
1913     nzone   = 1;
1914     for (dim_ind = 0; dim_ind < dd->ndim; dim_ind++)
1915     {
1916         dim = dd->dim[dim_ind];
1917         cd  = &comm->cd[dim_ind];
1918
1919         /* Check if we need to compute triclinic distances along this dim */
1920         bool distanceIsTriclinic = false;
1921         for (int i = 0; i <= dim_ind; i++)
1922         {
1923             if (ddbox->tric_dir[dd->dim[i]])
1924             {
1925                 distanceIsTriclinic = true;
1926             }
1927         }
1928
1929         if (dim >= ddbox->npbcdim && dd->ci[dim] == 0)
1930         {
1931             /* No pbc in this dimension, the first node should not comm. */
1932             nzone_send = 0;
1933         }
1934         else
1935         {
1936             nzone_send = nzone;
1937         }
1938
1939         v_d         = ddbox->v[dim];
1940         skew_fac2_d = gmx::square(ddbox->skew_fac[dim]);
1941
1942         cd->receiveInPlace = true;
1943         for (int p = 0; p < cd->numPulses(); p++)
1944         {
1945             /* Only atoms communicated in the first pulse are used
1946              * for multi-body bonded interactions or for bBondComm.
1947              */
1948             bDistBonded = ((bDistMB || bDist2B) && p == 0);
1949
1950             gmx_domdec_ind_t* ind = &cd->ind[p];
1951
1952             /* Thread 0 writes in the global index array */
1953             ind->index.clear();
1954             clearCommSetupData(&comm->dth[0]);
1955
1956             for (zone = 0; zone < nzone_send; zone++)
1957             {
1958                 if (dim_ind > 0 && distanceIsTriclinic)
1959                 {
1960                     /* Determine slightly more optimized skew_fac's
1961                      * for rounding.
1962                      * This reduces the number of communicated atoms
1963                      * by about 10% for 3D DD of rhombic dodecahedra.
1964                      */
1965                     for (dimd = 0; dimd < dim; dimd++)
1966                     {
1967                         sf2_round[dimd] = 1;
1968                         if (ddbox->tric_dir[dimd])
1969                         {
1970                             for (int i = dd->dim[dimd] + 1; i < DIM; i++)
1971                             {
1972                                 /* If we are shifted in dimension i
1973                                  * and the cell plane is tilted forward
1974                                  * in dimension i, skip this coupling.
1975                                  */
1976                                 if (!(zones->shift[nzone + zone][i] && ddbox->v[dimd][i][dimd] >= 0))
1977                                 {
1978                                     sf2_round[dimd] += gmx::square(ddbox->v[dimd][i][dimd]);
1979                                 }
1980                             }
1981                             sf2_round[dimd] = 1 / sf2_round[dimd];
1982                         }
1983                     }
1984                 }
1985
1986                 zonei = zone_perm[dim_ind][zone];
1987                 if (p == 0)
1988                 {
1989                     /* Here we permutate the zones to obtain a convenient order
1990                      * for neighbor searching
1991                      */
1992                     cg0 = zone_cg_range[zonei];
1993                     cg1 = zone_cg_range[zonei + 1];
1994                 }
1995                 else
1996                 {
1997                     /* Look only at the cg's received in the previous grid pulse
1998                      */
1999                     cg1 = zone_cg_range[nzone + zone + 1];
2000                     cg0 = cg1 - cd->ind[p - 1].nrecv[zone];
2001                 }
2002
2003                 const int numThreads = gmx::ssize(comm->dth);
2004 #pragma omp parallel for num_threads(numThreads) schedule(static)
2005                 for (int th = 0; th < numThreads; th++)
2006                 {
2007                     try
2008                     {
2009                         dd_comm_setup_work_t& work = comm->dth[th];
2010
2011                         /* Retain data accumulated into buffers of thread 0 */
2012                         if (th > 0)
2013                         {
2014                             clearCommSetupData(&work);
2015                         }
2016
2017                         int cg0_th = cg0 + ((cg1 - cg0) * th) / numThreads;
2018                         int cg1_th = cg0 + ((cg1 - cg0) * (th + 1)) / numThreads;
2019
2020                         /* Get the cg's for this pulse in this zone */
2021                         get_zone_pulse_cgs(dd,
2022                                            zonei,
2023                                            zone,
2024                                            cg0_th,
2025                                            cg1_th,
2026                                            dd->globalAtomGroupIndices,
2027                                            dim,
2028                                            dim_ind,
2029                                            dim0,
2030                                            dim1,
2031                                            dim2,
2032                                            r_comm2,
2033                                            r_bcomm2,
2034                                            box,
2035                                            distanceIsTriclinic,
2036                                            normal,
2037                                            skew_fac2_d,
2038                                            skew_fac_01,
2039                                            v_d,
2040                                            v_0,
2041                                            v_1,
2042                                            &corners,
2043                                            sf2_round,
2044                                            bDistBonded,
2045                                            bBondComm,
2046                                            bDist2B,
2047                                            bDistMB,
2048                                            state->x.rvec_array(),
2049                                            fr->cginfo,
2050                                            th == 0 ? &ind->index : &work.localAtomGroupBuffer,
2051                                            &work);
2052                     }
2053                     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
2054                 } // END
2055
2056                 std::vector<int>&       atomGroups = comm->dth[0].atomGroupBuffer;
2057                 std::vector<gmx::RVec>& positions  = comm->dth[0].positionBuffer;
2058                 ind->nsend[zone]                   = comm->dth[0].nsend_zone;
2059                 /* Append data of threads>=1 to the communication buffers */
2060                 for (int th = 1; th < numThreads; th++)
2061                 {
2062                     const dd_comm_setup_work_t& dth = comm->dth[th];
2063
2064                     ind->index.insert(ind->index.end(),
2065                                       dth.localAtomGroupBuffer.begin(),
2066                                       dth.localAtomGroupBuffer.end());
2067                     atomGroups.insert(
2068                             atomGroups.end(), dth.atomGroupBuffer.begin(), dth.atomGroupBuffer.end());
2069                     positions.insert(
2070                             positions.end(), dth.positionBuffer.begin(), dth.positionBuffer.end());
2071                     comm->dth[0].nat += dth.nat;
2072                     ind->nsend[zone] += dth.nsend_zone;
2073                 }
2074             }
2075             /* Clear the counts in case we do not have pbc */
2076             for (zone = nzone_send; zone < nzone; zone++)
2077             {
2078                 ind->nsend[zone] = 0;
2079             }
2080             ind->nsend[nzone]     = ind->index.size();
2081             ind->nsend[nzone + 1] = comm->dth[0].nat;
2082             /* Communicate the number of cg's and atoms to receive */
2083             ddSendrecv(dd, dim_ind, dddirBackward, ind->nsend, nzone + 2, ind->nrecv, nzone + 2);
2084
2085             if (p > 0)
2086             {
2087                 /* We can receive in place if only the last zone is not empty */
2088                 for (zone = 0; zone < nzone - 1; zone++)
2089                 {
2090                     if (ind->nrecv[zone] > 0)
2091                     {
2092                         cd->receiveInPlace = false;
2093                     }
2094                 }
2095             }
2096
2097             int receiveBufferSize = 0;
2098             if (!cd->receiveInPlace)
2099             {
2100                 receiveBufferSize = ind->nrecv[nzone];
2101             }
2102             /* These buffer are actually only needed with in-place */
2103             DDBufferAccess<int>       globalAtomGroupBuffer(comm->intBuffer, receiveBufferSize);
2104             DDBufferAccess<gmx::RVec> rvecBuffer(comm->rvecBuffer, receiveBufferSize);
2105
2106             dd_comm_setup_work_t& work = comm->dth[0];
2107
2108             /* Make space for the global cg indices */
2109             int numAtomGroupsNew = pos_cg + ind->nrecv[nzone];
2110             dd->globalAtomGroupIndices.resize(numAtomGroupsNew);
2111             /* Communicate the global cg indices */
2112             gmx::ArrayRef<int> integerBufferRef;
2113             if (cd->receiveInPlace)
2114             {
2115                 integerBufferRef = gmx::arrayRefFromArray(
2116                         dd->globalAtomGroupIndices.data() + pos_cg, ind->nrecv[nzone]);
2117             }
2118             else
2119             {
2120                 integerBufferRef = globalAtomGroupBuffer.buffer;
2121             }
2122             ddSendrecv<int>(dd, dim_ind, dddirBackward, work.atomGroupBuffer, integerBufferRef);
2123
2124             /* Make space for cg_cm */
2125             dd_resize_atominfo_and_state(fr, state, pos_cg + ind->nrecv[nzone]);
2126
2127             /* Communicate the coordinates */
2128             gmx::ArrayRef<gmx::RVec> rvecBufferRef;
2129             if (cd->receiveInPlace)
2130             {
2131                 rvecBufferRef = gmx::makeArrayRef(state->x).subArray(pos_cg, ind->nrecv[nzone]);
2132             }
2133             else
2134             {
2135                 rvecBufferRef = rvecBuffer.buffer;
2136             }
2137             ddSendrecv<gmx::RVec>(dd, dim_ind, dddirBackward, work.positionBuffer, rvecBufferRef);
2138
2139             /* Make the charge group index */
2140             if (cd->receiveInPlace)
2141             {
2142                 zone = (p == 0 ? 0 : nzone - 1);
2143                 while (zone < nzone)
2144                 {
2145                     for (int i = 0; i < ind->nrecv[zone]; i++)
2146                     {
2147                         int globalAtomIndex = dd->globalAtomGroupIndices[pos_cg];
2148                         fr->cginfo[pos_cg]  = ddcginfo(cginfo_mb, globalAtomIndex);
2149                         pos_cg++;
2150                     }
2151                     if (p == 0)
2152                     {
2153                         comm->zone_ncg1[nzone + zone] = ind->nrecv[zone];
2154                     }
2155                     zone++;
2156                     zone_cg_range[nzone + zone] = pos_cg;
2157                 }
2158             }
2159             else
2160             {
2161                 /* This part of the code is never executed with bBondComm. */
2162                 merge_cg_buffers(nzone,
2163                                  cd,
2164                                  p,
2165                                  zone_cg_range,
2166                                  dd->globalAtomGroupIndices,
2167                                  integerBufferRef.data(),
2168                                  state->x,
2169                                  rvecBufferRef,
2170                                  fr->cginfo_mb,
2171                                  fr->cginfo);
2172                 pos_cg += ind->nrecv[nzone];
2173             }
2174             nat_tot += ind->nrecv[nzone + 1];
2175         }
2176         if (!cd->receiveInPlace)
2177         {
2178             /* Store the atom block for easy copying of communication buffers */
2179             make_cell2at_index(cd, nzone, zone_cg_range[nzone]);
2180         }
2181         nzone += nzone;
2182     }
2183
2184     comm->atomRanges.setEnd(DDAtomRanges::Type::Zones, nat_tot);
2185
2186     if (!bBondComm)
2187     {
2188         /* We don't need to update cginfo, since that was alrady done above.
2189          * So we pass NULL for the forcerec.
2190          */
2191         dd_set_cginfo(dd->globalAtomGroupIndices, dd->ncg_home, dd->globalAtomGroupIndices.size(), nullptr);
2192     }
2193
2194     if (debug)
2195     {
2196         fprintf(debug, "Finished setting up DD communication, zones:");
2197         for (c = 0; c < zones->n; c++)
2198         {
2199             fprintf(debug, " %d", zones->cg_range[c + 1] - zones->cg_range[c]);
2200         }
2201         fprintf(debug, "\n");
2202     }
2203 }
2204
2205 //! Set boundaries for the charge group range.
2206 static void set_cg_boundaries(gmx_domdec_zones_t* zones)
2207 {
2208     for (auto& iZone : zones->iZones)
2209     {
2210         iZone.iAtomRange = gmx::Range<int>(0, zones->cg_range[iZone.iZoneIndex + 1]);
2211         iZone.jAtomRange = gmx::Range<int>(zones->cg_range[iZone.jZoneRange.begin()],
2212                                            zones->cg_range[iZone.jZoneRange.end()]);
2213     }
2214 }
2215
2216 /*! \brief Set zone dimensions for zones \p zone_start to \p zone_end-1
2217  *
2218  * Also sets the atom density for the home zone when \p zone_start=0.
2219  * For this \p numMovedChargeGroupsInHomeZone needs to be passed to tell
2220  * how many charge groups will move but are still part of the current range.
2221  * \todo When converting domdec to use proper classes, all these variables
2222  *       should be private and a method should return the correct count
2223  *       depending on an internal state.
2224  *
2225  * \param[in,out] dd          The domain decomposition struct
2226  * \param[in]     box         The box
2227  * \param[in]     ddbox       The domain decomposition box struct
2228  * \param[in]     zone_start  The start of the zone range to set sizes for
2229  * \param[in]     zone_end    The end of the zone range to set sizes for
2230  * \param[in]     numMovedChargeGroupsInHomeZone  The number of charge groups in the home zone that should moved but are still present in dd->comm->zones.cg_range
2231  */
2232 static void set_zones_size(gmx_domdec_t*      dd,
2233                            matrix             box,
2234                            const gmx_ddbox_t* ddbox,
2235                            int                zone_start,
2236                            int                zone_end,
2237                            int                numMovedChargeGroupsInHomeZone)
2238 {
2239     gmx_domdec_comm_t*  comm;
2240     gmx_domdec_zones_t* zones;
2241     gmx_bool            bDistMB;
2242     int                 z, d, dim;
2243     real                rcs, rcmbs;
2244     int                 i, j;
2245     real                vol;
2246
2247     comm = dd->comm;
2248
2249     zones = &comm->zones;
2250
2251     /* Do we need to determine extra distances for multi-body bondeds? */
2252     bDistMB = (comm->systemInfo.haveInterDomainMultiBodyBondeds && isDlbOn(dd->comm) && dd->ndim > 1);
2253
2254     for (z = zone_start; z < zone_end; z++)
2255     {
2256         /* Copy cell limits to zone limits.
2257          * Valid for non-DD dims and non-shifted dims.
2258          */
2259         copy_rvec(comm->cell_x0, zones->size[z].x0);
2260         copy_rvec(comm->cell_x1, zones->size[z].x1);
2261     }
2262
2263     for (d = 0; d < dd->ndim; d++)
2264     {
2265         dim = dd->dim[d];
2266
2267         for (z = 0; z < zones->n; z++)
2268         {
2269             /* With a staggered grid we have different sizes
2270              * for non-shifted dimensions.
2271              */
2272             if (isDlbOn(dd->comm) && zones->shift[z][dim] == 0)
2273             {
2274                 if (d == 1)
2275                 {
2276                     zones->size[z].x0[dim] = comm->zone_d1[zones->shift[z][dd->dim[d - 1]]].min0;
2277                     zones->size[z].x1[dim] = comm->zone_d1[zones->shift[z][dd->dim[d - 1]]].max1;
2278                 }
2279                 else if (d == 2)
2280                 {
2281                     zones->size[z].x0[dim] =
2282                             comm->zone_d2[zones->shift[z][dd->dim[d - 2]]][zones->shift[z][dd->dim[d - 1]]]
2283                                     .min0;
2284                     zones->size[z].x1[dim] =
2285                             comm->zone_d2[zones->shift[z][dd->dim[d - 2]]][zones->shift[z][dd->dim[d - 1]]]
2286                                     .max1;
2287                 }
2288             }
2289         }
2290
2291         rcs   = comm->systemInfo.cutoff;
2292         rcmbs = comm->cutoff_mbody;
2293         if (ddbox->tric_dir[dim])
2294         {
2295             rcs /= ddbox->skew_fac[dim];
2296             rcmbs /= ddbox->skew_fac[dim];
2297         }
2298
2299         /* Set the lower limit for the shifted zone dimensions */
2300         for (z = zone_start; z < zone_end; z++)
2301         {
2302             if (zones->shift[z][dim] > 0)
2303             {
2304                 dim = dd->dim[d];
2305                 if (!isDlbOn(dd->comm) || d == 0)
2306                 {
2307                     zones->size[z].x0[dim] = comm->cell_x1[dim];
2308                     zones->size[z].x1[dim] = comm->cell_x1[dim] + rcs;
2309                 }
2310                 else
2311                 {
2312                     /* Here we take the lower limit of the zone from
2313                      * the lowest domain of the zone below.
2314                      */
2315                     if (z < 4)
2316                     {
2317                         zones->size[z].x0[dim] = comm->zone_d1[zones->shift[z][dd->dim[d - 1]]].min1;
2318                     }
2319                     else
2320                     {
2321                         if (d == 1)
2322                         {
2323                             zones->size[z].x0[dim] = zones->size[zone_perm[2][z - 4]].x0[dim];
2324                         }
2325                         else
2326                         {
2327                             zones->size[z].x0[dim] =
2328                                     comm->zone_d2[zones->shift[z][dd->dim[d - 2]]][zones->shift[z][dd->dim[d - 1]]]
2329                                             .min1;
2330                         }
2331                     }
2332                     /* A temporary limit, is updated below */
2333                     zones->size[z].x1[dim] = zones->size[z].x0[dim];
2334
2335                     if (bDistMB)
2336                     {
2337                         for (size_t zi = 0; zi < zones->iZones.size(); zi++)
2338                         {
2339                             if (zones->shift[zi][dim] == 0)
2340                             {
2341                                 /* This takes the whole zone into account.
2342                                  * With multiple pulses this will lead
2343                                  * to a larger zone then strictly necessary.
2344                                  */
2345                                 zones->size[z].x1[dim] = std::max(zones->size[z].x1[dim],
2346                                                                   zones->size[zi].x1[dim] + rcmbs);
2347                             }
2348                         }
2349                     }
2350                 }
2351             }
2352         }
2353
2354         /* Loop over the i-zones to set the upper limit of each
2355          * j-zone they see.
2356          */
2357         for (const auto& iZone : zones->iZones)
2358         {
2359             const int zi = iZone.iZoneIndex;
2360             if (zones->shift[zi][dim] == 0)
2361             {
2362                 /* We should only use zones up to zone_end */
2363                 const auto& jZoneRangeFull = iZone.jZoneRange;
2364                 if (zone_end <= *jZoneRangeFull.begin())
2365                 {
2366                     continue;
2367                 }
2368                 const gmx::Range<int> jZoneRange(*jZoneRangeFull.begin(),
2369                                                  std::min(*jZoneRangeFull.end(), zone_end));
2370                 for (int jZone : jZoneRange)
2371                 {
2372                     if (zones->shift[jZone][dim] > 0)
2373                     {
2374                         zones->size[jZone].x1[dim] =
2375                                 std::max(zones->size[jZone].x1[dim], zones->size[zi].x1[dim] + rcs);
2376                     }
2377                 }
2378             }
2379         }
2380     }
2381
2382     for (z = zone_start; z < zone_end; z++)
2383     {
2384         /* Initialization only required to keep the compiler happy */
2385         rvec corner_min = { 0, 0, 0 }, corner_max = { 0, 0, 0 }, corner;
2386         int  nc, c;
2387
2388         /* To determine the bounding box for a zone we need to find
2389          * the extreme corners of 4, 2 or 1 corners.
2390          */
2391         nc = 1 << (ddbox->nboundeddim - 1);
2392
2393         for (c = 0; c < nc; c++)
2394         {
2395             /* Set up a zone corner at x=0, ignoring trilinic couplings */
2396             corner[XX] = 0;
2397             if ((c & 1) == 0)
2398             {
2399                 corner[YY] = zones->size[z].x0[YY];
2400             }
2401             else
2402             {
2403                 corner[YY] = zones->size[z].x1[YY];
2404             }
2405             if ((c & 2) == 0)
2406             {
2407                 corner[ZZ] = zones->size[z].x0[ZZ];
2408             }
2409             else
2410             {
2411                 corner[ZZ] = zones->size[z].x1[ZZ];
2412             }
2413             if (dd->ndim == 1 && dd->dim[0] < ZZ && ZZ < dd->unitCellInfo.npbcdim
2414                 && box[ZZ][1 - dd->dim[0]] != 0)
2415             {
2416                 /* With 1D domain decomposition the cg's are not in
2417                  * the triclinic box, but triclinic x-y and rectangular y/x-z.
2418                  * Shift the corner of the z-vector back to along the box
2419                  * vector of dimension d, so it will later end up at 0 along d.
2420                  * This can affect the location of this corner along dd->dim[0]
2421                  * through the matrix operation below if box[d][dd->dim[0]]!=0.
2422                  */
2423                 int d = 1 - dd->dim[0];
2424
2425                 corner[d] -= corner[ZZ] * box[ZZ][d] / box[ZZ][ZZ];
2426             }
2427             /* Apply the triclinic couplings */
2428             for (i = YY; i < ddbox->npbcdim && i < DIM; i++)
2429             {
2430                 for (j = XX; j < i; j++)
2431                 {
2432                     corner[j] += corner[i] * box[i][j] / box[i][i];
2433                 }
2434             }
2435             if (c == 0)
2436             {
2437                 copy_rvec(corner, corner_min);
2438                 copy_rvec(corner, corner_max);
2439             }
2440             else
2441             {
2442                 for (i = 0; i < DIM; i++)
2443                 {
2444                     corner_min[i] = std::min(corner_min[i], corner[i]);
2445                     corner_max[i] = std::max(corner_max[i], corner[i]);
2446                 }
2447             }
2448         }
2449         /* Copy the extreme cornes without offset along x */
2450         for (i = 0; i < DIM; i++)
2451         {
2452             zones->size[z].bb_x0[i] = corner_min[i];
2453             zones->size[z].bb_x1[i] = corner_max[i];
2454         }
2455         /* Add the offset along x */
2456         zones->size[z].bb_x0[XX] += zones->size[z].x0[XX];
2457         zones->size[z].bb_x1[XX] += zones->size[z].x1[XX];
2458     }
2459
2460     if (zone_start == 0)
2461     {
2462         vol = 1;
2463         for (dim = 0; dim < DIM; dim++)
2464         {
2465             vol *= zones->size[0].x1[dim] - zones->size[0].x0[dim];
2466         }
2467         zones->dens_zone0 =
2468                 (zones->cg_range[1] - zones->cg_range[0] - numMovedChargeGroupsInHomeZone) / vol;
2469     }
2470
2471     if (debug)
2472     {
2473         for (z = zone_start; z < zone_end; z++)
2474         {
2475             fprintf(debug,
2476                     "zone %d    %6.3f - %6.3f  %6.3f - %6.3f  %6.3f - %6.3f\n",
2477                     z,
2478                     zones->size[z].x0[XX],
2479                     zones->size[z].x1[XX],
2480                     zones->size[z].x0[YY],
2481                     zones->size[z].x1[YY],
2482                     zones->size[z].x0[ZZ],
2483                     zones->size[z].x1[ZZ]);
2484             fprintf(debug,
2485                     "zone %d bb %6.3f - %6.3f  %6.3f - %6.3f  %6.3f - %6.3f\n",
2486                     z,
2487                     zones->size[z].bb_x0[XX],
2488                     zones->size[z].bb_x1[XX],
2489                     zones->size[z].bb_x0[YY],
2490                     zones->size[z].bb_x1[YY],
2491                     zones->size[z].bb_x0[ZZ],
2492                     zones->size[z].bb_x1[ZZ]);
2493         }
2494     }
2495 }
2496
2497 /*! \brief Order data in \p dataToSort according to \p sort
2498  *
2499  * Note: both buffers should have at least \p sort.size() elements.
2500  */
2501 template<typename T>
2502 static void orderVector(gmx::ArrayRef<const gmx_cgsort_t> sort,
2503                         gmx::ArrayRef<T>                  dataToSort,
2504                         gmx::ArrayRef<T>                  sortBuffer)
2505 {
2506     GMX_ASSERT(dataToSort.size() >= sort.size(), "The vector needs to be sufficiently large");
2507     GMX_ASSERT(sortBuffer.size() >= sort.size(),
2508                "The sorting buffer needs to be sufficiently large");
2509
2510     /* Order the data into the temporary buffer */
2511     size_t i = 0;
2512     for (const gmx_cgsort_t& entry : sort)
2513     {
2514         sortBuffer[i++] = dataToSort[entry.ind];
2515     }
2516
2517     /* Copy back to the original array */
2518     std::copy(sortBuffer.begin(), sortBuffer.begin() + sort.size(), dataToSort.begin());
2519 }
2520
2521 /*! \brief Order data in \p dataToSort according to \p sort
2522  *
2523  * Note: \p vectorToSort should have at least \p sort.size() elements,
2524  *       \p workVector is resized when it is too small.
2525  */
2526 template<typename T>
2527 static void orderVector(gmx::ArrayRef<const gmx_cgsort_t> sort,
2528                         gmx::ArrayRef<T>                  vectorToSort,
2529                         std::vector<T>*                   workVector)
2530 {
2531     if (gmx::index(workVector->size()) < sort.ssize())
2532     {
2533         workVector->resize(sort.size());
2534     }
2535     orderVector<T>(sort, vectorToSort, *workVector);
2536 }
2537
2538 //! Returns the sorting order for atoms based on the nbnxn grid order in sort
2539 static void dd_sort_order_nbnxn(const t_forcerec* fr, std::vector<gmx_cgsort_t>* sort)
2540 {
2541     gmx::ArrayRef<const int> atomOrder = fr->nbv->getLocalAtomOrder();
2542
2543     /* Using push_back() instead of this resize results in much slower code */
2544     sort->resize(atomOrder.size());
2545     gmx::ArrayRef<gmx_cgsort_t> buffer    = *sort;
2546     size_t                      numSorted = 0;
2547     for (int i : atomOrder)
2548     {
2549         if (i >= 0)
2550         {
2551             /* The values of nsc and ind_gl are not used in this case */
2552             buffer[numSorted++].ind = i;
2553         }
2554     }
2555     sort->resize(numSorted);
2556 }
2557
2558 //! Returns the sorting state for DD.
2559 static void dd_sort_state(gmx_domdec_t* dd, t_forcerec* fr, t_state* state)
2560 {
2561     gmx_domdec_sort_t* sort = dd->comm->sort.get();
2562
2563     dd_sort_order_nbnxn(fr, &sort->sorted);
2564
2565     /* We alloc with the old size, since cgindex is still old */
2566     DDBufferAccess<gmx::RVec> rvecBuffer(dd->comm->rvecBuffer, dd->ncg_home);
2567
2568     /* Set the new home atom/charge group count */
2569     dd->ncg_home = sort->sorted.size();
2570     if (debug)
2571     {
2572         fprintf(debug, "Set the new home atom count to %d\n", dd->ncg_home);
2573     }
2574
2575     /* Reorder the state */
2576     gmx::ArrayRef<const gmx_cgsort_t> cgsort = sort->sorted;
2577     GMX_RELEASE_ASSERT(cgsort.ssize() == dd->ncg_home, "We should sort all the home atom groups");
2578
2579     if (state->flags & enumValueToBitMask(StateEntry::X))
2580     {
2581         orderVector(cgsort, makeArrayRef(state->x), rvecBuffer.buffer);
2582     }
2583     if (state->flags & enumValueToBitMask(StateEntry::V))
2584     {
2585         orderVector(cgsort, makeArrayRef(state->v), rvecBuffer.buffer);
2586     }
2587     if (state->flags & enumValueToBitMask(StateEntry::Cgp))
2588     {
2589         orderVector(cgsort, makeArrayRef(state->cg_p), rvecBuffer.buffer);
2590     }
2591
2592     /* Reorder the global cg index */
2593     orderVector<int>(cgsort, dd->globalAtomGroupIndices, &sort->intBuffer);
2594     /* Reorder the cginfo */
2595     orderVector<int>(cgsort, fr->cginfo, &sort->intBuffer);
2596     /* Set the home atom number */
2597     dd->comm->atomRanges.setEnd(DDAtomRanges::Type::Home, dd->ncg_home);
2598
2599     /* The atoms are now exactly in grid order, update the grid order */
2600     fr->nbv->setLocalAtomOrder();
2601 }
2602
2603 //! Accumulates load statistics.
2604 static void add_dd_statistics(gmx_domdec_t* dd)
2605 {
2606     gmx_domdec_comm_t* comm = dd->comm;
2607
2608     for (int i = 0; i < static_cast<int>(DDAtomRanges::Type::Number); i++)
2609     {
2610         auto range = static_cast<DDAtomRanges::Type>(i);
2611         comm->sum_nat[i] += comm->atomRanges.end(range) - comm->atomRanges.start(range);
2612     }
2613     comm->ndecomp++;
2614 }
2615
2616 void reset_dd_statistics_counters(gmx_domdec_t* dd)
2617 {
2618     gmx_domdec_comm_t* comm = dd->comm;
2619
2620     /* Reset all the statistics and counters for total run counting */
2621     for (int i = 0; i < static_cast<int>(DDAtomRanges::Type::Number); i++)
2622     {
2623         comm->sum_nat[i] = 0;
2624     }
2625     comm->ndecomp   = 0;
2626     comm->nload     = 0;
2627     comm->load_step = 0;
2628     comm->load_sum  = 0;
2629     comm->load_max  = 0;
2630     clear_ivec(comm->load_lim);
2631     comm->load_mdf = 0;
2632     comm->load_pme = 0;
2633 }
2634
2635 namespace gmx
2636 {
2637
2638 bool check_grid_jump(int64_t step, const gmx_domdec_t* dd, real cutoff, const gmx_ddbox_t* ddbox, bool bFatal)
2639 {
2640     gmx_domdec_comm_t* comm    = dd->comm;
2641     bool               invalid = false;
2642
2643     for (int d = 1; d < dd->ndim; d++)
2644     {
2645         const DDCellsizesWithDlb& cellsizes = comm->cellsizesWithDlb[d];
2646         const int                 dim       = dd->dim[d];
2647         const real                limit     = grid_jump_limit(comm, cutoff, d);
2648         real                      bfac      = ddbox->box_size[dim];
2649         if (ddbox->tric_dir[dim])
2650         {
2651             bfac *= ddbox->skew_fac[dim];
2652         }
2653         if ((cellsizes.fracUpper - cellsizes.fracLowerMax) * bfac < limit
2654             || (cellsizes.fracLower - cellsizes.fracUpperMin) * bfac > -limit)
2655         {
2656             invalid = true;
2657
2658             if (bFatal)
2659             {
2660                 char buf[22];
2661
2662                 /* This error should never be triggered under normal
2663                  * circumstances, but you never know ...
2664                  */
2665                 gmx_fatal(FARGS,
2666                           "step %s: The domain decomposition grid has shifted too much in the "
2667                           "%c-direction around cell %d %d %d. This should not have happened. "
2668                           "Running with fewer ranks might avoid this issue.",
2669                           gmx_step_str(step, buf),
2670                           dim2char(dim),
2671                           dd->ci[XX],
2672                           dd->ci[YY],
2673                           dd->ci[ZZ]);
2674             }
2675         }
2676     }
2677
2678     return invalid;
2679 }
2680
2681 void print_dd_statistics(const t_commrec* cr, const t_inputrec& inputrec, FILE* fplog)
2682 {
2683     gmx_domdec_comm_t* comm = cr->dd->comm;
2684
2685     const int numRanges = static_cast<int>(DDAtomRanges::Type::Number);
2686     gmx_sumd(numRanges, comm->sum_nat, cr);
2687
2688     if (fplog == nullptr)
2689     {
2690         return;
2691     }
2692
2693     fprintf(fplog, "\n    D O M A I N   D E C O M P O S I T I O N   S T A T I S T I C S\n\n");
2694
2695     for (int i = static_cast<int>(DDAtomRanges::Type::Zones); i < numRanges; i++)
2696     {
2697         auto   range = static_cast<DDAtomRanges::Type>(i);
2698         double av    = comm->sum_nat[i] / comm->ndecomp;
2699         switch (range)
2700         {
2701             case DDAtomRanges::Type::Zones:
2702                 fprintf(fplog, " av. #atoms communicated per step for force:  %d x %.1f\n", 2, av);
2703                 break;
2704             case DDAtomRanges::Type::Vsites:
2705                 if (cr->dd->vsite_comm)
2706                 {
2707                     fprintf(fplog,
2708                             " av. #atoms communicated per step for vsites: %d x %.1f\n",
2709                             (EEL_PME(inputrec.coulombtype)
2710                              || inputrec.coulombtype == CoulombInteractionType::Ewald)
2711                                     ? 3
2712                                     : 2,
2713                             av);
2714                 }
2715                 break;
2716             case DDAtomRanges::Type::Constraints:
2717                 if (cr->dd->constraint_comm)
2718                 {
2719                     fprintf(fplog,
2720                             " av. #atoms communicated per step for LINCS:  %d x %.1f\n",
2721                             1 + inputrec.nLincsIter,
2722                             av);
2723                 }
2724                 break;
2725             default: gmx_incons(" Unknown type for DD statistics");
2726         }
2727     }
2728     fprintf(fplog, "\n");
2729
2730     if (comm->ddSettings.recordLoad && EI_DYNAMICS(inputrec.eI))
2731     {
2732         print_dd_load_av(fplog, cr->dd);
2733     }
2734 }
2735
2736 //!\brief TODO Remove fplog when group scheme and charge groups are gone
2737 void dd_partition_system(FILE*                     fplog,
2738                          const gmx::MDLogger&      mdlog,
2739                          int64_t                   step,
2740                          const t_commrec*          cr,
2741                          bool                      bMasterState,
2742                          int                       nstglobalcomm,
2743                          t_state*                  state_global,
2744                          const gmx_mtop_t&         top_global,
2745                          const t_inputrec&         inputrec,
2746                          gmx::ImdSession*          imdSession,
2747                          pull_t*                   pull_work,
2748                          t_state*                  state_local,
2749                          gmx::ForceBuffers*        f,
2750                          gmx::MDAtoms*             mdAtoms,
2751                          gmx_localtop_t*           top_local,
2752                          t_forcerec*               fr,
2753                          gmx::VirtualSitesHandler* vsite,
2754                          gmx::Constraints*         constr,
2755                          t_nrnb*                   nrnb,
2756                          gmx_wallcycle*            wcycle,
2757                          bool                      bVerbose)
2758 {
2759     gmx_ddbox_t ddbox = { 0 };
2760     int         ncgindex_set;
2761     char        sbuf[22];
2762
2763     wallcycle_start(wcycle, ewcDOMDEC);
2764
2765     gmx_domdec_t*      dd   = cr->dd;
2766     gmx_domdec_comm_t* comm = dd->comm;
2767
2768     // TODO if the update code becomes accessible here, use
2769     // upd->deform for this logic.
2770     bool bBoxChanged = (bMasterState || inputrecDeform(&inputrec));
2771     if (inputrec.epc != PressureCoupling::No)
2772     {
2773         /* With nstpcouple > 1 pressure coupling happens.
2774          * one step after calculating the pressure.
2775          * Box scaling happens at the end of the MD step,
2776          * after the DD partitioning.
2777          * We therefore have to do DLB in the first partitioning
2778          * after an MD step where P-coupling occurred.
2779          * We need to determine the last step in which p-coupling occurred.
2780          * MRS -- need to validate this for vv?
2781          */
2782         int     n = inputrec.nstpcouple;
2783         int64_t step_pcoupl;
2784         if (n == 1)
2785         {
2786             step_pcoupl = step - 1;
2787         }
2788         else
2789         {
2790             step_pcoupl = ((step - 1) / n) * n + 1;
2791         }
2792         if (step_pcoupl >= comm->partition_step)
2793         {
2794             bBoxChanged = true;
2795         }
2796     }
2797
2798     bool bNStGlobalComm = (step % nstglobalcomm == 0);
2799     bool bDoDLB;
2800     if (!isDlbOn(comm))
2801     {
2802         bDoDLB = false;
2803     }
2804     else
2805     {
2806         /* Should we do dynamic load balacing this step?
2807          * Since it requires (possibly expensive) global communication,
2808          * we might want to do DLB less frequently.
2809          */
2810         if (bBoxChanged || inputrec.epc != PressureCoupling::No)
2811         {
2812             bDoDLB = bBoxChanged;
2813         }
2814         else
2815         {
2816             bDoDLB = bNStGlobalComm;
2817         }
2818     }
2819
2820     /* Check if we have recorded loads on the nodes */
2821     if (comm->ddSettings.recordLoad && dd_load_count(comm) > 0)
2822     {
2823         bool bCheckWhetherToTurnDlbOn = dd_dlb_get_should_check_whether_to_turn_dlb_on(dd);
2824
2825         /* Print load every nstlog, first and last step to the log file */
2826         bool bLogLoad = ((inputrec.nstlog > 0 && step % inputrec.nstlog == 0) || comm->n_load_collect == 0
2827                          || (inputrec.nsteps >= 0
2828                              && (step + inputrec.nstlist > inputrec.init_step + inputrec.nsteps)));
2829
2830         /* Avoid extra communication due to verbose screen output
2831          * when nstglobalcomm is set.
2832          */
2833         if (bDoDLB || bLogLoad || bCheckWhetherToTurnDlbOn
2834             || (bVerbose && (inputrec.nstlist == 0 || nstglobalcomm <= inputrec.nstlist)))
2835         {
2836             get_load_distribution(dd, wcycle);
2837             if (DDMASTER(dd))
2838             {
2839                 if (bLogLoad)
2840                 {
2841                     GMX_LOG(mdlog.info).asParagraph().appendText(dd_print_load(dd, step - 1));
2842                 }
2843                 if (bVerbose)
2844                 {
2845                     dd_print_load_verbose(dd);
2846                 }
2847             }
2848             comm->n_load_collect++;
2849
2850             if (isDlbOn(comm))
2851             {
2852                 if (DDMASTER(dd))
2853                 {
2854                     /* Add the measured cycles to the running average */
2855                     const float averageFactor = 0.1F;
2856                     comm->cyclesPerStepDlbExpAverage =
2857                             (1 - averageFactor) * comm->cyclesPerStepDlbExpAverage
2858                             + averageFactor * comm->cycl[ddCyclStep] / comm->cycl_n[ddCyclStep];
2859                 }
2860                 if (comm->dlbState == DlbState::onCanTurnOff
2861                     && dd->comm->n_load_have % c_checkTurnDlbOffInterval == c_checkTurnDlbOffInterval - 1)
2862                 {
2863                     bool turnOffDlb;
2864                     if (DDMASTER(dd))
2865                     {
2866                         /* If the running averaged cycles with DLB are more
2867                          * than before we turned on DLB, turn off DLB.
2868                          * We will again run and check the cycles without DLB
2869                          * and we can then decide if to turn off DLB forever.
2870                          */
2871                         turnOffDlb = (comm->cyclesPerStepDlbExpAverage > comm->cyclesPerStepBeforeDLB);
2872                     }
2873                     dd_bcast(dd, sizeof(turnOffDlb), &turnOffDlb);
2874                     if (turnOffDlb)
2875                     {
2876                         /* To turn off DLB, we need to redistribute the atoms */
2877                         dd_collect_state(dd, state_local, state_global);
2878                         bMasterState = true;
2879                         turn_off_dlb(mdlog, dd, step);
2880                     }
2881                 }
2882             }
2883             else if (bCheckWhetherToTurnDlbOn)
2884             {
2885                 bool turnOffDlbForever = false;
2886                 bool turnOnDlb         = false;
2887
2888                 /* Since the timings are node dependent, the master decides */
2889                 if (DDMASTER(dd))
2890                 {
2891                     /* If we recently turned off DLB, we want to check if
2892                      * performance is better without DLB. We want to do this
2893                      * ASAP to minimize the chance that external factors
2894                      * slowed down the DLB step are gone here and we
2895                      * incorrectly conclude that DLB was causing the slowdown.
2896                      * So we measure one nstlist block, no running average.
2897                      */
2898                     if (comm->haveTurnedOffDlb
2899                         && comm->cycl[ddCyclStep] / comm->cycl_n[ddCyclStep] < comm->cyclesPerStepDlbExpAverage)
2900                     {
2901                         /* After turning off DLB we ran nstlist steps in fewer
2902                          * cycles than with DLB. This likely means that DLB
2903                          * in not benefical, but this could be due to a one
2904                          * time unlucky fluctuation, so we require two such
2905                          * observations in close succession to turn off DLB
2906                          * forever.
2907                          */
2908                         if (comm->dlbSlowerPartitioningCount > 0
2909                             && dd->ddp_count < comm->dlbSlowerPartitioningCount + 10 * c_checkTurnDlbOnInterval)
2910                         {
2911                             turnOffDlbForever = true;
2912                         }
2913                         comm->haveTurnedOffDlb = false;
2914                         /* Register when we last measured DLB slowdown */
2915                         comm->dlbSlowerPartitioningCount = dd->ddp_count;
2916                     }
2917                     else
2918                     {
2919                         /* Here we check if the max PME rank load is more than 0.98
2920                          * the max PP force load. If so, PP DLB will not help,
2921                          * since we are (almost) limited by PME. Furthermore,
2922                          * DLB will cause a significant extra x/f redistribution
2923                          * cost on the PME ranks, which will then surely result
2924                          * in lower total performance.
2925                          */
2926                         if (comm->ddRankSetup.usePmeOnlyRanks && dd_pme_f_ratio(dd) > 1 - DD_PERF_LOSS_DLB_ON)
2927                         {
2928                             turnOnDlb = false;
2929                         }
2930                         else
2931                         {
2932                             turnOnDlb = (dd_force_imb_perf_loss(dd) >= DD_PERF_LOSS_DLB_ON);
2933                         }
2934                     }
2935                 }
2936                 struct
2937                 {
2938                     bool turnOffDlbForever;
2939                     bool turnOnDlb;
2940                 } bools{ turnOffDlbForever, turnOnDlb };
2941                 dd_bcast(dd, sizeof(bools), &bools);
2942                 if (bools.turnOffDlbForever)
2943                 {
2944                     turn_off_dlb_forever(mdlog, dd, step);
2945                 }
2946                 else if (bools.turnOnDlb)
2947                 {
2948                     turn_on_dlb(mdlog, dd, step);
2949                     bDoDLB = true;
2950                 }
2951             }
2952         }
2953         comm->n_load_have++;
2954     }
2955
2956     bool bRedist = false;
2957     if (bMasterState)
2958     {
2959         /* Clear the old state */
2960         clearDDStateIndices(dd, false);
2961         ncgindex_set = 0;
2962
2963         auto xGlobal = positionsFromStatePointer(state_global);
2964
2965         set_ddbox(*dd, true, DDMASTER(dd) ? state_global->box : nullptr, true, xGlobal, &ddbox);
2966
2967         distributeState(mdlog, dd, top_global, state_global, ddbox, state_local);
2968
2969         /* Ensure that we have space for the new distribution */
2970         dd_resize_atominfo_and_state(fr, state_local, dd->ncg_home);
2971
2972         inc_nrnb(nrnb, eNR_CGCM, comm->atomRanges.numHomeAtoms());
2973
2974         dd_set_cginfo(dd->globalAtomGroupIndices, 0, dd->ncg_home, fr);
2975     }
2976     else if (state_local->ddp_count != dd->ddp_count)
2977     {
2978         if (state_local->ddp_count > dd->ddp_count)
2979         {
2980             gmx_fatal(FARGS,
2981                       "Internal inconsistency state_local->ddp_count (%d) > dd->ddp_count (%" PRId64
2982                       ")",
2983                       state_local->ddp_count,
2984                       dd->ddp_count);
2985         }
2986
2987         if (state_local->ddp_count_cg_gl != state_local->ddp_count)
2988         {
2989             gmx_fatal(FARGS,
2990                       "Internal inconsistency state_local->ddp_count_cg_gl (%d) != "
2991                       "state_local->ddp_count (%d)",
2992                       state_local->ddp_count_cg_gl,
2993                       state_local->ddp_count);
2994         }
2995
2996         /* Clear the old state */
2997         clearDDStateIndices(dd, false);
2998
2999         /* Restore the atom group indices from state_local */
3000         restoreAtomGroups(dd, state_local);
3001         make_dd_indices(dd, 0);
3002         ncgindex_set = dd->ncg_home;
3003
3004         inc_nrnb(nrnb, eNR_CGCM, comm->atomRanges.numHomeAtoms());
3005
3006         dd_set_cginfo(dd->globalAtomGroupIndices, 0, dd->ncg_home, fr);
3007
3008         set_ddbox(*dd, bMasterState, state_local->box, true, state_local->x, &ddbox);
3009
3010         bRedist = isDlbOn(comm);
3011     }
3012     else
3013     {
3014         /* We have the full state, only redistribute the cgs */
3015
3016         /* Clear the non-home indices */
3017         clearDDStateIndices(dd, true);
3018         ncgindex_set = 0;
3019
3020         /* To avoid global communication, we do not recompute the extent
3021          * of the system for dims without pbc. Therefore we need to copy
3022          * the previously computed values when we do not communicate.
3023          */
3024         if (!bNStGlobalComm)
3025         {
3026             copy_rvec(comm->box0, ddbox.box0);
3027             copy_rvec(comm->box_size, ddbox.box_size);
3028         }
3029         set_ddbox(*dd, bMasterState, state_local->box, bNStGlobalComm, state_local->x, &ddbox);
3030
3031         bBoxChanged = true;
3032         bRedist     = true;
3033     }
3034     /* Copy needed for dim's without pbc when avoiding communication */
3035     copy_rvec(ddbox.box0, comm->box0);
3036     copy_rvec(ddbox.box_size, comm->box_size);
3037
3038     set_dd_cell_sizes(dd, &ddbox, dd->unitCellInfo.ddBoxIsDynamic, bMasterState, bDoDLB, step, wcycle);
3039
3040     if (comm->ddSettings.nstDDDumpGrid > 0 && step % comm->ddSettings.nstDDDumpGrid == 0)
3041     {
3042         write_dd_grid_pdb("dd_grid", step, dd, state_local->box, &ddbox);
3043     }
3044
3045     if (comm->systemInfo.useUpdateGroups)
3046     {
3047         comm->updateGroupsCog->addCogs(
3048                 gmx::arrayRefFromArray(dd->globalAtomGroupIndices.data(), dd->ncg_home), state_local->x);
3049     }
3050
3051     /* Check if we should sort the charge groups */
3052     const bool bSortCG = (bMasterState || bRedist);
3053
3054     /* When repartitioning we mark atom groups that will move to neighboring
3055      * DD cells, but we do not move them right away for performance reasons.
3056      * Thus we need to keep track of how many charge groups will move for
3057      * obtaining correct local charge group / atom counts.
3058      */
3059     int ncg_moved = 0;
3060     if (bRedist)
3061     {
3062         wallcycle_sub_start(wcycle, ewcsDD_REDIST);
3063
3064         ncgindex_set = dd->ncg_home;
3065         dd_redistribute_cg(fplog, step, dd, ddbox.tric_dir, state_local, fr, nrnb, &ncg_moved);
3066
3067         GMX_RELEASE_ASSERT(bSortCG, "Sorting is required after redistribution");
3068
3069         if (comm->systemInfo.useUpdateGroups)
3070         {
3071             comm->updateGroupsCog->addCogs(
3072                     gmx::arrayRefFromArray(dd->globalAtomGroupIndices.data(), dd->ncg_home),
3073                     state_local->x);
3074         }
3075
3076         wallcycle_sub_stop(wcycle, ewcsDD_REDIST);
3077     }
3078
3079     RVec cell_ns_x0, cell_ns_x1;
3080     get_nsgrid_boundaries(ddbox.nboundeddim,
3081                           state_local->box,
3082                           dd,
3083                           &ddbox,
3084                           &comm->cell_x0,
3085                           &comm->cell_x1,
3086                           dd->ncg_home,
3087                           as_rvec_array(state_local->x.data()),
3088                           cell_ns_x0,
3089                           cell_ns_x1);
3090
3091     if (bBoxChanged)
3092     {
3093         comm_dd_ns_cell_sizes(dd, &ddbox, cell_ns_x0, cell_ns_x1, step);
3094     }
3095
3096     if (bSortCG)
3097     {
3098         wallcycle_sub_start(wcycle, ewcsDD_GRID);
3099
3100         /* Sort the state on charge group position.
3101          * This enables exact restarts from this step.
3102          * It also improves performance by about 15% with larger numbers
3103          * of atoms per node.
3104          */
3105
3106         /* Fill the ns grid with the home cell,
3107          * so we can sort with the indices.
3108          */
3109         set_zones_ncg_home(dd);
3110
3111         set_zones_size(dd, state_local->box, &ddbox, 0, 1, ncg_moved);
3112
3113         nbnxn_put_on_grid(fr->nbv.get(),
3114                           state_local->box,
3115                           0,
3116                           comm->zones.size[0].bb_x0,
3117                           comm->zones.size[0].bb_x1,
3118                           comm->updateGroupsCog.get(),
3119                           { 0, dd->ncg_home },
3120                           comm->zones.dens_zone0,
3121                           fr->cginfo,
3122                           state_local->x,
3123                           ncg_moved,
3124                           bRedist ? comm->movedBuffer.data() : nullptr);
3125
3126         if (debug)
3127         {
3128             fprintf(debug, "Step %s, sorting the %d home charge groups\n", gmx_step_str(step, sbuf), dd->ncg_home);
3129         }
3130         dd_sort_state(dd, fr, state_local);
3131
3132         /* After sorting and compacting we set the correct size */
3133         state_change_natoms(state_local, comm->atomRanges.numHomeAtoms());
3134
3135         /* Rebuild all the indices */
3136         dd->ga2la->clear();
3137         ncgindex_set = 0;
3138
3139         wallcycle_sub_stop(wcycle, ewcsDD_GRID);
3140     }
3141     else
3142     {
3143         /* With the group scheme the sorting array is part of the DD state,
3144          * but it just got out of sync, so mark as invalid by emptying it.
3145          */
3146         if (inputrec.cutoff_scheme == CutoffScheme::Group)
3147         {
3148             comm->sort->sorted.clear();
3149         }
3150     }
3151
3152     if (comm->systemInfo.useUpdateGroups)
3153     {
3154         /* The update groups cog's are invalid after sorting
3155          * and need to be cleared before the next partitioning anyhow.
3156          */
3157         comm->updateGroupsCog->clear();
3158     }
3159
3160     wallcycle_sub_start(wcycle, ewcsDD_SETUPCOMM);
3161
3162     /* Set the induces for the home atoms */
3163     set_zones_ncg_home(dd);
3164     make_dd_indices(dd, ncgindex_set);
3165
3166     /* Setup up the communication and communicate the coordinates */
3167     setup_dd_communication(dd, state_local->box, &ddbox, fr, state_local);
3168
3169     /* Set the indices for the halo atoms */
3170     make_dd_indices(dd, dd->ncg_home);
3171
3172     /* Set the charge group boundaries for neighbor searching */
3173     set_cg_boundaries(&comm->zones);
3174
3175     /* When bSortCG=true, we have already set the size for zone 0 */
3176     set_zones_size(dd, state_local->box, &ddbox, bSortCG ? 1 : 0, comm->zones.n, 0);
3177
3178     wallcycle_sub_stop(wcycle, ewcsDD_SETUPCOMM);
3179
3180     /*
3181        write_dd_pdb("dd_home",step,"dump",top_global,cr,
3182                  -1,state_local->x.rvec_array(),state_local->box);
3183      */
3184
3185     wallcycle_sub_start(wcycle, ewcsDD_MAKETOP);
3186
3187     /* Extract a local topology from the global topology */
3188     IVec numPulses;
3189     for (int i = 0; i < dd->ndim; i++)
3190     {
3191         numPulses[dd->dim[i]] = comm->cd[i].numPulses();
3192     }
3193     dd_make_local_top(dd,
3194                       &comm->zones,
3195                       dd->unitCellInfo.npbcdim,
3196                       state_local->box,
3197                       comm->cellsize_min,
3198                       numPulses,
3199                       fr,
3200                       state_local->x.rvec_array(),
3201                       top_global,
3202                       top_local);
3203
3204     wallcycle_sub_stop(wcycle, ewcsDD_MAKETOP);
3205
3206     wallcycle_sub_start(wcycle, ewcsDD_MAKECONSTR);
3207
3208     /* Set up the special atom communication */
3209     int n = comm->atomRanges.end(DDAtomRanges::Type::Zones);
3210     for (int i = static_cast<int>(DDAtomRanges::Type::Zones) + 1;
3211          i < static_cast<int>(DDAtomRanges::Type::Number);
3212          i++)
3213     {
3214         auto range = static_cast<DDAtomRanges::Type>(i);
3215         switch (range)
3216         {
3217             case DDAtomRanges::Type::Vsites:
3218                 if (vsite && vsite->numInterUpdategroupVirtualSites())
3219                 {
3220                     n = dd_make_local_vsites(dd, n, top_local->idef.il);
3221                 }
3222                 break;
3223             case DDAtomRanges::Type::Constraints:
3224                 if (dd->comm->systemInfo.haveSplitConstraints || dd->comm->systemInfo.haveSplitSettles)
3225                 {
3226                     /* Only for inter-cg constraints we need special code */
3227                     n = dd_make_local_constraints(dd,
3228                                                   n,
3229                                                   top_global,
3230                                                   fr->cginfo.data(),
3231                                                   constr,
3232                                                   inputrec.nProjOrder,
3233                                                   top_local->idef.il);
3234                 }
3235                 break;
3236             default: gmx_incons("Unknown special atom type setup");
3237         }
3238         comm->atomRanges.setEnd(range, n);
3239     }
3240
3241     wallcycle_sub_stop(wcycle, ewcsDD_MAKECONSTR);
3242
3243     wallcycle_sub_start(wcycle, ewcsDD_TOPOTHER);
3244
3245     /* Make space for the extra coordinates for virtual site
3246      * or constraint communication.
3247      */
3248     state_local->natoms = comm->atomRanges.numAtomsTotal();
3249
3250     state_change_natoms(state_local, state_local->natoms);
3251
3252     int nat_f_novirsum;
3253     if (vsite && vsite->numInterUpdategroupVirtualSites())
3254     {
3255         nat_f_novirsum = comm->atomRanges.end(DDAtomRanges::Type::Vsites);
3256     }
3257     else
3258     {
3259         if (EEL_FULL(inputrec.coulombtype) && dd->haveExclusions)
3260         {
3261             nat_f_novirsum = comm->atomRanges.end(DDAtomRanges::Type::Zones);
3262         }
3263         else
3264         {
3265             nat_f_novirsum = comm->atomRanges.numHomeAtoms();
3266         }
3267     }
3268
3269     /* Set the number of atoms required for the force calculation.
3270      * Forces need to be constrained when doing energy
3271      * minimization. For simple simulations we could avoid some
3272      * allocation, zeroing and copying, but this is probably not worth
3273      * the complications and checking.
3274      */
3275     forcerec_set_ranges(fr,
3276                         comm->atomRanges.end(DDAtomRanges::Type::Zones),
3277                         comm->atomRanges.end(DDAtomRanges::Type::Constraints),
3278                         nat_f_novirsum);
3279
3280     /* Update atom data for mdatoms and several algorithms */
3281     mdAlgorithmsSetupAtomData(cr, inputrec, top_global, top_local, fr, f, mdAtoms, constr, vsite, nullptr);
3282
3283     auto mdatoms = mdAtoms->mdatoms();
3284     if (!thisRankHasDuty(cr, DUTY_PME))
3285     {
3286         /* Send the charges and/or c6/sigmas to our PME only node */
3287         gmx_pme_send_parameters(cr,
3288                                 *fr->ic,
3289                                 mdatoms->nChargePerturbed != 0,
3290                                 mdatoms->nTypePerturbed != 0,
3291                                 gmx::arrayRefFromArray(mdatoms->chargeA, mdatoms->nr),
3292                                 gmx::arrayRefFromArray(mdatoms->chargeB, mdatoms->nr),
3293                                 gmx::arrayRefFromArray(mdatoms->sqrt_c6A, mdatoms->nr),
3294                                 gmx::arrayRefFromArray(mdatoms->sqrt_c6B, mdatoms->nr),
3295                                 gmx::arrayRefFromArray(mdatoms->sigmaA, mdatoms->nr),
3296                                 gmx::arrayRefFromArray(mdatoms->sigmaB, mdatoms->nr),
3297                                 dd_pme_maxshift_x(*dd),
3298                                 dd_pme_maxshift_y(*dd));
3299     }
3300
3301     if (dd->atomSets != nullptr)
3302     {
3303         /* Update the local atom sets */
3304         dd->atomSets->setIndicesInDomainDecomposition(*(dd->ga2la));
3305     }
3306
3307     // The pull group construction can need the atom sets updated above
3308     if (inputrec.bPull)
3309     {
3310         /* Update the local pull groups */
3311         dd_make_local_pull_groups(cr, pull_work);
3312     }
3313
3314     /* Update the local atoms to be communicated via the IMD protocol if bIMD is true. */
3315     imdSession->dd_make_local_IMD_atoms(dd);
3316
3317     add_dd_statistics(dd);
3318
3319     /* Make sure we only count the cycles for this DD partitioning */
3320     clear_dd_cycle_counts(dd);
3321
3322     /* Because the order of the atoms might have changed since
3323      * the last vsite construction, we need to communicate the constructing
3324      * atom coordinates again (for spreading the forces this MD step).
3325      */
3326     dd_move_x_vsites(*dd, state_local->box, state_local->x.rvec_array());
3327
3328     wallcycle_sub_stop(wcycle, ewcsDD_TOPOTHER);
3329
3330     if (comm->ddSettings.nstDDDump > 0 && step % comm->ddSettings.nstDDDump == 0)
3331     {
3332         dd_move_x(dd, state_local->box, state_local->x, nullWallcycle);
3333         write_dd_pdb("dd_dump",
3334                      step,
3335                      "dump",
3336                      top_global,
3337                      cr,
3338                      -1,
3339                      state_local->x.rvec_array(),
3340                      state_local->box);
3341     }
3342
3343     /* Store the partitioning step */
3344     comm->partition_step = step;
3345
3346     /* Increase the DD partitioning counter */
3347     dd->ddp_count++;
3348     /* The state currently matches this DD partitioning count, store it */
3349     state_local->ddp_count = dd->ddp_count;
3350     if (bMasterState)
3351     {
3352         /* The DD master node knows the complete cg distribution,
3353          * store the count so we can possibly skip the cg info communication.
3354          */
3355         comm->master_cg_ddp_count = (bSortCG ? 0 : dd->ddp_count);
3356     }
3357
3358     if (comm->ddSettings.DD_debug > 0)
3359     {
3360         /* Set the env var GMX_DD_DEBUG if you suspect corrupted indices */
3361         check_index_consistency(dd, top_global.natoms, "after partitioning");
3362     }
3363
3364     wallcycle_stop(wcycle, ewcDOMDEC);
3365 }
3366
3367 } // namespace gmx