2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2018,2019,2020, 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.
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.
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.
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.
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.
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.
37 * \brief This file defines functions for mdrun to call to make a new
38 * domain decomposition, and check it.
40 * \author Berk Hess <hess@kth.se>
41 * \ingroup module_domdec
46 #include "partition.h"
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/ewald/pme_pp.h"
64 #include "gromacs/gmxlib/network.h"
65 #include "gromacs/gmxlib/nrnb.h"
66 #include "gromacs/imd/imd.h"
67 #include "gromacs/math/functions.h"
68 #include "gromacs/math/vec.h"
69 #include "gromacs/mdlib/forcerec.h"
70 #include "gromacs/mdlib/gmx_omp_nthreads.h"
71 #include "gromacs/mdlib/mdatoms.h"
72 #include "gromacs/mdlib/nsgrid.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"
97 #include "cellsizes.h"
98 #include "distribute.h"
99 #include "domdec_constraints.h"
100 #include "domdec_internal.h"
101 #include "domdec_vsite.h"
103 #include "redistribute.h"
106 /*! \brief Turn on DLB when the load imbalance causes this amount of total loss.
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.
111 #define DD_PERF_LOSS_DLB_ON 0.02
113 //! Warn about imbalance due to PP or PP/PME load imbalance at this loss.
114 #define DD_PERF_LOSS_WARN 0.05
117 //! Debug helper printing a DD zone
118 static void print_ddzone(FILE* fp, int d, int i, int j, gmx_ddzone_t* zone)
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 "
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.
139 static void dd_move_cellx(gmx_domdec_t* dd, const gmx_ddbox_t* ddbox, rvec cell_ns_x0, rvec cell_ns_x1)
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;
149 for (int d = 1; d < dd->ndim; d++)
151 int dim = dd->dim[d];
152 gmx_ddzone_t& zp = (d == 1) ? comm->zone_d1[0] : comm->zone_d2[0][0];
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];
165 gmx::ArrayRef<DDCellsizesWithDlb> cellsizes = comm->cellsizesWithDlb;
167 /* Loop backward over the dimensions and aggregate the extremes
170 for (int d = dd->ndim - 2; d >= 0; d--)
172 const int dim = dd->dim[d];
173 const bool applyPbc = (dim < ddbox->npbcdim);
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;
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.
185 for (int d1 = d; d1 < dd->ndim - 1; d1++)
187 gmx_ddzone_t& buf = buf_s[pos];
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];
195 /* Store the cell corner of the dimension we communicate along */
196 buf.p1_0 = comm->cell_x0[dim];
202 buf_s[pos] = (dd->ndim == 2) ? comm->zone_d1[0] : comm->zone_d2[0][0];
205 if (dd->ndim == 3 && d == 0)
207 buf_s[pos] = comm->zone_d2[0][1];
209 buf_s[pos] = comm->zone_d1[0];
213 /* We only need to communicate the extremes
214 * in the forward direction
216 int numPulses = comm->cd[d].numPulses();
220 /* Take the minimum to avoid double communication */
221 numPulsesMin = std::min(numPulses, dd->numCells[dim] - 1 - numPulses);
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.
230 numPulsesMin = numPulses;
232 for (int pulse = 0; pulse < numPulsesMin; pulse++)
234 /* Communicate the extremes forward */
235 bool receiveValidData = (applyPbc || dd->ci[dim] > 0);
237 int numElements = dd->ndim - d - 1;
238 ddSendrecv(dd, d, dddirForward, extr_s + d, numElements, extr_r + d, numElements);
240 if (receiveValidData)
242 for (int d1 = d; d1 < dd->ndim - 1; d1++)
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]);
251 const int numElementsInBuffer = pos;
252 for (int pulse = 0; pulse < numPulses; pulse++)
254 /* Communicate all the zone information backward */
255 bool receiveValidData = (applyPbc || dd->ci[dim] < dd->numCells[dim] - 1);
258 sizeof(gmx_ddzone_t) == c_ddzoneNumReals * sizeof(real),
259 "Here we expect gmx_ddzone_t to consist of c_ddzoneNumReals reals (only)");
261 int numReals = numElementsInBuffer * c_ddzoneNumReals;
265 gmx::arrayRefFromArray(&buf_s[0].min0, numReals),
266 gmx::arrayRefFromArray(&buf_r[0].min0, numReals));
271 for (int d1 = d + 1; d1 < dd->ndim; d1++)
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.
277 real dist_d = comm->cell_x1[dim] - buf_r[0].p1_0;
280 if (ddbox->tric_dir[dim])
282 /* c is the off-diagonal coupling between the cell planes
283 * along directions d and d1.
285 c = ddbox->v[dim][dd->dim[d1]][dim];
291 real det = (1 + c * c) * gmx::square(comm->systemInfo.cutoff) - dist_d * dist_d;
294 dh[d1] = comm->systemInfo.cutoff - (c * dist_d + std::sqrt(det)) / (1 + c * c);
298 /* A negative value signals out of range */
304 /* Accumulate the extremes over all pulses */
305 for (int i = 0; i < numElementsInBuffer; i++)
313 if (receiveValidData)
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);
321 if (dd->ndim == 3 && d == 0 && i == numElementsInBuffer - 1)
329 if (receiveValidData && dh[d1] >= 0)
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]);
335 /* Copy the received buffer to the send buffer,
336 * to pass the data through with the next pulse.
340 if (((applyPbc || dd->ci[dim] + numPulses < dd->numCells[dim]) && pulse == numPulses - 1)
341 || (!applyPbc && dd->ci[dim] + 1 + pulse == dd->numCells[dim] - 1))
343 /* Store the extremes */
346 for (int d1 = d; d1 < dd->ndim - 1; d1++)
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);
354 if (d == 1 || (d == 0 && dd->ndim == 3))
356 for (int i = d; i < 2; i++)
358 comm->zone_d2[1 - d][i] = buf_e[pos];
364 comm->zone_d1[1] = buf_e[pos];
370 if (d == 1 || (d == 0 && dd->ndim == 3))
372 for (int i = d; i < 2; i++)
374 comm->zone_d2[1 - d][i].dataSet = 0;
379 comm->zone_d1[1].dataSet = 0;
387 int dim = dd->dim[1];
388 for (int i = 0; i < 2; i++)
390 if (comm->zone_d1[i].dataSet != 0)
394 print_ddzone(debug, 1, i, 0, &comm->zone_d1[i]);
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);
403 int dim = dd->dim[2];
404 for (int i = 0; i < 2; i++)
406 for (int j = 0; j < 2; j++)
408 if (comm->zone_d2[i][j].dataSet != 0)
412 print_ddzone(debug, 2, i, j, &comm->zone_d2[i][j]);
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);
420 for (int d = 1; d < dd->ndim; d++)
422 cellsizes[d].fracLowerMax = extr_s[d - 1][0];
423 cellsizes[d].fracUpperMin = extr_s[d - 1][1];
427 "Cell fraction d %d, max0 %f, min1 %f\n",
429 cellsizes[d].fracLowerMax,
430 cellsizes[d].fracUpperMin);
435 //! Sets the charge-group zones to be equal to the home zone.
436 static void set_zones_ncg_home(gmx_domdec_t* dd)
438 gmx_domdec_zones_t* zones;
441 zones = &dd->comm->zones;
443 zones->cg_range[0] = 0;
444 for (i = 1; i < zones->n + 1; i++)
446 zones->cg_range[i] = dd->ncg_home;
448 /* zone_ncg1[0] should always be equal to ncg_home */
449 dd->comm->zone_ncg1[0] = dd->ncg_home;
452 //! Restore atom groups for the charge groups.
453 static void restoreAtomGroups(gmx_domdec_t* dd, const t_state* state)
455 gmx::ArrayRef<const int> atomGroupsState = state->cg_gl;
457 std::vector<int>& globalAtomGroupIndices = dd->globalAtomGroupIndices;
459 globalAtomGroupIndices.resize(atomGroupsState.size());
461 /* Copy back the global charge group indices from state
462 * and rebuild the local charge group to atom index.
464 for (gmx::index i = 0; i < atomGroupsState.ssize(); i++)
466 globalAtomGroupIndices[i] = atomGroupsState[i];
469 dd->ncg_home = atomGroupsState.size();
470 dd->comm->atomRanges.setEnd(DDAtomRanges::Type::Home, atomGroupsState.ssize());
472 set_zones_ncg_home(dd);
475 //! Sets the cginfo structures.
476 static void dd_set_cginfo(gmx::ArrayRef<const int> index_gl, int cg0, int cg1, t_forcerec* fr)
480 gmx::ArrayRef<cginfo_mb_t> cginfo_mb = fr->cginfo_mb;
481 gmx::ArrayRef<int> cginfo = fr->cginfo;
483 for (int cg = cg0; cg < cg1; cg++)
485 cginfo[cg] = ddcginfo(cginfo_mb, index_gl[cg]);
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)
493 const int numZones = dd->comm->zones.n;
494 const int* zone2cg = dd->comm->zones.cg_range;
495 const int* zone_ncg1 = dd->comm->zone_ncg1;
496 gmx::ArrayRef<const int> globalAtomGroupIndices = dd->globalAtomGroupIndices;
498 std::vector<int>& globalAtomIndices = dd->globalAtomIndices;
499 gmx_ga2la_t& ga2la = *dd->ga2la;
501 if (zone2cg[1] != dd->ncg_home)
503 gmx_incons("dd->ncg_zone is not up to date");
506 /* Make the local to global and global to local atom index */
508 globalAtomIndices.resize(a);
509 for (int zone = 0; zone < numZones; zone++)
520 int cg1 = zone2cg[zone + 1];
521 int cg1_p1 = cg0 + zone_ncg1[zone];
523 for (int cg = cg0; cg < cg1; cg++)
528 /* Signal that this cg is from more than one pulse away */
531 int cg_gl = globalAtomGroupIndices[cg];
532 globalAtomIndices.push_back(cg_gl);
533 ga2la.insert(cg_gl, { a, zone1 });
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)
544 const int numAtomsInZones = dd->comm->atomRanges.end(DDAtomRanges::Type::Zones);
546 if (dd->comm->ddSettings.DD_debug > 1)
548 std::vector<int> have(natoms_sys);
549 for (int a = 0; a < numAtomsInZones; a++)
551 int globalAtomIndex = dd->globalAtomIndices[a];
552 if (have[globalAtomIndex] > 0)
555 "DD rank %d: global atom %d occurs twice: index %d and %d\n",
558 have[globalAtomIndex],
563 have[globalAtomIndex] = a + 1;
568 std::vector<int> have(numAtomsInZones);
571 for (int i = 0; i < natoms_sys; i++)
573 if (const auto entry = dd->ga2la->find(i))
575 const int a = entry->la;
576 if (a >= numAtomsInZones)
579 "DD rank %d: global atom %d marked as local atom %d, which is larger than "
590 if (dd->globalAtomIndices[a] != i)
593 "DD rank %d: global atom %d marked as local atom %d, which has global "
598 dd->globalAtomIndices[a] + 1);
605 if (ngl != numAtomsInZones)
607 fprintf(stderr, "DD rank %d, %s: %d global atom indices, %d local atoms\n", dd->rank, where, ngl, numAtomsInZones);
609 for (int a = 0; a < numAtomsInZones; a++)
614 "DD rank %d, %s: local atom %d, global %d has no global index\n",
618 dd->globalAtomIndices[a] + 1);
624 gmx_fatal(FARGS, "DD rank %d, %s: %d atom(group) index inconsistencies", dd->rank, where, nerr);
628 //! Clear all DD global state indices
629 static void clearDDStateIndices(gmx_domdec_t* dd, const bool keepLocalAtomIndices)
631 gmx_ga2la_t& ga2la = *dd->ga2la;
633 if (!keepLocalAtomIndices)
635 /* Clear the whole list without the overhead of searching */
640 const int numAtomsInZones = dd->comm->atomRanges.end(DDAtomRanges::Type::Zones);
641 for (int i = 0; i < numAtomsInZones; i++)
643 ga2la.erase(dd->globalAtomIndices[i]);
647 dd_clear_local_vsite_indices(dd);
651 dd_clear_local_constraint_indices(dd);
655 bool check_grid_jump(int64_t step, const gmx_domdec_t* dd, real cutoff, const gmx_ddbox_t* ddbox, gmx_bool bFatal)
657 gmx_domdec_comm_t* comm = dd->comm;
658 bool invalid = false;
660 for (int d = 1; d < dd->ndim; d++)
662 const DDCellsizesWithDlb& cellsizes = comm->cellsizesWithDlb[d];
663 const int dim = dd->dim[d];
664 const real limit = grid_jump_limit(comm, cutoff, d);
665 real bfac = ddbox->box_size[dim];
666 if (ddbox->tric_dir[dim])
668 bfac *= ddbox->skew_fac[dim];
670 if ((cellsizes.fracUpper - cellsizes.fracLowerMax) * bfac < limit
671 || (cellsizes.fracLower - cellsizes.fracUpperMin) * bfac > -limit)
679 /* This error should never be triggered under normal
680 * circumstances, but you never know ...
683 "step %s: The domain decomposition grid has shifted too much in the "
684 "%c-direction around cell %d %d %d. This should not have happened. "
685 "Running with fewer ranks might avoid this issue.",
686 gmx_step_str(step, buf),
697 //! Return the duration of force calculations on this rank.
698 static float dd_force_load(gmx_domdec_comm_t* comm)
702 if (comm->ddSettings.eFlop)
705 if (comm->ddSettings.eFlop > 1)
707 load *= 1.0 + (comm->ddSettings.eFlop - 1) * (0.1 * rand() / RAND_MAX - 0.05);
712 load = comm->cycl[ddCyclF];
713 if (comm->cycl_n[ddCyclF] > 1)
715 /* Subtract the maximum of the last n cycle counts
716 * to get rid of possible high counts due to other sources,
717 * for instance system activity, that would otherwise
718 * affect the dynamic load balancing.
720 load -= comm->cycl_max[ddCyclF];
724 if (comm->cycl_n[ddCyclWaitGPU] && comm->nrank_gpu_shared > 1)
726 float gpu_wait, gpu_wait_sum;
728 gpu_wait = comm->cycl[ddCyclWaitGPU];
729 if (comm->cycl_n[ddCyclF] > 1)
731 /* We should remove the WaitGPU time of the same MD step
732 * as the one with the maximum F time, since the F time
733 * and the wait time are not independent.
734 * Furthermore, the step for the max F time should be chosen
735 * the same on all ranks that share the same GPU.
736 * But to keep the code simple, we remove the average instead.
737 * The main reason for artificially long times at some steps
738 * is spurious CPU activity or MPI time, so we don't expect
739 * that changes in the GPU wait time matter a lot here.
741 gpu_wait *= (comm->cycl_n[ddCyclF] - 1) / static_cast<float>(comm->cycl_n[ddCyclF]);
743 /* Sum the wait times over the ranks that share the same GPU */
744 MPI_Allreduce(&gpu_wait, &gpu_wait_sum, 1, MPI_FLOAT, MPI_SUM, comm->mpi_comm_gpu_shared);
745 /* Replace the wait time by the average over the ranks */
746 load += -gpu_wait + gpu_wait_sum / comm->nrank_gpu_shared;
754 //! Runs cell size checks and communicates the boundaries.
755 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)
757 gmx_domdec_comm_t* comm;
762 for (dim_ind = 0; dim_ind < dd->ndim; dim_ind++)
764 dim = dd->dim[dim_ind];
766 /* Without PBC we don't have restrictions on the outer cells */
767 if (!(dim >= ddbox->npbcdim && (dd->ci[dim] == 0 || dd->ci[dim] == dd->numCells[dim] - 1))
769 && (comm->cell_x1[dim] - comm->cell_x0[dim]) * ddbox->skew_fac[dim] < comm->cellsize_min[dim])
773 "step %s: The %c-size (%f) times the triclinic skew factor (%f) is smaller "
774 "than the smallest allowed cell size (%f) for domain decomposition grid cell "
776 gmx_step_str(step, buf),
778 comm->cell_x1[dim] - comm->cell_x0[dim],
779 ddbox->skew_fac[dim],
780 dd->comm->cellsize_min[dim],
787 if ((isDlbOn(dd->comm) && dd->ndim > 1) || ddbox->nboundeddim < DIM)
789 /* Communicate the boundaries and update cell_ns_x0/1 */
790 dd_move_cellx(dd, ddbox, cell_ns_x0, cell_ns_x1);
791 if (isDlbOn(dd->comm) && dd->ndim > 1)
793 check_grid_jump(step, dd, dd->comm->systemInfo.cutoff, ddbox, TRUE);
798 //! Compute and communicate to determine the load distribution across PP ranks.
799 static void get_load_distribution(gmx_domdec_t* dd, gmx_wallcycle_t wcycle)
801 gmx_domdec_comm_t* comm;
803 float cell_frac = 0, sbuf[DD_NLOAD_MAX];
808 fprintf(debug, "get_load_distribution start\n");
811 wallcycle_start(wcycle, ewcDDCOMMLOAD);
815 bSepPME = (dd->pme_nodeid >= 0);
817 if (dd->ndim == 0 && bSepPME)
819 /* Without decomposition, but with PME nodes, we need the load */
820 comm->load[0].mdf = comm->cycl[ddCyclPPduringPME];
821 comm->load[0].pme = comm->cycl[ddCyclPME];
824 for (int d = dd->ndim - 1; d >= 0; d--)
826 const DDCellsizesWithDlb* cellsizes = (isDlbOn(dd->comm) ? &comm->cellsizesWithDlb[d] : nullptr);
827 const int dim = dd->dim[d];
828 /* Check if we participate in the communication in this dimension */
829 if (d == dd->ndim - 1 || (dd->ci[dd->dim[d + 1]] == 0 && dd->ci[dd->dim[dd->ndim - 1]] == 0))
831 load = &comm->load[d];
832 if (isDlbOn(dd->comm))
834 cell_frac = cellsizes->fracUpper - cellsizes->fracLower;
837 if (d == dd->ndim - 1)
839 sbuf[pos++] = dd_force_load(comm);
840 sbuf[pos++] = sbuf[0];
841 if (isDlbOn(dd->comm))
843 sbuf[pos++] = sbuf[0];
844 sbuf[pos++] = cell_frac;
847 sbuf[pos++] = cellsizes->fracLowerMax;
848 sbuf[pos++] = cellsizes->fracUpperMin;
853 sbuf[pos++] = comm->cycl[ddCyclPPduringPME];
854 sbuf[pos++] = comm->cycl[ddCyclPME];
859 sbuf[pos++] = comm->load[d + 1].sum;
860 sbuf[pos++] = comm->load[d + 1].max;
861 if (isDlbOn(dd->comm))
863 sbuf[pos++] = comm->load[d + 1].sum_m;
864 sbuf[pos++] = comm->load[d + 1].cvol_min * cell_frac;
865 sbuf[pos++] = comm->load[d + 1].flags;
868 sbuf[pos++] = cellsizes->fracLowerMax;
869 sbuf[pos++] = cellsizes->fracUpperMin;
874 sbuf[pos++] = comm->load[d + 1].mdf;
875 sbuf[pos++] = comm->load[d + 1].pme;
879 /* Communicate a row in DD direction d.
880 * The communicators are setup such that the root always has rank 0.
884 load->nload * sizeof(float),
887 load->nload * sizeof(float),
890 comm->mpi_comm_load[d]);
892 if (dd->ci[dim] == dd->master_ci[dim])
894 /* We are the master along this row, process this row */
895 RowMaster* rowMaster = nullptr;
899 rowMaster = cellsizes->rowMaster.get();
909 for (int i = 0; i < dd->numCells[dim]; i++)
911 load->sum += load->load[pos++];
912 load->max = std::max(load->max, load->load[pos]);
914 if (isDlbOn(dd->comm))
916 if (rowMaster->dlbIsLimited)
918 /* This direction could not be load balanced properly,
919 * therefore we need to use the maximum iso the average load.
921 load->sum_m = std::max(load->sum_m, load->load[pos]);
925 load->sum_m += load->load[pos];
928 load->cvol_min = std::min(load->cvol_min, load->load[pos]);
930 if (d < dd->ndim - 1)
932 load->flags = gmx::roundToInt(load->load[pos++]);
936 rowMaster->bounds[i].cellFracLowerMax = load->load[pos++];
937 rowMaster->bounds[i].cellFracUpperMin = load->load[pos++];
942 load->mdf = std::max(load->mdf, load->load[pos]);
944 load->pme = std::max(load->pme, load->load[pos]);
948 if (isDlbOn(comm) && rowMaster->dlbIsLimited)
950 load->sum_m *= dd->numCells[dim];
951 load->flags |= (1 << d);
959 comm->nload += dd_load_count(comm);
960 comm->load_step += comm->cycl[ddCyclStep];
961 comm->load_sum += comm->load[0].sum;
962 comm->load_max += comm->load[0].max;
965 for (int d = 0; d < dd->ndim; d++)
967 if (comm->load[0].flags & (1 << d))
975 comm->load_mdf += comm->load[0].mdf;
976 comm->load_pme += comm->load[0].pme;
980 wallcycle_stop(wcycle, ewcDDCOMMLOAD);
984 fprintf(debug, "get_load_distribution finished\n");
988 /*! \brief Return the relative performance loss on the total run time
989 * due to the force calculation load imbalance. */
990 static float dd_force_load_fraction(gmx_domdec_t* dd)
992 if (dd->comm->nload > 0 && dd->comm->load_step > 0)
994 return dd->comm->load_sum / (dd->comm->load_step * dd->nnodes);
1002 /*! \brief Return the relative performance loss on the total run time
1003 * due to the force calculation load imbalance. */
1004 static float dd_force_imb_perf_loss(gmx_domdec_t* dd)
1006 if (dd->comm->nload > 0 && dd->comm->load_step > 0)
1008 return (dd->comm->load_max * dd->nnodes - dd->comm->load_sum) / (dd->comm->load_step * dd->nnodes);
1016 //! Print load-balance report e.g. at the end of a run.
1017 static void print_dd_load_av(FILE* fplog, gmx_domdec_t* dd)
1019 gmx_domdec_comm_t* comm = dd->comm;
1021 /* Only the master rank prints loads and only if we measured loads */
1022 if (!DDMASTER(dd) || comm->nload == 0)
1028 int numPpRanks = dd->nnodes;
1029 int numPmeRanks = (comm->ddRankSetup.usePmeOnlyRanks ? comm->ddRankSetup.numRanksDoingPme : 0);
1030 int numRanks = numPpRanks + numPmeRanks;
1031 float lossFraction = 0;
1033 /* Print the average load imbalance and performance loss */
1034 if (dd->nnodes > 1 && comm->load_sum > 0)
1036 float imbalance = comm->load_max * numPpRanks / comm->load_sum - 1;
1037 lossFraction = dd_force_imb_perf_loss(dd);
1039 std::string msg = "\nDynamic load balancing report:\n";
1040 std::string dlbStateStr;
1042 switch (dd->comm->dlbState)
1044 case DlbState::offUser:
1045 dlbStateStr = "DLB was off during the run per user request.";
1047 case DlbState::offForever:
1048 /* Currectly this can happen due to performance loss observed, cell size
1049 * limitations or incompatibility with other settings observed during
1050 * determineInitialDlbState(). */
1051 dlbStateStr = "DLB got disabled because it was unsuitable to use.";
1053 case DlbState::offCanTurnOn:
1054 dlbStateStr = "DLB was off during the run due to low measured imbalance.";
1056 case DlbState::offTemporarilyLocked:
1058 "DLB was locked at the end of the run due to unfinished PP-PME "
1061 case DlbState::onCanTurnOff:
1062 dlbStateStr = "DLB was turned on during the run due to measured imbalance.";
1064 case DlbState::onUser:
1065 dlbStateStr = "DLB was permanently on during the run per user request.";
1067 default: GMX_ASSERT(false, "Undocumented DLB state");
1070 msg += " " + dlbStateStr + "\n";
1071 msg += gmx::formatString(" Average load imbalance: %.1f%%.\n", imbalance * 100);
1072 msg += gmx::formatString(
1073 " The balanceable part of the MD step is %d%%, load imbalance is computed from "
1075 gmx::roundToInt(dd_force_load_fraction(dd) * 100));
1076 msg += gmx::formatString(
1077 " Part of the total run time spent waiting due to load imbalance: %.1f%%.\n",
1078 lossFraction * 100);
1079 fprintf(fplog, "%s", msg.c_str());
1080 fprintf(stderr, "\n%s", msg.c_str());
1083 /* Print during what percentage of steps the load balancing was limited */
1084 bool dlbWasLimited = false;
1087 sprintf(buf, " Steps where the load balancing was limited by -rdd, -rcon and/or -dds:");
1088 for (int d = 0; d < dd->ndim; d++)
1090 int limitPercentage = (200 * comm->load_lim[d] + 1) / (2 * comm->nload);
1091 sprintf(buf + strlen(buf), " %c %d %%", dim2char(dd->dim[d]), limitPercentage);
1092 if (limitPercentage >= 50)
1094 dlbWasLimited = true;
1097 sprintf(buf + strlen(buf), "\n");
1098 fprintf(fplog, "%s", buf);
1099 fprintf(stderr, "%s", buf);
1102 /* Print the performance loss due to separate PME - PP rank imbalance */
1103 float lossFractionPme = 0;
1104 if (numPmeRanks > 0 && comm->load_mdf > 0 && comm->load_step > 0)
1106 float pmeForceRatio = comm->load_pme / comm->load_mdf;
1107 lossFractionPme = (comm->load_pme - comm->load_mdf) / comm->load_step;
1108 if (lossFractionPme <= 0)
1110 lossFractionPme *= numPmeRanks / static_cast<float>(numRanks);
1114 lossFractionPme *= numPpRanks / static_cast<float>(numRanks);
1116 sprintf(buf, " Average PME mesh/force load: %5.3f\n", pmeForceRatio);
1117 fprintf(fplog, "%s", buf);
1118 fprintf(stderr, "%s", buf);
1120 " Part of the total run time spent waiting due to PP/PME imbalance: %.1f %%\n",
1121 std::fabs(lossFractionPme) * 100);
1122 fprintf(fplog, "%s", buf);
1123 fprintf(stderr, "%s", buf);
1125 fprintf(fplog, "\n");
1126 fprintf(stderr, "\n");
1128 if (lossFraction >= DD_PERF_LOSS_WARN)
1130 std::string message = gmx::formatString(
1131 "NOTE: %.1f %% of the available CPU time was lost due to load imbalance\n"
1132 " in the domain decomposition.\n",
1133 lossFraction * 100);
1135 bool hadSuggestion = false;
1138 message += " You might want to use dynamic load balancing (option -dlb.)\n";
1139 hadSuggestion = true;
1141 else if (dlbWasLimited)
1144 " You might want to decrease the cell size limit (options -rdd, -rcon "
1146 hadSuggestion = true;
1148 message += gmx::formatString(
1149 " You can %sconsider manually changing the decomposition (option -dd);\n"
1150 " e.g. by using fewer domains along the box dimension in which there is\n"
1151 " considerable inhomogeneity in the simulated system.",
1152 hadSuggestion ? "also " : "");
1155 fprintf(fplog, "%s\n", message.c_str());
1156 fprintf(stderr, "%s\n", message.c_str());
1158 if (numPmeRanks > 0 && std::fabs(lossFractionPme) >= DD_PERF_LOSS_WARN)
1161 "NOTE: %.1f %% performance was lost because the PME ranks\n"
1162 " had %s work to do than the PP ranks.\n"
1163 " You might want to %s the number of PME ranks\n"
1164 " or %s the cut-off and the grid spacing.\n",
1165 std::fabs(lossFractionPme * 100),
1166 (lossFractionPme < 0) ? "less" : "more",
1167 (lossFractionPme < 0) ? "decrease" : "increase",
1168 (lossFractionPme < 0) ? "decrease" : "increase");
1169 fprintf(fplog, "%s\n", buf);
1170 fprintf(stderr, "%s\n", buf);
1174 //! Return the minimum communication volume.
1175 static float dd_vol_min(gmx_domdec_t* dd)
1177 return dd->comm->load[0].cvol_min * dd->nnodes;
1180 //! Return the DD load flags.
1181 static int dd_load_flags(gmx_domdec_t* dd)
1183 return dd->comm->load[0].flags;
1186 //! Return the reported load imbalance in force calculations.
1187 static float dd_f_imbal(gmx_domdec_t* dd)
1189 if (dd->comm->load[0].sum > 0)
1191 return dd->comm->load[0].max * dd->nnodes / dd->comm->load[0].sum - 1.0F;
1195 /* Something is wrong in the cycle counting, report no load imbalance */
1200 //! Returns DD load balance report.
1201 static std::string dd_print_load(gmx_domdec_t* dd, int64_t step)
1203 gmx::StringOutputStream stream;
1204 gmx::TextWriter log(&stream);
1206 int flags = dd_load_flags(dd);
1209 log.writeString("DD load balancing is limited by minimum cell size in dimension");
1210 for (int d = 0; d < dd->ndim; d++)
1212 if (flags & (1 << d))
1214 log.writeStringFormatted(" %c", dim2char(dd->dim[d]));
1217 log.ensureLineBreak();
1219 log.writeString("DD step " + gmx::toString(step));
1220 if (isDlbOn(dd->comm))
1222 log.writeStringFormatted(" vol min/aver %5.3f%c", dd_vol_min(dd), flags ? '!' : ' ');
1226 log.writeStringFormatted(" load imb.: force %4.1f%%", dd_f_imbal(dd) * 100);
1228 if (dd->comm->cycl_n[ddCyclPME])
1230 log.writeStringFormatted(" pme mesh/force %5.3f", dd_pme_f_ratio(dd));
1232 log.ensureLineBreak();
1233 return stream.toString();
1236 //! Prints DD load balance report in mdrun verbose mode.
1237 static void dd_print_load_verbose(gmx_domdec_t* dd)
1239 if (isDlbOn(dd->comm))
1241 fprintf(stderr, "vol %4.2f%c ", dd_vol_min(dd), dd_load_flags(dd) ? '!' : ' ');
1245 fprintf(stderr, "imb F %2d%% ", gmx::roundToInt(dd_f_imbal(dd) * 100));
1247 if (dd->comm->cycl_n[ddCyclPME])
1249 fprintf(stderr, "pme/F %4.2f ", dd_pme_f_ratio(dd));
1253 //! Turns on dynamic load balancing if possible and needed.
1254 static void turn_on_dlb(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t step)
1256 gmx_domdec_comm_t* comm = dd->comm;
1258 real cellsize_min = comm->cellsize_min[dd->dim[0]];
1259 for (int d = 1; d < dd->ndim; d++)
1261 cellsize_min = std::min(cellsize_min, comm->cellsize_min[dd->dim[d]]);
1264 /* Turn off DLB if we're too close to the cell size limit. */
1265 if (cellsize_min < comm->cellsize_limit * 1.05)
1268 .appendTextFormatted(
1269 "step %s Measured %.1f %% performance loss due to load imbalance, "
1270 "but the minimum cell size is smaller than 1.05 times the cell size limit. "
1271 "Will no longer try dynamic load balancing.",
1272 gmx::toString(step).c_str(),
1273 dd_force_imb_perf_loss(dd) * 100);
1275 comm->dlbState = DlbState::offForever;
1280 .appendTextFormatted(
1281 "step %s Turning on dynamic load balancing, because the performance loss due "
1282 "to load imbalance is %.1f %%.",
1283 gmx::toString(step).c_str(),
1284 dd_force_imb_perf_loss(dd) * 100);
1285 comm->dlbState = DlbState::onCanTurnOff;
1287 /* Store the non-DLB performance, so we can check if DLB actually
1288 * improves performance.
1290 GMX_RELEASE_ASSERT(comm->cycl_n[ddCyclStep] > 0,
1291 "When we turned on DLB, we should have measured cycles");
1292 comm->cyclesPerStepBeforeDLB = comm->cycl[ddCyclStep] / comm->cycl_n[ddCyclStep];
1296 /* We can set the required cell size info here,
1297 * so we do not need to communicate this.
1298 * The grid is completely uniform.
1300 for (int d = 0; d < dd->ndim; d++)
1302 RowMaster* rowMaster = comm->cellsizesWithDlb[d].rowMaster.get();
1306 comm->load[d].sum_m = comm->load[d].sum;
1308 int nc = dd->numCells[dd->dim[d]];
1309 for (int i = 0; i < nc; i++)
1311 rowMaster->cellFrac[i] = i / static_cast<real>(nc);
1314 rowMaster->bounds[i].cellFracLowerMax = i / static_cast<real>(nc);
1315 rowMaster->bounds[i].cellFracUpperMin = (i + 1) / static_cast<real>(nc);
1318 rowMaster->cellFrac[nc] = 1.0;
1323 //! Turns off dynamic load balancing (but leave it able to turn back on).
1324 static void turn_off_dlb(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t step)
1328 "step " + gmx::toString(step)
1329 + " Turning off dynamic load balancing, because it is degrading performance.");
1330 dd->comm->dlbState = DlbState::offCanTurnOn;
1331 dd->comm->haveTurnedOffDlb = true;
1332 dd->comm->ddPartioningCountFirstDlbOff = dd->ddp_count;
1335 //! Turns off dynamic load balancing permanently.
1336 static void turn_off_dlb_forever(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t step)
1338 GMX_RELEASE_ASSERT(dd->comm->dlbState == DlbState::offCanTurnOn,
1339 "Can only turn off DLB forever when it was in the can-turn-on state");
1342 "step " + gmx::toString(step)
1343 + " Will no longer try dynamic load balancing, as it degraded performance.");
1344 dd->comm->dlbState = DlbState::offForever;
1347 void set_dd_dlb_max_cutoff(t_commrec* cr, real cutoff)
1349 gmx_domdec_comm_t* comm;
1351 comm = cr->dd->comm;
1353 /* Turn on the DLB limiting (might have been on already) */
1354 comm->bPMELoadBalDLBLimits = TRUE;
1356 /* Change the cut-off limit */
1357 comm->PMELoadBal_max_cutoff = cutoff;
1362 "PME load balancing set a limit to the DLB staggering such that a %f cut-off will "
1363 "continue to fit\n",
1364 comm->PMELoadBal_max_cutoff);
1368 //! Merge atom buffers.
1369 static void merge_cg_buffers(int ncell,
1370 gmx_domdec_comm_dim_t* cd,
1373 gmx::ArrayRef<int> index_gl,
1375 gmx::ArrayRef<gmx::RVec> x,
1376 gmx::ArrayRef<const gmx::RVec> recv_vr,
1377 gmx::ArrayRef<cginfo_mb_t> cginfo_mb,
1378 gmx::ArrayRef<int> cginfo)
1380 gmx_domdec_ind_t *ind, *ind_p;
1381 int p, cell, c, cg, cg0, cg1, cg_gl;
1384 ind = &cd->ind[pulse];
1386 /* First correct the already stored data */
1387 shift = ind->nrecv[ncell];
1388 for (cell = ncell - 1; cell >= 0; cell--)
1390 shift -= ind->nrecv[cell];
1393 /* Move the cg's present from previous grid pulses */
1394 cg0 = ncg_cell[ncell + cell];
1395 cg1 = ncg_cell[ncell + cell + 1];
1396 for (cg = cg1 - 1; cg >= cg0; cg--)
1398 index_gl[cg + shift] = index_gl[cg];
1399 x[cg + shift] = x[cg];
1400 cginfo[cg + shift] = cginfo[cg];
1402 /* Correct the already stored send indices for the shift */
1403 for (p = 1; p <= pulse; p++)
1405 ind_p = &cd->ind[p];
1407 for (c = 0; c < cell; c++)
1409 cg0 += ind_p->nsend[c];
1411 cg1 = cg0 + ind_p->nsend[cell];
1412 for (cg = cg0; cg < cg1; cg++)
1414 ind_p->index[cg] += shift;
1420 /* Merge in the communicated buffers */
1423 for (cell = 0; cell < ncell; cell++)
1425 cg1 = ncg_cell[ncell + cell + 1] + shift;
1426 for (cg = 0; cg < ind->nrecv[cell]; cg++)
1428 /* Copy this atom from the buffer */
1429 index_gl[cg1] = recv_i[cg0];
1430 x[cg1] = recv_vr[cg0];
1431 /* Copy information */
1432 cg_gl = index_gl[cg1];
1433 cginfo[cg1] = ddcginfo(cginfo_mb, cg_gl);
1437 shift += ind->nrecv[cell];
1438 ncg_cell[ncell + cell + 1] = cg1;
1442 //! Makes a range partitioning for the atom groups wthin a cell
1443 static void make_cell2at_index(gmx_domdec_comm_dim_t* cd, int nzone, int atomGroupStart)
1445 /* Store the atom block boundaries for easy copying of communication buffers
1447 int g = atomGroupStart;
1448 for (int zone = 0; zone < nzone; zone++)
1450 for (gmx_domdec_ind_t& ind : cd->ind)
1452 ind.cell2at0[zone] = g;
1453 g += ind.nrecv[zone];
1454 ind.cell2at1[zone] = g;
1459 //! Returns whether a link is missing.
1460 static gmx_bool missing_link(const t_blocka& link, const int globalAtomIndex, const gmx_ga2la_t& ga2la)
1462 for (int i = link.index[globalAtomIndex]; i < link.index[globalAtomIndex + 1]; i++)
1464 if (!ga2la.findHome(link.a[i]))
1473 //! Domain corners for communication, a maximum of 4 i-zones see a j domain
1476 //! The corners for the non-bonded communication.
1478 //! Corner for rounding.
1480 //! Corners for rounding.
1482 //! Corners for bounded communication.
1484 //! Corner for rounding for bonded communication.
1488 //! Determine the corners of the domain(s) we are communicating with.
1489 static void set_dd_corners(const gmx_domdec_t* dd, int dim0, int dim1, int dim2, gmx_bool bDistMB, dd_corners_t* c)
1491 const gmx_domdec_comm_t* comm;
1492 const gmx_domdec_zones_t* zones;
1496 zones = &comm->zones;
1498 /* Keep the compiler happy */
1502 /* The first dimension is equal for all cells */
1503 c->c[0][0] = comm->cell_x0[dim0];
1506 c->bc[0] = c->c[0][0];
1511 /* This cell row is only seen from the first row */
1512 c->c[1][0] = comm->cell_x0[dim1];
1513 /* All rows can see this row */
1514 c->c[1][1] = comm->cell_x0[dim1];
1515 if (isDlbOn(dd->comm))
1517 c->c[1][1] = std::max(comm->cell_x0[dim1], comm->zone_d1[1].mch0);
1520 /* For the multi-body distance we need the maximum */
1521 c->bc[1] = std::max(comm->cell_x0[dim1], comm->zone_d1[1].p1_0);
1524 /* Set the upper-right corner for rounding */
1525 c->cr0 = comm->cell_x1[dim0];
1530 for (int j = 0; j < 4; j++)
1532 c->c[2][j] = comm->cell_x0[dim2];
1534 if (isDlbOn(dd->comm))
1536 /* Use the maximum of the i-cells that see a j-cell */
1537 for (const auto& iZone : zones->iZones)
1539 const int iZoneIndex = iZone.iZoneIndex;
1540 for (int jZone : iZone.jZoneRange)
1544 c->c[2][jZone - 4] = std::max(
1546 comm->zone_d2[zones->shift[iZoneIndex][dim0]][zones->shift[iZoneIndex][dim1]]
1553 /* For the multi-body distance we need the maximum */
1554 c->bc[2] = comm->cell_x0[dim2];
1555 for (int i = 0; i < 2; i++)
1557 for (int j = 0; j < 2; j++)
1559 c->bc[2] = std::max(c->bc[2], comm->zone_d2[i][j].p1_0);
1565 /* Set the upper-right corner for rounding */
1566 /* Cell (0,0,0) and cell (1,0,0) can see cell 4 (0,1,1)
1567 * Only cell (0,0,0) can see cell 7 (1,1,1)
1569 c->cr1[0] = comm->cell_x1[dim1];
1570 c->cr1[3] = comm->cell_x1[dim1];
1571 if (isDlbOn(dd->comm))
1573 c->cr1[0] = std::max(comm->cell_x1[dim1], comm->zone_d1[1].mch1);
1576 /* For the multi-body distance we need the maximum */
1577 c->bcr1 = std::max(comm->cell_x1[dim1], comm->zone_d1[1].p1_1);
1584 /*! \brief Add the atom groups we need to send in this pulse from this
1585 * zone to \p localAtomGroups and \p work. */
1586 static void get_zone_pulse_cgs(gmx_domdec_t* dd,
1591 gmx::ArrayRef<const int> globalAtomGroupIndices,
1600 bool distanceIsTriclinic,
1607 const dd_corners_t* c,
1608 const rvec sf2_round,
1609 gmx_bool bDistBonded,
1614 gmx::ArrayRef<const int> cginfo,
1615 std::vector<int>* localAtomGroups,
1616 dd_comm_setup_work_t* work)
1618 gmx_domdec_comm_t* comm;
1620 gmx_bool bDistMB_pulse;
1622 real r2, rb2, r, tric_sh;
1629 bScrew = (dd->unitCellInfo.haveScrewPBC && dim == XX);
1631 bDistMB_pulse = (bDistMB && bDistBonded);
1633 /* Unpack the work data */
1634 std::vector<int>& ibuf = work->atomGroupBuffer;
1635 std::vector<gmx::RVec>& vbuf = work->positionBuffer;
1639 for (cg = cg0; cg < cg1; cg++)
1643 if (!distanceIsTriclinic)
1645 /* Rectangular direction, easy */
1646 r = cg_cm[cg][dim] - c->c[dim_ind][zone];
1653 r = cg_cm[cg][dim] - c->bc[dim_ind];
1659 /* Rounding gives at most a 16% reduction
1660 * in communicated atoms
1662 if (dim_ind >= 1 && (zonei == 1 || zonei == 2))
1664 r = cg_cm[cg][dim0] - c->cr0;
1665 /* This is the first dimension, so always r >= 0 */
1672 if (dim_ind == 2 && (zonei == 2 || zonei == 3))
1674 r = cg_cm[cg][dim1] - c->cr1[zone];
1681 r = cg_cm[cg][dim1] - c->bcr1;
1691 /* Triclinic direction, more complicated */
1694 /* Rounding, conservative as the skew_fac multiplication
1695 * will slightly underestimate the distance.
1697 if (dim_ind >= 1 && (zonei == 1 || zonei == 2))
1699 rn[dim0] = cg_cm[cg][dim0] - c->cr0;
1700 for (i = dim0 + 1; i < DIM; i++)
1702 rn[dim0] -= cg_cm[cg][i] * v_0[i][dim0];
1704 r2 = rn[dim0] * rn[dim0] * sf2_round[dim0];
1707 rb[dim0] = rn[dim0];
1710 /* Take care that the cell planes along dim0 might not
1711 * be orthogonal to those along dim1 and dim2.
1713 for (i = 1; i <= dim_ind; i++)
1716 if (normal[dim0][dimd] > 0)
1718 rn[dimd] -= rn[dim0] * normal[dim0][dimd];
1721 rb[dimd] -= rb[dim0] * normal[dim0][dimd];
1726 if (dim_ind == 2 && (zonei == 2 || zonei == 3))
1728 GMX_ASSERT(dim1 >= 0 && dim1 < DIM, "Must have a valid dimension index");
1729 rn[dim1] += cg_cm[cg][dim1] - c->cr1[zone];
1731 for (i = dim1 + 1; i < DIM; i++)
1733 tric_sh -= cg_cm[cg][i] * v_1[i][dim1];
1735 rn[dim1] += tric_sh;
1738 r2 += rn[dim1] * rn[dim1] * sf2_round[dim1];
1739 /* Take care of coupling of the distances
1740 * to the planes along dim0 and dim1 through dim2.
1742 r2 -= rn[dim0] * rn[dim1] * skew_fac_01;
1743 /* Take care that the cell planes along dim1
1744 * might not be orthogonal to that along dim2.
1746 if (normal[dim1][dim2] > 0)
1748 rn[dim2] -= rn[dim1] * normal[dim1][dim2];
1753 rb[dim1] += cg_cm[cg][dim1] - c->bcr1 + tric_sh;
1756 rb2 += rb[dim1] * rb[dim1] * sf2_round[dim1];
1757 /* Take care of coupling of the distances
1758 * to the planes along dim0 and dim1 through dim2.
1760 rb2 -= rb[dim0] * rb[dim1] * skew_fac_01;
1761 /* Take care that the cell planes along dim1
1762 * might not be orthogonal to that along dim2.
1764 if (normal[dim1][dim2] > 0)
1766 rb[dim2] -= rb[dim1] * normal[dim1][dim2];
1771 /* The distance along the communication direction */
1772 rn[dim] += cg_cm[cg][dim] - c->c[dim_ind][zone];
1774 for (i = dim + 1; i < DIM; i++)
1776 tric_sh -= cg_cm[cg][i] * v_d[i][dim];
1781 r2 += rn[dim] * rn[dim] * skew_fac2_d;
1782 /* Take care of coupling of the distances
1783 * to the planes along dim0 and dim1 through dim2.
1785 if (dim_ind == 1 && zonei == 1)
1787 r2 -= rn[dim0] * rn[dim] * skew_fac_01;
1793 GMX_ASSERT(dim >= 0 && dim < DIM, "Must have a valid dimension index");
1794 rb[dim] += cg_cm[cg][dim] - c->bc[dim_ind] + tric_sh;
1797 rb2 += rb[dim] * rb[dim] * skew_fac2_d;
1798 /* Take care of coupling of the distances
1799 * to the planes along dim0 and dim1 through dim2.
1801 if (dim_ind == 1 && zonei == 1)
1803 rb2 -= rb[dim0] * rb[dim] * skew_fac_01;
1810 || (bDistBonded && ((bDistMB && rb2 < r_bcomm2) || (bDist2B && r2 < r_bcomm2))
1812 || (GET_CGINFO_BOND_INTER(cginfo[cg])
1813 && missing_link(*comm->bondedLinks, globalAtomGroupIndices[cg], *dd->ga2la)))))
1815 /* Store the local and global atom group indices and position */
1816 localAtomGroups->push_back(cg);
1817 ibuf.push_back(globalAtomGroupIndices[cg]);
1821 if (dd->ci[dim] == 0)
1823 /* Correct cg_cm for pbc */
1824 rvec_add(cg_cm[cg], box[dim], posPbc);
1827 posPbc[YY] = box[YY][YY] - posPbc[YY];
1828 posPbc[ZZ] = box[ZZ][ZZ] - posPbc[ZZ];
1833 copy_rvec(cg_cm[cg], posPbc);
1835 vbuf.emplace_back(posPbc[XX], posPbc[YY], posPbc[ZZ]);
1842 work->nsend_zone = nsend_z;
1846 static void clearCommSetupData(dd_comm_setup_work_t* work)
1848 work->localAtomGroupBuffer.clear();
1849 work->atomGroupBuffer.clear();
1850 work->positionBuffer.clear();
1852 work->nsend_zone = 0;
1855 //! Prepare DD communication.
1856 static void setup_dd_communication(gmx_domdec_t* dd, matrix box, gmx_ddbox_t* ddbox, t_forcerec* fr, t_state* state)
1858 int dim_ind, dim, dim0, dim1, dim2, dimd, nat_tot;
1859 int nzone, nzone_send, zone, zonei, cg0, cg1;
1861 int * zone_cg_range, pos_cg;
1862 gmx_domdec_comm_t* comm;
1863 gmx_domdec_zones_t* zones;
1864 gmx_domdec_comm_dim_t* cd;
1865 gmx_bool bBondComm, bDist2B, bDistMB, bDistBonded;
1866 dd_corners_t corners;
1867 rvec * normal, *v_d, *v_0 = nullptr, *v_1 = nullptr;
1868 real skew_fac2_d, skew_fac_01;
1873 fprintf(debug, "Setting up DD communication\n");
1878 if (comm->dth.empty())
1880 /* Initialize the thread data.
1881 * This can not be done in init_domain_decomposition,
1882 * as the numbers of threads is determined later.
1884 int numThreads = gmx_omp_nthreads_get(emntDomdec);
1885 comm->dth.resize(numThreads);
1888 bBondComm = comm->systemInfo.filterBondedCommunication;
1890 /* Do we need to determine extra distances for multi-body bondeds? */
1891 bDistMB = (comm->systemInfo.haveInterDomainMultiBodyBondeds && isDlbOn(dd->comm) && dd->ndim > 1);
1893 /* Do we need to determine extra distances for only two-body bondeds? */
1894 bDist2B = (bBondComm && !bDistMB);
1896 const real r_comm2 =
1897 gmx::square(domainToDomainIntoAtomToDomainCutoff(comm->systemInfo, comm->systemInfo.cutoff));
1898 const real r_bcomm2 =
1899 gmx::square(domainToDomainIntoAtomToDomainCutoff(comm->systemInfo, comm->cutoff_mbody));
1903 fprintf(debug, "bBondComm %s, r_bc %f\n", gmx::boolToString(bBondComm), std::sqrt(r_bcomm2));
1906 zones = &comm->zones;
1909 dim1 = (dd->ndim >= 2 ? dd->dim[1] : -1);
1910 dim2 = (dd->ndim >= 3 ? dd->dim[2] : -1);
1912 set_dd_corners(dd, dim0, dim1, dim2, bDistMB, &corners);
1914 /* Triclinic stuff */
1915 normal = ddbox->normal;
1919 v_0 = ddbox->v[dim0];
1920 if (ddbox->tric_dir[dim0] && ddbox->tric_dir[dim1])
1922 /* Determine the coupling coefficient for the distances
1923 * to the cell planes along dim0 and dim1 through dim2.
1924 * This is required for correct rounding.
1926 skew_fac_01 = ddbox->v[dim0][dim1 + 1][dim0] * ddbox->v[dim1][dim1 + 1][dim1];
1929 fprintf(debug, "\nskew_fac_01 %f\n", skew_fac_01);
1935 v_1 = ddbox->v[dim1];
1938 zone_cg_range = zones->cg_range;
1939 gmx::ArrayRef<cginfo_mb_t> cginfo_mb = fr->cginfo_mb;
1941 zone_cg_range[0] = 0;
1942 zone_cg_range[1] = dd->ncg_home;
1943 comm->zone_ncg1[0] = dd->ncg_home;
1944 pos_cg = dd->ncg_home;
1946 nat_tot = comm->atomRanges.numHomeAtoms();
1948 for (dim_ind = 0; dim_ind < dd->ndim; dim_ind++)
1950 dim = dd->dim[dim_ind];
1951 cd = &comm->cd[dim_ind];
1953 /* Check if we need to compute triclinic distances along this dim */
1954 bool distanceIsTriclinic = false;
1955 for (int i = 0; i <= dim_ind; i++)
1957 if (ddbox->tric_dir[dd->dim[i]])
1959 distanceIsTriclinic = true;
1963 if (dim >= ddbox->npbcdim && dd->ci[dim] == 0)
1965 /* No pbc in this dimension, the first node should not comm. */
1973 v_d = ddbox->v[dim];
1974 skew_fac2_d = gmx::square(ddbox->skew_fac[dim]);
1976 cd->receiveInPlace = true;
1977 for (int p = 0; p < cd->numPulses(); p++)
1979 /* Only atoms communicated in the first pulse are used
1980 * for multi-body bonded interactions or for bBondComm.
1982 bDistBonded = ((bDistMB || bDist2B) && p == 0);
1984 gmx_domdec_ind_t* ind = &cd->ind[p];
1986 /* Thread 0 writes in the global index array */
1988 clearCommSetupData(&comm->dth[0]);
1990 for (zone = 0; zone < nzone_send; zone++)
1992 if (dim_ind > 0 && distanceIsTriclinic)
1994 /* Determine slightly more optimized skew_fac's
1996 * This reduces the number of communicated atoms
1997 * by about 10% for 3D DD of rhombic dodecahedra.
1999 for (dimd = 0; dimd < dim; dimd++)
2001 sf2_round[dimd] = 1;
2002 if (ddbox->tric_dir[dimd])
2004 for (int i = dd->dim[dimd] + 1; i < DIM; i++)
2006 /* If we are shifted in dimension i
2007 * and the cell plane is tilted forward
2008 * in dimension i, skip this coupling.
2010 if (!(zones->shift[nzone + zone][i] && ddbox->v[dimd][i][dimd] >= 0))
2012 sf2_round[dimd] += gmx::square(ddbox->v[dimd][i][dimd]);
2015 sf2_round[dimd] = 1 / sf2_round[dimd];
2020 zonei = zone_perm[dim_ind][zone];
2023 /* Here we permutate the zones to obtain a convenient order
2024 * for neighbor searching
2026 cg0 = zone_cg_range[zonei];
2027 cg1 = zone_cg_range[zonei + 1];
2031 /* Look only at the cg's received in the previous grid pulse
2033 cg1 = zone_cg_range[nzone + zone + 1];
2034 cg0 = cg1 - cd->ind[p - 1].nrecv[zone];
2037 const int numThreads = gmx::ssize(comm->dth);
2038 #pragma omp parallel for num_threads(numThreads) schedule(static)
2039 for (int th = 0; th < numThreads; th++)
2043 dd_comm_setup_work_t& work = comm->dth[th];
2045 /* Retain data accumulated into buffers of thread 0 */
2048 clearCommSetupData(&work);
2051 int cg0_th = cg0 + ((cg1 - cg0) * th) / numThreads;
2052 int cg1_th = cg0 + ((cg1 - cg0) * (th + 1)) / numThreads;
2054 /* Get the cg's for this pulse in this zone */
2055 get_zone_pulse_cgs(dd,
2060 dd->globalAtomGroupIndices,
2069 distanceIsTriclinic,
2082 state->x.rvec_array(),
2084 th == 0 ? &ind->index : &work.localAtomGroupBuffer,
2087 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
2090 std::vector<int>& atomGroups = comm->dth[0].atomGroupBuffer;
2091 std::vector<gmx::RVec>& positions = comm->dth[0].positionBuffer;
2092 ind->nsend[zone] = comm->dth[0].nsend_zone;
2093 /* Append data of threads>=1 to the communication buffers */
2094 for (int th = 1; th < numThreads; th++)
2096 const dd_comm_setup_work_t& dth = comm->dth[th];
2098 ind->index.insert(ind->index.end(),
2099 dth.localAtomGroupBuffer.begin(),
2100 dth.localAtomGroupBuffer.end());
2102 atomGroups.end(), dth.atomGroupBuffer.begin(), dth.atomGroupBuffer.end());
2104 positions.end(), dth.positionBuffer.begin(), dth.positionBuffer.end());
2105 comm->dth[0].nat += dth.nat;
2106 ind->nsend[zone] += dth.nsend_zone;
2109 /* Clear the counts in case we do not have pbc */
2110 for (zone = nzone_send; zone < nzone; zone++)
2112 ind->nsend[zone] = 0;
2114 ind->nsend[nzone] = ind->index.size();
2115 ind->nsend[nzone + 1] = comm->dth[0].nat;
2116 /* Communicate the number of cg's and atoms to receive */
2117 ddSendrecv(dd, dim_ind, dddirBackward, ind->nsend, nzone + 2, ind->nrecv, nzone + 2);
2121 /* We can receive in place if only the last zone is not empty */
2122 for (zone = 0; zone < nzone - 1; zone++)
2124 if (ind->nrecv[zone] > 0)
2126 cd->receiveInPlace = false;
2131 int receiveBufferSize = 0;
2132 if (!cd->receiveInPlace)
2134 receiveBufferSize = ind->nrecv[nzone];
2136 /* These buffer are actually only needed with in-place */
2137 DDBufferAccess<int> globalAtomGroupBuffer(comm->intBuffer, receiveBufferSize);
2138 DDBufferAccess<gmx::RVec> rvecBuffer(comm->rvecBuffer, receiveBufferSize);
2140 dd_comm_setup_work_t& work = comm->dth[0];
2142 /* Make space for the global cg indices */
2143 int numAtomGroupsNew = pos_cg + ind->nrecv[nzone];
2144 dd->globalAtomGroupIndices.resize(numAtomGroupsNew);
2145 /* Communicate the global cg indices */
2146 gmx::ArrayRef<int> integerBufferRef;
2147 if (cd->receiveInPlace)
2149 integerBufferRef = gmx::arrayRefFromArray(
2150 dd->globalAtomGroupIndices.data() + pos_cg, ind->nrecv[nzone]);
2154 integerBufferRef = globalAtomGroupBuffer.buffer;
2156 ddSendrecv<int>(dd, dim_ind, dddirBackward, work.atomGroupBuffer, integerBufferRef);
2158 /* Make space for cg_cm */
2159 dd_resize_atominfo_and_state(fr, state, pos_cg + ind->nrecv[nzone]);
2161 /* Communicate the coordinates */
2162 gmx::ArrayRef<gmx::RVec> rvecBufferRef;
2163 if (cd->receiveInPlace)
2165 rvecBufferRef = gmx::makeArrayRef(state->x).subArray(pos_cg, ind->nrecv[nzone]);
2169 rvecBufferRef = rvecBuffer.buffer;
2171 ddSendrecv<gmx::RVec>(dd, dim_ind, dddirBackward, work.positionBuffer, rvecBufferRef);
2173 /* Make the charge group index */
2174 if (cd->receiveInPlace)
2176 zone = (p == 0 ? 0 : nzone - 1);
2177 while (zone < nzone)
2179 for (int i = 0; i < ind->nrecv[zone]; i++)
2181 int globalAtomIndex = dd->globalAtomGroupIndices[pos_cg];
2182 fr->cginfo[pos_cg] = ddcginfo(cginfo_mb, globalAtomIndex);
2187 comm->zone_ncg1[nzone + zone] = ind->nrecv[zone];
2190 zone_cg_range[nzone + zone] = pos_cg;
2195 /* This part of the code is never executed with bBondComm. */
2196 merge_cg_buffers(nzone,
2200 dd->globalAtomGroupIndices,
2201 integerBufferRef.data(),
2206 pos_cg += ind->nrecv[nzone];
2208 nat_tot += ind->nrecv[nzone + 1];
2210 if (!cd->receiveInPlace)
2212 /* Store the atom block for easy copying of communication buffers */
2213 make_cell2at_index(cd, nzone, zone_cg_range[nzone]);
2218 comm->atomRanges.setEnd(DDAtomRanges::Type::Zones, nat_tot);
2222 /* We don't need to update cginfo, since that was alrady done above.
2223 * So we pass NULL for the forcerec.
2225 dd_set_cginfo(dd->globalAtomGroupIndices, dd->ncg_home, dd->globalAtomGroupIndices.size(), nullptr);
2230 fprintf(debug, "Finished setting up DD communication, zones:");
2231 for (c = 0; c < zones->n; c++)
2233 fprintf(debug, " %d", zones->cg_range[c + 1] - zones->cg_range[c]);
2235 fprintf(debug, "\n");
2239 //! Set boundaries for the charge group range.
2240 static void set_cg_boundaries(gmx_domdec_zones_t* zones)
2242 for (auto& iZone : zones->iZones)
2244 iZone.iAtomRange = gmx::Range<int>(0, zones->cg_range[iZone.iZoneIndex + 1]);
2245 iZone.jAtomRange = gmx::Range<int>(zones->cg_range[iZone.jZoneRange.begin()],
2246 zones->cg_range[iZone.jZoneRange.end()]);
2250 /*! \brief Set zone dimensions for zones \p zone_start to \p zone_end-1
2252 * Also sets the atom density for the home zone when \p zone_start=0.
2253 * For this \p numMovedChargeGroupsInHomeZone needs to be passed to tell
2254 * how many charge groups will move but are still part of the current range.
2255 * \todo When converting domdec to use proper classes, all these variables
2256 * should be private and a method should return the correct count
2257 * depending on an internal state.
2259 * \param[in,out] dd The domain decomposition struct
2260 * \param[in] box The box
2261 * \param[in] ddbox The domain decomposition box struct
2262 * \param[in] zone_start The start of the zone range to set sizes for
2263 * \param[in] zone_end The end of the zone range to set sizes for
2264 * \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
2266 static void set_zones_size(gmx_domdec_t* dd,
2268 const gmx_ddbox_t* ddbox,
2271 int numMovedChargeGroupsInHomeZone)
2273 gmx_domdec_comm_t* comm;
2274 gmx_domdec_zones_t* zones;
2283 zones = &comm->zones;
2285 /* Do we need to determine extra distances for multi-body bondeds? */
2286 bDistMB = (comm->systemInfo.haveInterDomainMultiBodyBondeds && isDlbOn(dd->comm) && dd->ndim > 1);
2288 for (z = zone_start; z < zone_end; z++)
2290 /* Copy cell limits to zone limits.
2291 * Valid for non-DD dims and non-shifted dims.
2293 copy_rvec(comm->cell_x0, zones->size[z].x0);
2294 copy_rvec(comm->cell_x1, zones->size[z].x1);
2297 for (d = 0; d < dd->ndim; d++)
2301 for (z = 0; z < zones->n; z++)
2303 /* With a staggered grid we have different sizes
2304 * for non-shifted dimensions.
2306 if (isDlbOn(dd->comm) && zones->shift[z][dim] == 0)
2310 zones->size[z].x0[dim] = comm->zone_d1[zones->shift[z][dd->dim[d - 1]]].min0;
2311 zones->size[z].x1[dim] = comm->zone_d1[zones->shift[z][dd->dim[d - 1]]].max1;
2315 zones->size[z].x0[dim] =
2316 comm->zone_d2[zones->shift[z][dd->dim[d - 2]]][zones->shift[z][dd->dim[d - 1]]]
2318 zones->size[z].x1[dim] =
2319 comm->zone_d2[zones->shift[z][dd->dim[d - 2]]][zones->shift[z][dd->dim[d - 1]]]
2325 rcs = comm->systemInfo.cutoff;
2326 rcmbs = comm->cutoff_mbody;
2327 if (ddbox->tric_dir[dim])
2329 rcs /= ddbox->skew_fac[dim];
2330 rcmbs /= ddbox->skew_fac[dim];
2333 /* Set the lower limit for the shifted zone dimensions */
2334 for (z = zone_start; z < zone_end; z++)
2336 if (zones->shift[z][dim] > 0)
2339 if (!isDlbOn(dd->comm) || d == 0)
2341 zones->size[z].x0[dim] = comm->cell_x1[dim];
2342 zones->size[z].x1[dim] = comm->cell_x1[dim] + rcs;
2346 /* Here we take the lower limit of the zone from
2347 * the lowest domain of the zone below.
2351 zones->size[z].x0[dim] = comm->zone_d1[zones->shift[z][dd->dim[d - 1]]].min1;
2357 zones->size[z].x0[dim] = zones->size[zone_perm[2][z - 4]].x0[dim];
2361 zones->size[z].x0[dim] =
2362 comm->zone_d2[zones->shift[z][dd->dim[d - 2]]][zones->shift[z][dd->dim[d - 1]]]
2366 /* A temporary limit, is updated below */
2367 zones->size[z].x1[dim] = zones->size[z].x0[dim];
2371 for (size_t zi = 0; zi < zones->iZones.size(); zi++)
2373 if (zones->shift[zi][dim] == 0)
2375 /* This takes the whole zone into account.
2376 * With multiple pulses this will lead
2377 * to a larger zone then strictly necessary.
2379 zones->size[z].x1[dim] = std::max(zones->size[z].x1[dim],
2380 zones->size[zi].x1[dim] + rcmbs);
2388 /* Loop over the i-zones to set the upper limit of each
2391 for (const auto& iZone : zones->iZones)
2393 const int zi = iZone.iZoneIndex;
2394 if (zones->shift[zi][dim] == 0)
2396 /* We should only use zones up to zone_end */
2397 const auto& jZoneRangeFull = iZone.jZoneRange;
2398 if (zone_end <= *jZoneRangeFull.begin())
2402 const gmx::Range<int> jZoneRange(*jZoneRangeFull.begin(),
2403 std::min(*jZoneRangeFull.end(), zone_end));
2404 for (int jZone : jZoneRange)
2406 if (zones->shift[jZone][dim] > 0)
2408 zones->size[jZone].x1[dim] =
2409 std::max(zones->size[jZone].x1[dim], zones->size[zi].x1[dim] + rcs);
2416 for (z = zone_start; z < zone_end; z++)
2418 /* Initialization only required to keep the compiler happy */
2419 rvec corner_min = { 0, 0, 0 }, corner_max = { 0, 0, 0 }, corner;
2422 /* To determine the bounding box for a zone we need to find
2423 * the extreme corners of 4, 2 or 1 corners.
2425 nc = 1 << (ddbox->nboundeddim - 1);
2427 for (c = 0; c < nc; c++)
2429 /* Set up a zone corner at x=0, ignoring trilinic couplings */
2433 corner[YY] = zones->size[z].x0[YY];
2437 corner[YY] = zones->size[z].x1[YY];
2441 corner[ZZ] = zones->size[z].x0[ZZ];
2445 corner[ZZ] = zones->size[z].x1[ZZ];
2447 if (dd->ndim == 1 && dd->dim[0] < ZZ && ZZ < dd->unitCellInfo.npbcdim
2448 && box[ZZ][1 - dd->dim[0]] != 0)
2450 /* With 1D domain decomposition the cg's are not in
2451 * the triclinic box, but triclinic x-y and rectangular y/x-z.
2452 * Shift the corner of the z-vector back to along the box
2453 * vector of dimension d, so it will later end up at 0 along d.
2454 * This can affect the location of this corner along dd->dim[0]
2455 * through the matrix operation below if box[d][dd->dim[0]]!=0.
2457 int d = 1 - dd->dim[0];
2459 corner[d] -= corner[ZZ] * box[ZZ][d] / box[ZZ][ZZ];
2461 /* Apply the triclinic couplings */
2462 for (i = YY; i < ddbox->npbcdim && i < DIM; i++)
2464 for (j = XX; j < i; j++)
2466 corner[j] += corner[i] * box[i][j] / box[i][i];
2471 copy_rvec(corner, corner_min);
2472 copy_rvec(corner, corner_max);
2476 for (i = 0; i < DIM; i++)
2478 corner_min[i] = std::min(corner_min[i], corner[i]);
2479 corner_max[i] = std::max(corner_max[i], corner[i]);
2483 /* Copy the extreme cornes without offset along x */
2484 for (i = 0; i < DIM; i++)
2486 zones->size[z].bb_x0[i] = corner_min[i];
2487 zones->size[z].bb_x1[i] = corner_max[i];
2489 /* Add the offset along x */
2490 zones->size[z].bb_x0[XX] += zones->size[z].x0[XX];
2491 zones->size[z].bb_x1[XX] += zones->size[z].x1[XX];
2494 if (zone_start == 0)
2497 for (dim = 0; dim < DIM; dim++)
2499 vol *= zones->size[0].x1[dim] - zones->size[0].x0[dim];
2502 (zones->cg_range[1] - zones->cg_range[0] - numMovedChargeGroupsInHomeZone) / vol;
2507 for (z = zone_start; z < zone_end; z++)
2510 "zone %d %6.3f - %6.3f %6.3f - %6.3f %6.3f - %6.3f\n",
2512 zones->size[z].x0[XX],
2513 zones->size[z].x1[XX],
2514 zones->size[z].x0[YY],
2515 zones->size[z].x1[YY],
2516 zones->size[z].x0[ZZ],
2517 zones->size[z].x1[ZZ]);
2519 "zone %d bb %6.3f - %6.3f %6.3f - %6.3f %6.3f - %6.3f\n",
2521 zones->size[z].bb_x0[XX],
2522 zones->size[z].bb_x1[XX],
2523 zones->size[z].bb_x0[YY],
2524 zones->size[z].bb_x1[YY],
2525 zones->size[z].bb_x0[ZZ],
2526 zones->size[z].bb_x1[ZZ]);
2531 /*! \brief Order data in \p dataToSort according to \p sort
2533 * Note: both buffers should have at least \p sort.size() elements.
2535 template<typename T>
2536 static void orderVector(gmx::ArrayRef<const gmx_cgsort_t> sort,
2537 gmx::ArrayRef<T> dataToSort,
2538 gmx::ArrayRef<T> sortBuffer)
2540 GMX_ASSERT(dataToSort.size() >= sort.size(), "The vector needs to be sufficiently large");
2541 GMX_ASSERT(sortBuffer.size() >= sort.size(),
2542 "The sorting buffer needs to be sufficiently large");
2544 /* Order the data into the temporary buffer */
2546 for (const gmx_cgsort_t& entry : sort)
2548 sortBuffer[i++] = dataToSort[entry.ind];
2551 /* Copy back to the original array */
2552 std::copy(sortBuffer.begin(), sortBuffer.begin() + sort.size(), dataToSort.begin());
2555 /*! \brief Order data in \p dataToSort according to \p sort
2557 * Note: \p vectorToSort should have at least \p sort.size() elements,
2558 * \p workVector is resized when it is too small.
2560 template<typename T>
2561 static void orderVector(gmx::ArrayRef<const gmx_cgsort_t> sort,
2562 gmx::ArrayRef<T> vectorToSort,
2563 std::vector<T>* workVector)
2565 if (gmx::index(workVector->size()) < sort.ssize())
2567 workVector->resize(sort.size());
2569 orderVector<T>(sort, vectorToSort, *workVector);
2572 //! Returns the sorting order for atoms based on the nbnxn grid order in sort
2573 static void dd_sort_order_nbnxn(const t_forcerec* fr, std::vector<gmx_cgsort_t>* sort)
2575 gmx::ArrayRef<const int> atomOrder = fr->nbv->getLocalAtomOrder();
2577 /* Using push_back() instead of this resize results in much slower code */
2578 sort->resize(atomOrder.size());
2579 gmx::ArrayRef<gmx_cgsort_t> buffer = *sort;
2580 size_t numSorted = 0;
2581 for (int i : atomOrder)
2585 /* The values of nsc and ind_gl are not used in this case */
2586 buffer[numSorted++].ind = i;
2589 sort->resize(numSorted);
2592 //! Returns the sorting state for DD.
2593 static void dd_sort_state(gmx_domdec_t* dd, t_forcerec* fr, t_state* state)
2595 gmx_domdec_sort_t* sort = dd->comm->sort.get();
2597 dd_sort_order_nbnxn(fr, &sort->sorted);
2599 /* We alloc with the old size, since cgindex is still old */
2600 DDBufferAccess<gmx::RVec> rvecBuffer(dd->comm->rvecBuffer, dd->ncg_home);
2602 /* Set the new home atom/charge group count */
2603 dd->ncg_home = sort->sorted.size();
2606 fprintf(debug, "Set the new home atom count to %d\n", dd->ncg_home);
2609 /* Reorder the state */
2610 gmx::ArrayRef<const gmx_cgsort_t> cgsort = sort->sorted;
2611 GMX_RELEASE_ASSERT(cgsort.ssize() == dd->ncg_home, "We should sort all the home atom groups");
2613 if (state->flags & (1 << estX))
2615 orderVector(cgsort, makeArrayRef(state->x), rvecBuffer.buffer);
2617 if (state->flags & (1 << estV))
2619 orderVector(cgsort, makeArrayRef(state->v), rvecBuffer.buffer);
2621 if (state->flags & (1 << estCGP))
2623 orderVector(cgsort, makeArrayRef(state->cg_p), rvecBuffer.buffer);
2626 /* Reorder the global cg index */
2627 orderVector<int>(cgsort, dd->globalAtomGroupIndices, &sort->intBuffer);
2628 /* Reorder the cginfo */
2629 orderVector<int>(cgsort, fr->cginfo, &sort->intBuffer);
2630 /* Set the home atom number */
2631 dd->comm->atomRanges.setEnd(DDAtomRanges::Type::Home, dd->ncg_home);
2633 /* The atoms are now exactly in grid order, update the grid order */
2634 fr->nbv->setLocalAtomOrder();
2637 //! Accumulates load statistics.
2638 static void add_dd_statistics(gmx_domdec_t* dd)
2640 gmx_domdec_comm_t* comm = dd->comm;
2642 for (int i = 0; i < static_cast<int>(DDAtomRanges::Type::Number); i++)
2644 auto range = static_cast<DDAtomRanges::Type>(i);
2645 comm->sum_nat[i] += comm->atomRanges.end(range) - comm->atomRanges.start(range);
2650 void reset_dd_statistics_counters(gmx_domdec_t* dd)
2652 gmx_domdec_comm_t* comm = dd->comm;
2654 /* Reset all the statistics and counters for total run counting */
2655 for (int i = 0; i < static_cast<int>(DDAtomRanges::Type::Number); i++)
2657 comm->sum_nat[i] = 0;
2661 comm->load_step = 0;
2664 clear_ivec(comm->load_lim);
2669 void print_dd_statistics(const t_commrec* cr, const t_inputrec* ir, FILE* fplog)
2671 gmx_domdec_comm_t* comm = cr->dd->comm;
2673 const int numRanges = static_cast<int>(DDAtomRanges::Type::Number);
2674 gmx_sumd(numRanges, comm->sum_nat, cr);
2676 if (fplog == nullptr)
2681 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");
2683 for (int i = static_cast<int>(DDAtomRanges::Type::Zones); i < numRanges; i++)
2685 auto range = static_cast<DDAtomRanges::Type>(i);
2686 double av = comm->sum_nat[i] / comm->ndecomp;
2689 case DDAtomRanges::Type::Zones:
2690 fprintf(fplog, " av. #atoms communicated per step for force: %d x %.1f\n", 2, av);
2692 case DDAtomRanges::Type::Vsites:
2693 if (cr->dd->vsite_comm)
2696 " av. #atoms communicated per step for vsites: %d x %.1f\n",
2697 (EEL_PME(ir->coulombtype) || ir->coulombtype == eelEWALD) ? 3 : 2,
2701 case DDAtomRanges::Type::Constraints:
2702 if (cr->dd->constraint_comm)
2705 " av. #atoms communicated per step for LINCS: %d x %.1f\n",
2710 default: gmx_incons(" Unknown type for DD statistics");
2713 fprintf(fplog, "\n");
2715 if (comm->ddSettings.recordLoad && EI_DYNAMICS(ir->eI))
2717 print_dd_load_av(fplog, cr->dd);
2721 //!\brief TODO Remove fplog when group scheme and charge groups are gone
2722 void dd_partition_system(FILE* fplog,
2723 const gmx::MDLogger& mdlog,
2725 const t_commrec* cr,
2726 gmx_bool bMasterState,
2728 t_state* state_global,
2729 const gmx_mtop_t& top_global,
2730 const t_inputrec* ir,
2731 gmx::ImdSession* imdSession,
2733 t_state* state_local,
2734 gmx::ForceBuffers* f,
2735 gmx::MDAtoms* mdAtoms,
2736 gmx_localtop_t* top_local,
2738 gmx::VirtualSitesHandler* vsite,
2739 gmx::Constraints* constr,
2741 gmx_wallcycle* wcycle,
2745 gmx_domdec_comm_t* comm;
2746 gmx_ddbox_t ddbox = { 0 };
2747 int64_t step_pcoupl;
2748 rvec cell_ns_x0, cell_ns_x1;
2749 int ncgindex_set, ncg_moved, nat_f_novirsum;
2750 gmx_bool bBoxChanged, bNStGlobalComm, bDoDLB, bCheckWhetherToTurnDlbOn, bLogLoad;
2756 wallcycle_start(wcycle, ewcDOMDEC);
2761 // TODO if the update code becomes accessible here, use
2762 // upd->deform for this logic.
2763 bBoxChanged = (bMasterState || inputrecDeform(ir));
2764 if (ir->epc != epcNO)
2766 /* With nstpcouple > 1 pressure coupling happens.
2767 * one step after calculating the pressure.
2768 * Box scaling happens at the end of the MD step,
2769 * after the DD partitioning.
2770 * We therefore have to do DLB in the first partitioning
2771 * after an MD step where P-coupling occurred.
2772 * We need to determine the last step in which p-coupling occurred.
2773 * MRS -- need to validate this for vv?
2775 int n = ir->nstpcouple;
2778 step_pcoupl = step - 1;
2782 step_pcoupl = ((step - 1) / n) * n + 1;
2784 if (step_pcoupl >= comm->partition_step)
2790 bNStGlobalComm = (step % nstglobalcomm == 0);
2798 /* Should we do dynamic load balacing this step?
2799 * Since it requires (possibly expensive) global communication,
2800 * we might want to do DLB less frequently.
2802 if (bBoxChanged || ir->epc != epcNO)
2804 bDoDLB = bBoxChanged;
2808 bDoDLB = bNStGlobalComm;
2812 /* Check if we have recorded loads on the nodes */
2813 if (comm->ddSettings.recordLoad && dd_load_count(comm) > 0)
2815 bCheckWhetherToTurnDlbOn = dd_dlb_get_should_check_whether_to_turn_dlb_on(dd);
2817 /* Print load every nstlog, first and last step to the log file */
2818 bLogLoad = ((ir->nstlog > 0 && step % ir->nstlog == 0) || comm->n_load_collect == 0
2819 || (ir->nsteps >= 0 && (step + ir->nstlist > ir->init_step + ir->nsteps)));
2821 /* Avoid extra communication due to verbose screen output
2822 * when nstglobalcomm is set.
2824 if (bDoDLB || bLogLoad || bCheckWhetherToTurnDlbOn
2825 || (bVerbose && (ir->nstlist == 0 || nstglobalcomm <= ir->nstlist)))
2827 get_load_distribution(dd, wcycle);
2832 GMX_LOG(mdlog.info).asParagraph().appendText(dd_print_load(dd, step - 1));
2836 dd_print_load_verbose(dd);
2839 comm->n_load_collect++;
2845 /* Add the measured cycles to the running average */
2846 const float averageFactor = 0.1F;
2847 comm->cyclesPerStepDlbExpAverage =
2848 (1 - averageFactor) * comm->cyclesPerStepDlbExpAverage
2849 + averageFactor * comm->cycl[ddCyclStep] / comm->cycl_n[ddCyclStep];
2851 if (comm->dlbState == DlbState::onCanTurnOff
2852 && dd->comm->n_load_have % c_checkTurnDlbOffInterval == c_checkTurnDlbOffInterval - 1)
2854 gmx_bool turnOffDlb;
2857 /* If the running averaged cycles with DLB are more
2858 * than before we turned on DLB, turn off DLB.
2859 * We will again run and check the cycles without DLB
2860 * and we can then decide if to turn off DLB forever.
2862 turnOffDlb = (comm->cyclesPerStepDlbExpAverage > comm->cyclesPerStepBeforeDLB);
2864 dd_bcast(dd, sizeof(turnOffDlb), &turnOffDlb);
2867 /* To turn off DLB, we need to redistribute the atoms */
2868 dd_collect_state(dd, state_local, state_global);
2869 bMasterState = TRUE;
2870 turn_off_dlb(mdlog, dd, step);
2874 else if (bCheckWhetherToTurnDlbOn)
2876 gmx_bool turnOffDlbForever = FALSE;
2877 gmx_bool turnOnDlb = FALSE;
2879 /* Since the timings are node dependent, the master decides */
2882 /* If we recently turned off DLB, we want to check if
2883 * performance is better without DLB. We want to do this
2884 * ASAP to minimize the chance that external factors
2885 * slowed down the DLB step are gone here and we
2886 * incorrectly conclude that DLB was causing the slowdown.
2887 * So we measure one nstlist block, no running average.
2889 if (comm->haveTurnedOffDlb
2890 && comm->cycl[ddCyclStep] / comm->cycl_n[ddCyclStep] < comm->cyclesPerStepDlbExpAverage)
2892 /* After turning off DLB we ran nstlist steps in fewer
2893 * cycles than with DLB. This likely means that DLB
2894 * in not benefical, but this could be due to a one
2895 * time unlucky fluctuation, so we require two such
2896 * observations in close succession to turn off DLB
2899 if (comm->dlbSlowerPartitioningCount > 0
2900 && dd->ddp_count < comm->dlbSlowerPartitioningCount + 10 * c_checkTurnDlbOnInterval)
2902 turnOffDlbForever = TRUE;
2904 comm->haveTurnedOffDlb = false;
2905 /* Register when we last measured DLB slowdown */
2906 comm->dlbSlowerPartitioningCount = dd->ddp_count;
2910 /* Here we check if the max PME rank load is more than 0.98
2911 * the max PP force load. If so, PP DLB will not help,
2912 * since we are (almost) limited by PME. Furthermore,
2913 * DLB will cause a significant extra x/f redistribution
2914 * cost on the PME ranks, which will then surely result
2915 * in lower total performance.
2917 if (comm->ddRankSetup.usePmeOnlyRanks && dd_pme_f_ratio(dd) > 1 - DD_PERF_LOSS_DLB_ON)
2923 turnOnDlb = (dd_force_imb_perf_loss(dd) >= DD_PERF_LOSS_DLB_ON);
2929 gmx_bool turnOffDlbForever;
2931 } bools{ turnOffDlbForever, turnOnDlb };
2932 dd_bcast(dd, sizeof(bools), &bools);
2933 if (bools.turnOffDlbForever)
2935 turn_off_dlb_forever(mdlog, dd, step);
2937 else if (bools.turnOnDlb)
2939 turn_on_dlb(mdlog, dd, step);
2944 comm->n_load_have++;
2950 /* Clear the old state */
2951 clearDDStateIndices(dd, false);
2954 auto xGlobal = positionsFromStatePointer(state_global);
2956 set_ddbox(*dd, true, DDMASTER(dd) ? state_global->box : nullptr, true, xGlobal, &ddbox);
2958 distributeState(mdlog, dd, top_global, state_global, ddbox, state_local);
2960 /* Ensure that we have space for the new distribution */
2961 dd_resize_atominfo_and_state(fr, state_local, dd->ncg_home);
2963 inc_nrnb(nrnb, eNR_CGCM, comm->atomRanges.numHomeAtoms());
2965 dd_set_cginfo(dd->globalAtomGroupIndices, 0, dd->ncg_home, fr);
2967 else if (state_local->ddp_count != dd->ddp_count)
2969 if (state_local->ddp_count > dd->ddp_count)
2972 "Internal inconsistency state_local->ddp_count (%d) > dd->ddp_count (%" PRId64
2974 state_local->ddp_count,
2978 if (state_local->ddp_count_cg_gl != state_local->ddp_count)
2981 "Internal inconsistency state_local->ddp_count_cg_gl (%d) != "
2982 "state_local->ddp_count (%d)",
2983 state_local->ddp_count_cg_gl,
2984 state_local->ddp_count);
2987 /* Clear the old state */
2988 clearDDStateIndices(dd, false);
2990 /* Restore the atom group indices from state_local */
2991 restoreAtomGroups(dd, state_local);
2992 make_dd_indices(dd, 0);
2993 ncgindex_set = dd->ncg_home;
2995 inc_nrnb(nrnb, eNR_CGCM, comm->atomRanges.numHomeAtoms());
2997 dd_set_cginfo(dd->globalAtomGroupIndices, 0, dd->ncg_home, fr);
2999 set_ddbox(*dd, bMasterState, state_local->box, true, state_local->x, &ddbox);
3001 bRedist = isDlbOn(comm);
3005 /* We have the full state, only redistribute the cgs */
3007 /* Clear the non-home indices */
3008 clearDDStateIndices(dd, true);
3011 /* To avoid global communication, we do not recompute the extent
3012 * of the system for dims without pbc. Therefore we need to copy
3013 * the previously computed values when we do not communicate.
3015 if (!bNStGlobalComm)
3017 copy_rvec(comm->box0, ddbox.box0);
3018 copy_rvec(comm->box_size, ddbox.box_size);
3020 set_ddbox(*dd, bMasterState, state_local->box, bNStGlobalComm, state_local->x, &ddbox);
3025 /* Copy needed for dim's without pbc when avoiding communication */
3026 copy_rvec(ddbox.box0, comm->box0);
3027 copy_rvec(ddbox.box_size, comm->box_size);
3029 set_dd_cell_sizes(dd, &ddbox, dd->unitCellInfo.ddBoxIsDynamic, bMasterState, bDoDLB, step, wcycle);
3031 if (comm->ddSettings.nstDDDumpGrid > 0 && step % comm->ddSettings.nstDDDumpGrid == 0)
3033 write_dd_grid_pdb("dd_grid", step, dd, state_local->box, &ddbox);
3036 if (comm->systemInfo.useUpdateGroups)
3038 comm->updateGroupsCog->addCogs(
3039 gmx::arrayRefFromArray(dd->globalAtomGroupIndices.data(), dd->ncg_home), state_local->x);
3042 /* Check if we should sort the charge groups */
3043 const bool bSortCG = (bMasterState || bRedist);
3045 /* When repartitioning we mark atom groups that will move to neighboring
3046 * DD cells, but we do not move them right away for performance reasons.
3047 * Thus we need to keep track of how many charge groups will move for
3048 * obtaining correct local charge group / atom counts.
3053 wallcycle_sub_start(wcycle, ewcsDD_REDIST);
3055 ncgindex_set = dd->ncg_home;
3056 dd_redistribute_cg(fplog, step, dd, ddbox.tric_dir, state_local, fr, nrnb, &ncg_moved);
3058 GMX_RELEASE_ASSERT(bSortCG, "Sorting is required after redistribution");
3060 if (comm->systemInfo.useUpdateGroups)
3062 comm->updateGroupsCog->addCogs(
3063 gmx::arrayRefFromArray(dd->globalAtomGroupIndices.data(), dd->ncg_home),
3067 wallcycle_sub_stop(wcycle, ewcsDD_REDIST);
3070 // TODO: Integrate this code in the nbnxm module
3071 get_nsgrid_boundaries(ddbox.nboundeddim,
3078 as_rvec_array(state_local->x.data()),
3085 comm_dd_ns_cell_sizes(dd, &ddbox, cell_ns_x0, cell_ns_x1, step);
3090 wallcycle_sub_start(wcycle, ewcsDD_GRID);
3092 /* Sort the state on charge group position.
3093 * This enables exact restarts from this step.
3094 * It also improves performance by about 15% with larger numbers
3095 * of atoms per node.
3098 /* Fill the ns grid with the home cell,
3099 * so we can sort with the indices.
3101 set_zones_ncg_home(dd);
3103 set_zones_size(dd, state_local->box, &ddbox, 0, 1, ncg_moved);
3105 nbnxn_put_on_grid(fr->nbv.get(),
3108 comm->zones.size[0].bb_x0,
3109 comm->zones.size[0].bb_x1,
3110 comm->updateGroupsCog.get(),
3111 { 0, dd->ncg_home },
3112 comm->zones.dens_zone0,
3116 bRedist ? comm->movedBuffer.data() : nullptr);
3120 fprintf(debug, "Step %s, sorting the %d home charge groups\n", gmx_step_str(step, sbuf), dd->ncg_home);
3122 dd_sort_state(dd, fr, state_local);
3124 /* After sorting and compacting we set the correct size */
3125 state_change_natoms(state_local, comm->atomRanges.numHomeAtoms());
3127 /* Rebuild all the indices */
3131 wallcycle_sub_stop(wcycle, ewcsDD_GRID);
3135 /* With the group scheme the sorting array is part of the DD state,
3136 * but it just got out of sync, so mark as invalid by emptying it.
3138 if (ir->cutoff_scheme == ecutsGROUP)
3140 comm->sort->sorted.clear();
3144 if (comm->systemInfo.useUpdateGroups)
3146 /* The update groups cog's are invalid after sorting
3147 * and need to be cleared before the next partitioning anyhow.
3149 comm->updateGroupsCog->clear();
3152 wallcycle_sub_start(wcycle, ewcsDD_SETUPCOMM);
3154 /* Set the induces for the home atoms */
3155 set_zones_ncg_home(dd);
3156 make_dd_indices(dd, ncgindex_set);
3158 /* Setup up the communication and communicate the coordinates */
3159 setup_dd_communication(dd, state_local->box, &ddbox, fr, state_local);
3161 /* Set the indices for the halo atoms */
3162 make_dd_indices(dd, dd->ncg_home);
3164 /* Set the charge group boundaries for neighbor searching */
3165 set_cg_boundaries(&comm->zones);
3167 /* When bSortCG=true, we have already set the size for zone 0 */
3168 set_zones_size(dd, state_local->box, &ddbox, bSortCG ? 1 : 0, comm->zones.n, 0);
3170 wallcycle_sub_stop(wcycle, ewcsDD_SETUPCOMM);
3173 write_dd_pdb("dd_home",step,"dump",top_global,cr,
3174 -1,state_local->x.rvec_array(),state_local->box);
3177 wallcycle_sub_start(wcycle, ewcsDD_MAKETOP);
3179 /* Extract a local topology from the global topology */
3180 for (int i = 0; i < dd->ndim; i++)
3182 np[dd->dim[i]] = comm->cd[i].numPulses();
3184 dd_make_local_top(dd,
3186 dd->unitCellInfo.npbcdim,
3191 state_local->x.rvec_array(),
3195 wallcycle_sub_stop(wcycle, ewcsDD_MAKETOP);
3197 wallcycle_sub_start(wcycle, ewcsDD_MAKECONSTR);
3199 /* Set up the special atom communication */
3200 int n = comm->atomRanges.end(DDAtomRanges::Type::Zones);
3201 for (int i = static_cast<int>(DDAtomRanges::Type::Zones) + 1;
3202 i < static_cast<int>(DDAtomRanges::Type::Number);
3205 auto range = static_cast<DDAtomRanges::Type>(i);
3208 case DDAtomRanges::Type::Vsites:
3209 if (vsite && vsite->numInterUpdategroupVirtualSites())
3211 n = dd_make_local_vsites(dd, n, top_local->idef.il);
3214 case DDAtomRanges::Type::Constraints:
3215 if (dd->comm->systemInfo.haveSplitConstraints || dd->comm->systemInfo.haveSplitSettles)
3217 /* Only for inter-cg constraints we need special code */
3218 n = dd_make_local_constraints(dd,
3224 top_local->idef.il);
3227 default: gmx_incons("Unknown special atom type setup");
3229 comm->atomRanges.setEnd(range, n);
3232 wallcycle_sub_stop(wcycle, ewcsDD_MAKECONSTR);
3234 wallcycle_sub_start(wcycle, ewcsDD_TOPOTHER);
3236 /* Make space for the extra coordinates for virtual site
3237 * or constraint communication.
3239 state_local->natoms = comm->atomRanges.numAtomsTotal();
3241 state_change_natoms(state_local, state_local->natoms);
3243 if (vsite && vsite->numInterUpdategroupVirtualSites())
3245 nat_f_novirsum = comm->atomRanges.end(DDAtomRanges::Type::Vsites);
3249 if (EEL_FULL(ir->coulombtype) && dd->haveExclusions)
3251 nat_f_novirsum = comm->atomRanges.end(DDAtomRanges::Type::Zones);
3255 nat_f_novirsum = comm->atomRanges.numHomeAtoms();
3259 /* Set the number of atoms required for the force calculation.
3260 * Forces need to be constrained when doing energy
3261 * minimization. For simple simulations we could avoid some
3262 * allocation, zeroing and copying, but this is probably not worth
3263 * the complications and checking.
3265 forcerec_set_ranges(fr,
3266 comm->atomRanges.end(DDAtomRanges::Type::Zones),
3267 comm->atomRanges.end(DDAtomRanges::Type::Constraints),
3270 /* Update atom data for mdatoms and several algorithms */
3271 mdAlgorithmsSetupAtomData(cr, ir, top_global, top_local, fr, f, mdAtoms, constr, vsite, nullptr);
3273 auto mdatoms = mdAtoms->mdatoms();
3274 if (!thisRankHasDuty(cr, DUTY_PME))
3276 /* Send the charges and/or c6/sigmas to our PME only node */
3277 gmx_pme_send_parameters(cr,
3279 mdatoms->nChargePerturbed != 0,
3280 mdatoms->nTypePerturbed != 0,
3287 dd_pme_maxshift_x(dd),
3288 dd_pme_maxshift_y(dd));
3291 if (dd->atomSets != nullptr)
3293 /* Update the local atom sets */
3294 dd->atomSets->setIndicesInDomainDecomposition(*(dd->ga2la));
3297 // The pull group construction can need the atom sets updated above
3300 /* Update the local pull groups */
3301 dd_make_local_pull_groups(cr, pull_work);
3304 /* Update the local atoms to be communicated via the IMD protocol if bIMD is TRUE. */
3305 imdSession->dd_make_local_IMD_atoms(dd);
3307 add_dd_statistics(dd);
3309 /* Make sure we only count the cycles for this DD partitioning */
3310 clear_dd_cycle_counts(dd);
3312 /* Because the order of the atoms might have changed since
3313 * the last vsite construction, we need to communicate the constructing
3314 * atom coordinates again (for spreading the forces this MD step).
3316 dd_move_x_vsites(*dd, state_local->box, state_local->x.rvec_array());
3318 wallcycle_sub_stop(wcycle, ewcsDD_TOPOTHER);
3320 if (comm->ddSettings.nstDDDump > 0 && step % comm->ddSettings.nstDDDump == 0)
3322 dd_move_x(dd, state_local->box, state_local->x, nullWallcycle);
3323 write_dd_pdb("dd_dump",
3329 state_local->x.rvec_array(),
3333 /* Store the partitioning step */
3334 comm->partition_step = step;
3336 /* Increase the DD partitioning counter */
3338 /* The state currently matches this DD partitioning count, store it */
3339 state_local->ddp_count = dd->ddp_count;
3342 /* The DD master node knows the complete cg distribution,
3343 * store the count so we can possibly skip the cg info communication.
3345 comm->master_cg_ddp_count = (bSortCG ? 0 : dd->ddp_count);
3348 if (comm->ddSettings.DD_debug > 0)
3350 /* Set the env var GMX_DD_DEBUG if you suspect corrupted indices */
3351 check_index_consistency(dd, top_global.natoms, "after partitioning");
3354 wallcycle_stop(wcycle, ewcDOMDEC);
3357 /*! \brief Check whether bonded interactions are missing, if appropriate */
3358 void checkNumberOfBondedInteractions(const gmx::MDLogger& mdlog,
3360 int totalNumberOfBondedInteractions,
3361 const gmx_mtop_t* top_global,
3362 const gmx_localtop_t* top_local,
3363 gmx::ArrayRef<const gmx::RVec> x,
3365 bool* shouldCheckNumberOfBondedInteractions)
3367 if (*shouldCheckNumberOfBondedInteractions)
3369 if (totalNumberOfBondedInteractions != cr->dd->nbonded_global)
3371 dd_print_missing_interactions(
3372 mdlog, cr, totalNumberOfBondedInteractions, top_global, top_local, x, box); // Does not return
3374 *shouldCheckNumberOfBondedInteractions = false;