76051509ecd8d499821b82fd8ed07e7bf290a18d
[alexxy/gromacs.git] / src / gromacs / ewald / pme.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014,2015,2016,2017 The GROMACS development team.
7  * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by
8  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
9  * and including many others, as listed in the AUTHORS file in the
10  * top-level source directory and at http://www.gromacs.org.
11  *
12  * GROMACS is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public License
14  * as published by the Free Software Foundation; either version 2.1
15  * of the License, or (at your option) any later version.
16  *
17  * GROMACS is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with GROMACS; if not, see
24  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
26  *
27  * If you want to redistribute modifications to GROMACS, please
28  * consider that scientific software is very special. Version
29  * control is crucial - bugs must be traceable. We will be happy to
30  * consider code for inclusion in the official distribution, but
31  * derived work must not be called official GROMACS. Details are found
32  * in the README & COPYING files - if they are missing, get the
33  * official version at http://www.gromacs.org.
34  *
35  * To help us fund GROMACS development, we humbly ask that you cite
36  * the research papers on the package. Check out http://www.gromacs.org.
37  */
38 /*! \internal \file
39  *
40  * \brief This file contains function definitions necessary for
41  * computing energies and forces for the PME long-ranged part (Coulomb
42  * and LJ).
43  *
44  * \author Erik Lindahl <erik@kth.se>
45  * \author Berk Hess <hess@kth.se>
46  * \ingroup module_ewald
47  */
48 /* IMPORTANT FOR DEVELOPERS:
49  *
50  * Triclinic pme stuff isn't entirely trivial, and we've experienced
51  * some bugs during development (many of them due to me). To avoid
52  * this in the future, please check the following things if you make
53  * changes in this file:
54  *
55  * 1. You should obtain identical (at least to the PME precision)
56  *    energies, forces, and virial for
57  *    a rectangular box and a triclinic one where the z (or y) axis is
58  *    tilted a whole box side. For instance you could use these boxes:
59  *
60  *    rectangular       triclinic
61  *     2  0  0           2  0  0
62  *     0  2  0           0  2  0
63  *     0  0  6           2  2  6
64  *
65  * 2. You should check the energy conservation in a triclinic box.
66  *
67  * It might seem an overkill, but better safe than sorry.
68  * /Erik 001109
69  */
70
71 #include "gmxpre.h"
72
73 #include "pme.h"
74
75 #include "config.h"
76
77 #include <cassert>
78 #include <cmath>
79 #include <cstdio>
80 #include <cstdlib>
81 #include <cstring>
82
83 #include <algorithm>
84 #include <list>
85
86 #include "gromacs/domdec/domdec.h"
87 #include "gromacs/ewald/ewald_utils.h"
88 #include "gromacs/fft/parallel_3dfft.h"
89 #include "gromacs/fileio/pdbio.h"
90 #include "gromacs/gmxlib/network.h"
91 #include "gromacs/gmxlib/nrnb.h"
92 #include "gromacs/hardware/hw_info.h"
93 #include "gromacs/math/gmxcomplex.h"
94 #include "gromacs/math/invertmatrix.h"
95 #include "gromacs/math/units.h"
96 #include "gromacs/math/vec.h"
97 #include "gromacs/math/vectypes.h"
98 #include "gromacs/mdtypes/commrec.h"
99 #include "gromacs/mdtypes/forcerec.h"
100 #include "gromacs/mdtypes/inputrec.h"
101 #include "gromacs/mdtypes/md_enums.h"
102 #include "gromacs/mdtypes/simulation_workload.h"
103 #include "gromacs/pbcutil/pbc.h"
104 #include "gromacs/timing/cyclecounter.h"
105 #include "gromacs/timing/wallcycle.h"
106 #include "gromacs/timing/walltime_accounting.h"
107 #include "gromacs/topology/topology.h"
108 #include "gromacs/utility/basedefinitions.h"
109 #include "gromacs/utility/cstringutil.h"
110 #include "gromacs/utility/exceptions.h"
111 #include "gromacs/utility/fatalerror.h"
112 #include "gromacs/utility/gmxmpi.h"
113 #include "gromacs/utility/gmxomp.h"
114 #include "gromacs/utility/logger.h"
115 #include "gromacs/utility/real.h"
116 #include "gromacs/utility/smalloc.h"
117 #include "gromacs/utility/stringutil.h"
118 #include "gromacs/utility/unique_cptr.h"
119
120 #include "calculate_spline_moduli.h"
121 #include "pme_gather.h"
122 #include "pme_gpu_internal.h"
123 #include "pme_grid.h"
124 #include "pme_internal.h"
125 #include "pme_redistribute.h"
126 #include "pme_solve.h"
127 #include "pme_spline_work.h"
128 #include "pme_spread.h"
129
130 /*! \brief Help build a descriptive message in \c error if there are
131  * \c errorReasons why PME on GPU is not supported.
132  *
133  * \returns Whether the lack of errorReasons indicate there is support. */
134 static bool addMessageIfNotSupported(const std::list<std::string>& errorReasons, std::string* error)
135 {
136     bool isSupported = errorReasons.empty();
137     if (!isSupported && error)
138     {
139         std::string regressionTestMarker = "PME GPU does not support";
140         // this prefix is tested for in the regression tests script gmxtest.pl
141         *error = regressionTestMarker;
142         if (errorReasons.size() == 1)
143         {
144             *error += " " + errorReasons.back();
145         }
146         else
147         {
148             *error += ": " + gmx::joinStrings(errorReasons, "; ");
149         }
150         *error += ".";
151     }
152     return isSupported;
153 }
154
155 bool pme_gpu_supports_build(std::string* error)
156 {
157     std::list<std::string> errorReasons;
158     if (GMX_DOUBLE)
159     {
160         errorReasons.emplace_back("a double-precision build");
161     }
162     if (!GMX_GPU)
163     {
164         errorReasons.emplace_back("a non-GPU build");
165     }
166     if (GMX_GPU_SYCL)
167     {
168         errorReasons.emplace_back("SYCL build"); // SYCL-TODO
169     }
170     return addMessageIfNotSupported(errorReasons, error);
171 }
172
173 bool pme_gpu_supports_hardware(const gmx_hw_info_t gmx_unused& hwinfo, std::string* error)
174 {
175     std::list<std::string> errorReasons;
176
177     if (GMX_GPU_OPENCL)
178     {
179 #ifdef __APPLE__
180         errorReasons.emplace_back("Apple OS X operating system");
181 #endif
182     }
183     return addMessageIfNotSupported(errorReasons, error);
184 }
185
186 bool pme_gpu_supports_input(const t_inputrec& ir, std::string* error)
187 {
188     std::list<std::string> errorReasons;
189     if (!EEL_PME(ir.coulombtype))
190     {
191         errorReasons.emplace_back("systems that do not use PME for electrostatics");
192     }
193     if (ir.pme_order != 4)
194     {
195         errorReasons.emplace_back("interpolation orders other than 4");
196     }
197     if (EVDW_PME(ir.vdwtype))
198     {
199         errorReasons.emplace_back("Lennard-Jones PME");
200     }
201     if (!EI_DYNAMICS(ir.eI))
202     {
203         errorReasons.emplace_back(
204                 "Cannot compute PME interactions on a GPU, because PME GPU requires a dynamical "
205                 "integrator (md, sd, etc).");
206     }
207     return addMessageIfNotSupported(errorReasons, error);
208 }
209
210 /*! \brief \libinternal
211  * Finds out if PME with given inputs is possible to run on GPU.
212  * This function is an internal final check, validating the whole PME structure on creation,
213  * but it still duplicates the preliminary checks from the above (externally exposed) pme_gpu_supports_input() - just in case.
214  *
215  * \param[in]  pme          The PME structure.
216  * \param[out] error        The error message if the input is not supported on GPU.
217  * \returns                 True if this PME input is possible to run on GPU, false otherwise.
218  */
219 static bool pme_gpu_check_restrictions(const gmx_pme_t* pme, std::string* error)
220 {
221     std::list<std::string> errorReasons;
222     if (pme->nnodes != 1)
223     {
224         errorReasons.emplace_back("PME decomposition");
225     }
226     if (pme->pme_order != 4)
227     {
228         errorReasons.emplace_back("interpolation orders other than 4");
229     }
230     if (pme->doLJ)
231     {
232         errorReasons.emplace_back("Lennard-Jones PME");
233     }
234     if (GMX_DOUBLE)
235     {
236         errorReasons.emplace_back("double precision");
237     }
238     if (!GMX_GPU)
239     {
240         errorReasons.emplace_back("non-GPU build of GROMACS");
241     }
242     if (GMX_GPU_SYCL)
243     {
244         errorReasons.emplace_back("SYCL build of GROMACS"); // SYCL-TODO
245     }
246     return addMessageIfNotSupported(errorReasons, error);
247 }
248
249 PmeRunMode pme_run_mode(const gmx_pme_t* pme)
250 {
251     GMX_ASSERT(pme != nullptr, "Expecting valid PME data pointer");
252     return pme->runMode;
253 }
254
255 gmx::PinningPolicy pme_get_pinning_policy()
256 {
257     return gmx::PinningPolicy::PinnedIfSupported;
258 }
259
260 /*! \brief Number of bytes in a cache line.
261  *
262  * Must also be a multiple of the SIMD and SIMD4 register size, to
263  * preserve alignment.
264  */
265 const int gmxCacheLineSize = 64;
266
267 //! Set up coordinate communication
268 static void setup_coordinate_communication(PmeAtomComm* atc)
269 {
270     int nslab, n, i;
271     int fw, bw;
272
273     nslab = atc->nslab;
274
275     n = 0;
276     for (i = 1; i <= nslab / 2; i++)
277     {
278         fw = (atc->nodeid + i) % nslab;
279         bw = (atc->nodeid - i + nslab) % nslab;
280         if (n < nslab - 1)
281         {
282             atc->slabCommSetup[n].node_dest = fw;
283             atc->slabCommSetup[n].node_src  = bw;
284             n++;
285         }
286         if (n < nslab - 1)
287         {
288             atc->slabCommSetup[n].node_dest = bw;
289             atc->slabCommSetup[n].node_src  = fw;
290             n++;
291         }
292     }
293 }
294
295 /*! \brief Round \p n up to the next multiple of \p f */
296 static int mult_up(int n, int f)
297 {
298     return ((n + f - 1) / f) * f;
299 }
300
301 /*! \brief Return estimate of the load imbalance from the PME grid not being a good match for the number of PME ranks */
302 static double estimate_pme_load_imbalance(struct gmx_pme_t* pme)
303 {
304     int    nma, nmi;
305     double n1, n2, n3;
306
307     nma = pme->nnodes_major;
308     nmi = pme->nnodes_minor;
309
310     n1 = mult_up(pme->nkx, nma) * mult_up(pme->nky, nmi) * pme->nkz;
311     n2 = mult_up(pme->nkx, nma) * mult_up(pme->nkz, nmi) * pme->nky;
312     n3 = mult_up(pme->nky, nma) * mult_up(pme->nkz, nmi) * pme->nkx;
313
314     /* pme_solve is roughly double the cost of an fft */
315
316     return (n1 + n2 + 3 * n3) / static_cast<double>(6 * pme->nkx * pme->nky * pme->nkz);
317 }
318
319 #ifndef DOXYGEN
320
321 PmeAtomComm::PmeAtomComm(MPI_Comm   PmeMpiCommunicator,
322                          const int  numThreads,
323                          const int  pmeOrder,
324                          const int  dimIndex,
325                          const bool doSpread) :
326     dimind(dimIndex),
327     bSpread(doSpread),
328     pme_order(pmeOrder),
329     nthread(numThreads),
330     spline(nthread)
331 {
332     if (PmeMpiCommunicator != MPI_COMM_NULL)
333     {
334         mpi_comm = PmeMpiCommunicator;
335 #    if GMX_MPI
336         MPI_Comm_size(mpi_comm, &nslab);
337         MPI_Comm_rank(mpi_comm, &nodeid);
338 #    endif
339     }
340     if (debug)
341     {
342         fprintf(debug, "For PME atom communication in dimind %d: nslab %d rank %d\n", dimind, nslab, nodeid);
343     }
344
345     if (nslab > 1)
346     {
347         slabCommSetup.resize(nslab);
348         setup_coordinate_communication(this);
349
350         count_thread.resize(nthread);
351         for (auto& countThread : count_thread)
352         {
353             countThread.resize(nslab);
354         }
355     }
356
357     if (nthread > 1)
358     {
359         threadMap.resize(nthread);
360
361 #    pragma omp parallel for num_threads(nthread) schedule(static)
362         for (int thread = 0; thread < nthread; thread++)
363         {
364             try
365             {
366                 /* Allocate buffer with padding to avoid cache polution */
367                 threadMap[thread].nBuffer.resize(nthread + 2 * gmxCacheLineSize);
368                 threadMap[thread].n = threadMap[thread].nBuffer.data() + gmxCacheLineSize;
369             }
370             GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
371         }
372     }
373 }
374
375 #endif // !DOXYGEN
376
377 /*! \brief Initialize data structure for communication */
378 static void init_overlap_comm(pme_overlap_t* ol, int norder, MPI_Comm comm, int nnodes, int nodeid, int ndata, int commplainsize)
379 {
380     gmx_bool bCont;
381
382     ol->mpi_comm = comm;
383     ol->nnodes   = nnodes;
384     ol->nodeid   = nodeid;
385
386     /* Linear translation of the PME grid won't affect reciprocal space
387      * calculations, so to optimize we only interpolate "upwards",
388      * which also means we only have to consider overlap in one direction.
389      * I.e., particles on this node might also be spread to grid indices
390      * that belong to higher nodes (modulo nnodes)
391      */
392
393     ol->s2g0.resize(ol->nnodes + 1);
394     ol->s2g1.resize(ol->nnodes);
395     if (debug)
396     {
397         fprintf(debug, "PME slab boundaries:");
398     }
399     for (int i = 0; i < nnodes; i++)
400     {
401         /* s2g0 the local interpolation grid start.
402          * s2g1 the local interpolation grid end.
403          * Since in calc_pidx we divide particles, and not grid lines,
404          * spatially uniform along dimension x or y, we need to round
405          * s2g0 down and s2g1 up.
406          */
407         ol->s2g0[i] = (i * ndata + 0) / nnodes;
408         ol->s2g1[i] = ((i + 1) * ndata + nnodes - 1) / nnodes + norder - 1;
409
410         if (debug)
411         {
412             fprintf(debug, "  %3d %3d", ol->s2g0[i], ol->s2g1[i]);
413         }
414     }
415     ol->s2g0[nnodes] = ndata;
416     if (debug)
417     {
418         fprintf(debug, "\n");
419     }
420
421     /* Determine with how many nodes we need to communicate the grid overlap */
422     int testRankCount = 0;
423     do
424     {
425         testRankCount++;
426         bCont = FALSE;
427         for (int i = 0; i < nnodes; i++)
428         {
429             if ((i + testRankCount < nnodes && ol->s2g1[i] > ol->s2g0[i + testRankCount])
430                 || (i + testRankCount >= nnodes && ol->s2g1[i] > ol->s2g0[i + testRankCount - nnodes] + ndata))
431             {
432                 bCont = TRUE;
433             }
434         }
435     } while (bCont && testRankCount < nnodes);
436
437     ol->comm_data.resize(testRankCount - 1);
438     ol->send_size = 0;
439
440     for (size_t b = 0; b < ol->comm_data.size(); b++)
441     {
442         pme_grid_comm_t* pgc = &ol->comm_data[b];
443
444         /* Send */
445         pgc->send_id  = (ol->nodeid + (b + 1)) % ol->nnodes;
446         int fft_start = ol->s2g0[pgc->send_id];
447         int fft_end   = ol->s2g0[pgc->send_id + 1];
448         if (pgc->send_id < nodeid)
449         {
450             fft_start += ndata;
451             fft_end += ndata;
452         }
453         int send_index1  = ol->s2g1[nodeid];
454         send_index1      = std::min(send_index1, fft_end);
455         pgc->send_index0 = fft_start;
456         pgc->send_nindex = std::max(0, send_index1 - pgc->send_index0);
457         ol->send_size += pgc->send_nindex;
458
459         /* We always start receiving to the first index of our slab */
460         pgc->recv_id    = (ol->nodeid - (b + 1) + ol->nnodes) % ol->nnodes;
461         fft_start       = ol->s2g0[ol->nodeid];
462         fft_end         = ol->s2g0[ol->nodeid + 1];
463         int recv_index1 = ol->s2g1[pgc->recv_id];
464         if (pgc->recv_id > nodeid)
465         {
466             recv_index1 -= ndata;
467         }
468         recv_index1      = std::min(recv_index1, fft_end);
469         pgc->recv_index0 = fft_start;
470         pgc->recv_nindex = std::max(0, recv_index1 - pgc->recv_index0);
471     }
472
473 #if GMX_MPI
474     /* Communicate the buffer sizes to receive */
475     MPI_Status stat;
476     for (size_t b = 0; b < ol->comm_data.size(); b++)
477     {
478         MPI_Sendrecv(&ol->send_size, 1, MPI_INT, ol->comm_data[b].send_id, b, &ol->comm_data[b].recv_size,
479                      1, MPI_INT, ol->comm_data[b].recv_id, b, ol->mpi_comm, &stat);
480     }
481 #endif
482
483     /* For non-divisible grid we need pme_order iso pme_order-1 */
484     ol->sendbuf.resize(norder * commplainsize);
485     ol->recvbuf.resize(norder * commplainsize);
486 }
487
488 int minimalPmeGridSize(int pmeOrder)
489 {
490     /* The actual grid size limitations are:
491      *   serial:        >= pme_order
492      *   DD, no OpenMP: >= 2*(pme_order - 1)
493      *   DD, OpenMP:    >= pme_order + 1
494      * But we use the maximum for simplicity since in practice there is not
495      * much performance difference between pme_order and 2*(pme_order -1).
496      */
497     int minimalSize = 2 * (pmeOrder - 1);
498
499     GMX_RELEASE_ASSERT(pmeOrder >= 3, "pmeOrder has to be >= 3");
500     GMX_RELEASE_ASSERT(minimalSize >= pmeOrder + 1, "The grid size should be >= pmeOrder + 1");
501
502     return minimalSize;
503 }
504
505 bool gmx_pme_check_restrictions(int pme_order, int nkx, int nky, int nkz, int numPmeDomainsAlongX, bool useThreads, bool errorsAreFatal)
506 {
507     if (pme_order > PME_ORDER_MAX)
508     {
509         if (!errorsAreFatal)
510         {
511             return false;
512         }
513
514         std::string message = gmx::formatString(
515                 "pme_order (%d) is larger than the maximum allowed value (%d). Modify and "
516                 "recompile the code if you really need such a high order.",
517                 pme_order, PME_ORDER_MAX);
518         GMX_THROW(gmx::InconsistentInputError(message));
519     }
520
521     const int minGridSize = minimalPmeGridSize(pme_order);
522     if (nkx < minGridSize || nky < minGridSize || nkz < minGridSize)
523     {
524         if (!errorsAreFatal)
525         {
526             return false;
527         }
528         std::string message =
529                 gmx::formatString("The PME grid sizes need to be >= 2*(pme_order-1) (%d)", minGridSize);
530         GMX_THROW(gmx::InconsistentInputError(message));
531     }
532
533     /* Check for a limitation of the (current) sum_fftgrid_dd code.
534      * We only allow multiple communication pulses in dim 1, not in dim 0.
535      */
536     if (useThreads
537         && (nkx < numPmeDomainsAlongX * pme_order && nkx != numPmeDomainsAlongX * (pme_order - 1)))
538     {
539         if (!errorsAreFatal)
540         {
541             return false;
542         }
543         gmx_fatal(FARGS,
544                   "The number of PME grid lines per rank along x is %g. But when using OpenMP "
545                   "threads, the number of grid lines per rank along x should be >= pme_order (%d) "
546                   "or = pmeorder-1. To resolve this issue, use fewer ranks along x (and possibly "
547                   "more along y and/or z) by specifying -dd manually.",
548                   nkx / static_cast<double>(numPmeDomainsAlongX), pme_order);
549     }
550
551     return true;
552 }
553
554 /*! \brief Round \p enumerator */
555 static int div_round_up(int enumerator, int denominator)
556 {
557     return (enumerator + denominator - 1) / denominator;
558 }
559
560 gmx_pme_t* gmx_pme_init(const t_commrec*     cr,
561                         const NumPmeDomains& numPmeDomains,
562                         const t_inputrec*    ir,
563                         gmx_bool             bFreeEnergy_q,
564                         gmx_bool             bFreeEnergy_lj,
565                         gmx_bool             bReproducible,
566                         real                 ewaldcoeff_q,
567                         real                 ewaldcoeff_lj,
568                         int                  nthread,
569                         PmeRunMode           runMode,
570                         PmeGpu*              pmeGpu,
571                         const DeviceContext* deviceContext,
572                         const DeviceStream*  deviceStream,
573                         const PmeGpuProgram* pmeGpuProgram,
574                         const gmx::MDLogger& mdlog)
575 {
576     int  use_threads, sum_use_threads, i;
577     ivec ndata;
578
579     if (debug)
580     {
581         fprintf(debug, "Creating PME data structures.\n");
582     }
583
584     gmx::unique_cptr<gmx_pme_t, gmx_pme_destroy> pme(new gmx_pme_t());
585
586     pme->sum_qgrid_tmp    = nullptr;
587     pme->sum_qgrid_dd_tmp = nullptr;
588
589     pme->buf_nalloc = 0;
590
591     pme->nnodes  = 1;
592     pme->bPPnode = TRUE;
593
594     pme->nnodes_major = numPmeDomains.x;
595     pme->nnodes_minor = numPmeDomains.y;
596
597     if (numPmeDomains.x * numPmeDomains.y > 1)
598     {
599         pme->mpi_comm = cr->mpi_comm_mygroup;
600
601 #if GMX_MPI
602         MPI_Comm_rank(pme->mpi_comm, &pme->nodeid);
603         MPI_Comm_size(pme->mpi_comm, &pme->nnodes);
604 #endif
605         if (pme->nnodes != numPmeDomains.x * numPmeDomains.y)
606         {
607             gmx_incons("PME rank count mismatch");
608         }
609     }
610     else
611     {
612         pme->mpi_comm = MPI_COMM_NULL;
613     }
614
615     if (pme->nnodes == 1)
616     {
617         pme->mpi_comm_d[0] = MPI_COMM_NULL;
618         pme->mpi_comm_d[1] = MPI_COMM_NULL;
619         pme->ndecompdim    = 0;
620         pme->nodeid_major  = 0;
621         pme->nodeid_minor  = 0;
622     }
623     else
624     {
625         if (numPmeDomains.y == 1)
626         {
627             pme->mpi_comm_d[0] = pme->mpi_comm;
628             pme->mpi_comm_d[1] = MPI_COMM_NULL;
629             pme->ndecompdim    = 1;
630             pme->nodeid_major  = pme->nodeid;
631             pme->nodeid_minor  = 0;
632         }
633         else if (numPmeDomains.x == 1)
634         {
635             pme->mpi_comm_d[0] = MPI_COMM_NULL;
636             pme->mpi_comm_d[1] = pme->mpi_comm;
637             pme->ndecompdim    = 1;
638             pme->nodeid_major  = 0;
639             pme->nodeid_minor  = pme->nodeid;
640         }
641         else
642         {
643             if (pme->nnodes % numPmeDomains.x != 0)
644             {
645                 gmx_incons(
646                         "For 2D PME decomposition, #PME ranks must be divisible by the number of "
647                         "domains along x");
648             }
649             pme->ndecompdim = 2;
650
651 #if GMX_MPI
652             MPI_Comm_split(pme->mpi_comm, pme->nodeid % numPmeDomains.y, pme->nodeid,
653                            &pme->mpi_comm_d[0]); /* My communicator along major dimension */
654             MPI_Comm_split(pme->mpi_comm, pme->nodeid / numPmeDomains.y, pme->nodeid,
655                            &pme->mpi_comm_d[1]); /* My communicator along minor dimension */
656
657             MPI_Comm_rank(pme->mpi_comm_d[0], &pme->nodeid_major);
658             MPI_Comm_size(pme->mpi_comm_d[0], &pme->nnodes_major);
659             MPI_Comm_rank(pme->mpi_comm_d[1], &pme->nodeid_minor);
660             MPI_Comm_size(pme->mpi_comm_d[1], &pme->nnodes_minor);
661 #endif
662         }
663     }
664     // cr is always initialized if there is a a PP rank, so we can safely assume
665     // that when it is not, like in ewald tests, we not on a PP rank.
666     pme->bPPnode = ((cr != nullptr && cr->duty != 0) && thisRankHasDuty(cr, DUTY_PP));
667
668     pme->nthread = nthread;
669
670     /* Check if any of the PME MPI ranks uses threads */
671     use_threads = (pme->nthread > 1 ? 1 : 0);
672 #if GMX_MPI
673     if (pme->nnodes > 1)
674     {
675         MPI_Allreduce(&use_threads, &sum_use_threads, 1, MPI_INT, MPI_SUM, pme->mpi_comm);
676     }
677     else
678 #endif
679     {
680         sum_use_threads = use_threads;
681     }
682     pme->bUseThreads = (sum_use_threads > 0);
683
684     if (ir->pbcType == PbcType::Screw)
685     {
686         gmx_fatal(FARGS, "pme does not (yet) work with pbc = screw");
687     }
688
689     /* NOTE:
690      * It is likely that the current gmx_pme_do() routine supports calculating
691      * only Coulomb or LJ while gmx_pme_init() configures for both,
692      * but that has never been tested.
693      * It is likely that the current gmx_pme_do() routine supports calculating,
694      * not calculating free-energy for Coulomb and/or LJ while gmx_pme_init()
695      * configures with free-energy, but that has never been tested.
696      */
697     pme->doCoulomb     = EEL_PME(ir->coulombtype);
698     pme->doLJ          = EVDW_PME(ir->vdwtype);
699     pme->bFEP_q        = ((ir->efep != efepNO) && bFreeEnergy_q);
700     pme->bFEP_lj       = ((ir->efep != efepNO) && bFreeEnergy_lj);
701     pme->bFEP          = (pme->bFEP_q || pme->bFEP_lj);
702     pme->nkx           = ir->nkx;
703     pme->nky           = ir->nky;
704     pme->nkz           = ir->nkz;
705     pme->bP3M          = (ir->coulombtype == eelP3M_AD || getenv("GMX_PME_P3M") != nullptr);
706     pme->pme_order     = ir->pme_order;
707     pme->ewaldcoeff_q  = ewaldcoeff_q;
708     pme->ewaldcoeff_lj = ewaldcoeff_lj;
709
710     /* Always constant electrostatics coefficients */
711     pme->epsilon_r = ir->epsilon_r;
712
713     /* Always constant LJ coefficients */
714     pme->ljpme_combination_rule = ir->ljpme_combination_rule;
715
716     // The box requires scaling with nwalls = 2, we store that condition as well
717     // as the scaling factor
718     delete pme->boxScaler;
719     pme->boxScaler = new EwaldBoxZScaler(*ir);
720
721     /* If we violate restrictions, generate a fatal error here */
722     gmx_pme_check_restrictions(pme->pme_order, pme->nkx, pme->nky, pme->nkz, pme->nnodes_major,
723                                pme->bUseThreads, true);
724
725     if (pme->nnodes > 1)
726     {
727         double imbal;
728
729 #if GMX_MPI
730         MPI_Type_contiguous(DIM, GMX_MPI_REAL, &(pme->rvec_mpi));
731         MPI_Type_commit(&(pme->rvec_mpi));
732 #endif
733
734         /* Note that the coefficient spreading and force gathering, which usually
735          * takes about the same amount of time as FFT+solve_pme,
736          * is always fully load balanced
737          * (unless the coefficient distribution is inhomogeneous).
738          */
739
740         imbal = estimate_pme_load_imbalance(pme.get());
741         if (imbal >= 1.2 && pme->nodeid_major == 0 && pme->nodeid_minor == 0)
742         {
743             GMX_LOG(mdlog.warning)
744                     .asParagraph()
745                     .appendTextFormatted(
746                             "NOTE: The load imbalance in PME FFT and solve is %d%%.\n"
747                             "      For optimal PME load balancing\n"
748                             "      PME grid_x (%d) and grid_y (%d) should be divisible by "
749                             "#PME_ranks_x "
750                             "(%d)\n"
751                             "      and PME grid_y (%d) and grid_z (%d) should be divisible by "
752                             "#PME_ranks_y "
753                             "(%d)",
754                             gmx::roundToInt((imbal - 1) * 100), pme->nkx, pme->nky,
755                             pme->nnodes_major, pme->nky, pme->nkz, pme->nnodes_minor);
756         }
757     }
758
759     /* For non-divisible grid we need pme_order iso pme_order-1 */
760     /* In sum_qgrid_dd x overlap is copied in place: take padding into account.
761      * y is always copied through a buffer: we don't need padding in z,
762      * but we do need the overlap in x because of the communication order.
763      */
764     init_overlap_comm(&pme->overlap[0], pme->pme_order, pme->mpi_comm_d[0], pme->nnodes_major,
765                       pme->nodeid_major, pme->nkx,
766                       (div_round_up(pme->nky, pme->nnodes_minor) + pme->pme_order)
767                               * (pme->nkz + pme->pme_order - 1));
768
769     /* Along overlap dim 1 we can send in multiple pulses in sum_fftgrid_dd.
770      * We do this with an offset buffer of equal size, so we need to allocate
771      * extra for the offset. That's what the (+1)*pme->nkz is for.
772      */
773     init_overlap_comm(&pme->overlap[1], pme->pme_order, pme->mpi_comm_d[1], pme->nnodes_minor,
774                       pme->nodeid_minor, pme->nky,
775                       (div_round_up(pme->nkx, pme->nnodes_major) + pme->pme_order + 1) * pme->nkz);
776
777     /* Double-check for a limitation of the (current) sum_fftgrid_dd code.
778      * Note that gmx_pme_check_restrictions checked for this already.
779      */
780     if (pme->bUseThreads && (pme->overlap[0].comm_data.size() > 1))
781     {
782         gmx_incons(
783                 "More than one communication pulse required for grid overlap communication along "
784                 "the major dimension while using threads");
785     }
786
787     snew(pme->bsp_mod[XX], pme->nkx);
788     snew(pme->bsp_mod[YY], pme->nky);
789     snew(pme->bsp_mod[ZZ], pme->nkz);
790
791     pme->gpu     = pmeGpu; /* Carrying over the single GPU structure */
792     pme->runMode = runMode;
793
794     /* The required size of the interpolation grid, including overlap.
795      * The allocated size (pmegrid_n?) might be slightly larger.
796      */
797     pme->pmegrid_nx = pme->overlap[0].s2g1[pme->nodeid_major] - pme->overlap[0].s2g0[pme->nodeid_major];
798     pme->pmegrid_ny = pme->overlap[1].s2g1[pme->nodeid_minor] - pme->overlap[1].s2g0[pme->nodeid_minor];
799     pme->pmegrid_nz_base = pme->nkz;
800     pme->pmegrid_nz      = pme->pmegrid_nz_base + pme->pme_order - 1;
801     set_grid_alignment(&pme->pmegrid_nz, pme->pme_order);
802     pme->pmegrid_start_ix = pme->overlap[0].s2g0[pme->nodeid_major];
803     pme->pmegrid_start_iy = pme->overlap[1].s2g0[pme->nodeid_minor];
804     pme->pmegrid_start_iz = 0;
805
806     make_gridindex_to_localindex(pme->nkx, pme->pmegrid_start_ix,
807                                  pme->pmegrid_nx - (pme->pme_order - 1), &pme->nnx, &pme->fshx);
808     make_gridindex_to_localindex(pme->nky, pme->pmegrid_start_iy,
809                                  pme->pmegrid_ny - (pme->pme_order - 1), &pme->nny, &pme->fshy);
810     make_gridindex_to_localindex(pme->nkz, pme->pmegrid_start_iz, pme->pmegrid_nz_base, &pme->nnz,
811                                  &pme->fshz);
812
813     pme->spline_work = make_pme_spline_work(pme->pme_order);
814
815     ndata[0] = pme->nkx;
816     ndata[1] = pme->nky;
817     ndata[2] = pme->nkz;
818     /* It doesn't matter if we allocate too many grids here,
819      * we only allocate and use the ones we need.
820      */
821     if (pme->doLJ)
822     {
823         pme->ngrids = ((ir->ljpme_combination_rule == eljpmeLB) ? DO_Q_AND_LJ_LB : DO_Q_AND_LJ);
824     }
825     else
826     {
827         pme->ngrids = DO_Q;
828     }
829     snew(pme->fftgrid, pme->ngrids);
830     snew(pme->cfftgrid, pme->ngrids);
831     snew(pme->pfft_setup, pme->ngrids);
832
833     for (i = 0; i < pme->ngrids; ++i)
834     {
835         if ((i < DO_Q && pme->doCoulomb && (i == 0 || bFreeEnergy_q))
836             || (i >= DO_Q && pme->doLJ
837                 && (i == 2 || bFreeEnergy_lj || ir->ljpme_combination_rule == eljpmeLB)))
838         {
839             pmegrids_init(&pme->pmegrid[i], pme->pmegrid_nx, pme->pmegrid_ny, pme->pmegrid_nz,
840                           pme->pmegrid_nz_base, pme->pme_order, pme->bUseThreads, pme->nthread,
841                           pme->overlap[0].s2g1[pme->nodeid_major]
842                                   - pme->overlap[0].s2g0[pme->nodeid_major + 1],
843                           pme->overlap[1].s2g1[pme->nodeid_minor]
844                                   - pme->overlap[1].s2g0[pme->nodeid_minor + 1]);
845             /* This routine will allocate the grid data to fit the FFTs */
846             const auto allocateRealGridForGpu = (pme->runMode == PmeRunMode::Mixed)
847                                                         ? gmx::PinningPolicy::PinnedIfSupported
848                                                         : gmx::PinningPolicy::CannotBePinned;
849             gmx_parallel_3dfft_init(&pme->pfft_setup[i], ndata, &pme->fftgrid[i], &pme->cfftgrid[i],
850                                     pme->mpi_comm_d, bReproducible, pme->nthread, allocateRealGridForGpu);
851         }
852     }
853
854     if (!pme->bP3M)
855     {
856         /* Use plain SPME B-spline interpolation */
857         make_bspline_moduli(pme->bsp_mod, pme->nkx, pme->nky, pme->nkz, pme->pme_order);
858     }
859     else
860     {
861         /* Use the P3M grid-optimized influence function */
862         make_p3m_bspline_moduli(pme->bsp_mod, pme->nkx, pme->nky, pme->nkz, pme->pme_order);
863     }
864
865     /* Use atc[0] for spreading */
866     const int firstDimIndex   = (numPmeDomains.x > 1 ? 0 : 1);
867     MPI_Comm  mpiCommFirstDim = (pme->nnodes > 1 ? pme->mpi_comm_d[firstDimIndex] : MPI_COMM_NULL);
868     bool      doSpread        = true;
869     pme->atc.emplace_back(mpiCommFirstDim, pme->nthread, pme->pme_order, firstDimIndex, doSpread);
870     if (pme->ndecompdim >= 2)
871     {
872         const int secondDimIndex = 1;
873         doSpread                 = false;
874         pme->atc.emplace_back(pme->mpi_comm_d[1], pme->nthread, pme->pme_order, secondDimIndex, doSpread);
875     }
876
877     // Initial check of validity of the input for running on the GPU
878     if (pme->runMode != PmeRunMode::CPU)
879     {
880         std::string errorString;
881         bool        canRunOnGpu = pme_gpu_check_restrictions(pme.get(), &errorString);
882         if (!canRunOnGpu)
883         {
884             GMX_THROW(gmx::NotImplementedError(errorString));
885         }
886         pme_gpu_reinit(pme.get(), deviceContext, deviceStream, pmeGpuProgram);
887     }
888     else
889     {
890         GMX_ASSERT(pme->gpu == nullptr, "Should not have PME GPU object when PME is on a CPU.");
891     }
892
893
894     pme_init_all_work(&pme->solve_work, pme->nthread, pme->nkx);
895
896     // no exception was thrown during the init, so we hand over the PME structure handle
897     return pme.release();
898 }
899
900 void gmx_pme_reinit(struct gmx_pme_t** pmedata,
901                     const t_commrec*   cr,
902                     struct gmx_pme_t*  pme_src,
903                     const t_inputrec*  ir,
904                     const ivec         grid_size,
905                     real               ewaldcoeff_q,
906                     real               ewaldcoeff_lj)
907 {
908     // Create a copy of t_inputrec fields that are used in gmx_pme_init().
909     // TODO: This would be better as just copying a sub-structure that contains
910     // all the PME parameters and nothing else.
911     t_inputrec irc;
912     irc.pbcType                = ir->pbcType;
913     irc.coulombtype            = ir->coulombtype;
914     irc.vdwtype                = ir->vdwtype;
915     irc.efep                   = ir->efep;
916     irc.pme_order              = ir->pme_order;
917     irc.epsilon_r              = ir->epsilon_r;
918     irc.ljpme_combination_rule = ir->ljpme_combination_rule;
919     irc.nkx                    = grid_size[XX];
920     irc.nky                    = grid_size[YY];
921     irc.nkz                    = grid_size[ZZ];
922
923     try
924     {
925         // This is reinit. Any logging should have been done at first init.
926         // Here we should avoid writing notes for settings the user did not
927         // set directly.
928         const gmx::MDLogger dummyLogger;
929         GMX_ASSERT(pmedata, "Invalid PME pointer");
930         NumPmeDomains numPmeDomains = { pme_src->nnodes_major, pme_src->nnodes_minor };
931         *pmedata = gmx_pme_init(cr, numPmeDomains, &irc, pme_src->bFEP_q, pme_src->bFEP_lj, FALSE,
932                                 ewaldcoeff_q, ewaldcoeff_lj, pme_src->nthread, pme_src->runMode,
933                                 pme_src->gpu, nullptr, nullptr, nullptr, dummyLogger);
934         /* When running PME on the CPU not using domain decomposition,
935          * the atom data is allocated once only in gmx_pme_(re)init().
936          */
937         if (!pme_src->gpu && pme_src->nnodes == 1)
938         {
939             gmx_pme_reinit_atoms(*pmedata, pme_src->atc[0].numAtoms(), nullptr, nullptr);
940         }
941         // TODO this is mostly passing around current values
942     }
943     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
944
945     /* We can easily reuse the allocated pme grids in pme_src */
946     reuse_pmegrids(&pme_src->pmegrid[PME_GRID_QA], &(*pmedata)->pmegrid[PME_GRID_QA]);
947     /* We would like to reuse the fft grids, but that's harder */
948 }
949
950 void gmx_pme_calc_energy(gmx_pme_t* pme, gmx::ArrayRef<const gmx::RVec> x, gmx::ArrayRef<const real> q, real* V)
951 {
952     pmegrids_t* grid;
953
954     if (pme->nnodes > 1)
955     {
956         gmx_incons("gmx_pme_calc_energy called in parallel");
957     }
958     if (pme->bFEP_q)
959     {
960         gmx_incons("gmx_pme_calc_energy with free energy");
961     }
962
963     if (!pme->atc_energy)
964     {
965         pme->atc_energy = std::make_unique<PmeAtomComm>(MPI_COMM_NULL, 1, pme->pme_order, 0, true);
966     }
967     PmeAtomComm* atc = pme->atc_energy.get();
968     atc->setNumAtoms(x.ssize());
969     atc->x           = x;
970     atc->coefficient = q;
971
972     /* We only use the A-charges grid */
973     grid = &pme->pmegrid[PME_GRID_QA];
974
975     /* Only calculate the spline coefficients, don't actually spread */
976     spread_on_grid(pme, atc, nullptr, TRUE, FALSE, pme->fftgrid[PME_GRID_QA], FALSE, PME_GRID_QA);
977
978     *V = gather_energy_bsplines(pme, grid->grid.grid, atc);
979 }
980
981 /*! \brief Calculate initial Lorentz-Berthelot coefficients for LJ-PME */
982 static void calc_initial_lb_coeffs(gmx::ArrayRef<real> coefficient, const real* local_c6, const real* local_sigma)
983 {
984     for (gmx::index i = 0; i < coefficient.ssize(); ++i)
985     {
986         real sigma4    = local_sigma[i];
987         sigma4         = sigma4 * sigma4;
988         sigma4         = sigma4 * sigma4;
989         coefficient[i] = local_c6[i] / sigma4;
990     }
991 }
992
993 /*! \brief Calculate next Lorentz-Berthelot coefficients for LJ-PME */
994 static void calc_next_lb_coeffs(gmx::ArrayRef<real> coefficient, const real* local_sigma)
995 {
996     for (gmx::index i = 0; i < coefficient.ssize(); ++i)
997     {
998         coefficient[i] *= local_sigma[i];
999     }
1000 }
1001
1002 int gmx_pme_do(struct gmx_pme_t*              pme,
1003                gmx::ArrayRef<const gmx::RVec> coordinates,
1004                gmx::ArrayRef<gmx::RVec>       forces,
1005                real                           chargeA[],
1006                real                           chargeB[],
1007                real                           c6A[],
1008                real                           c6B[],
1009                real                           sigmaA[],
1010                real                           sigmaB[],
1011                const matrix                   box,
1012                const t_commrec*               cr,
1013                int                            maxshift_x,
1014                int                            maxshift_y,
1015                t_nrnb*                        nrnb,
1016                gmx_wallcycle*                 wcycle,
1017                matrix                         vir_q,
1018                matrix                         vir_lj,
1019                real*                          energy_q,
1020                real*                          energy_lj,
1021                real                           lambda_q,
1022                real                           lambda_lj,
1023                real*                          dvdlambda_q,
1024                real*                          dvdlambda_lj,
1025                const gmx::StepWorkload&       stepWork)
1026 {
1027     GMX_ASSERT(pme->runMode == PmeRunMode::CPU,
1028                "gmx_pme_do should not be called on the GPU PME run.");
1029
1030     int                  d, npme, grid_index, max_grid_index;
1031     PmeAtomComm&         atc         = pme->atc[0];
1032     pmegrids_t*          pmegrid     = nullptr;
1033     real*                grid        = nullptr;
1034     real*                coefficient = nullptr;
1035     PmeOutput            output[2]; // The second is used for the B state with FEP
1036     real                 scale, lambda;
1037     gmx_bool             bClearF;
1038     gmx_parallel_3dfft_t pfft_setup;
1039     real*                fftgrid;
1040     t_complex*           cfftgrid;
1041     int                  thread;
1042     gmx_bool             bFirst, bDoSplines;
1043     int                  fep_state;
1044     int                  fep_states_lj = pme->bFEP_lj ? 2 : 1;
1045     // There's no support for computing energy without virial, or vice versa
1046     const bool computeEnergyAndVirial = (stepWork.computeEnergy || stepWork.computeVirial);
1047
1048     /* We could be passing lambda!=0 while no q or LJ is actually perturbed */
1049     if (!pme->bFEP_q)
1050     {
1051         lambda_q = 0;
1052     }
1053     if (!pme->bFEP_lj)
1054     {
1055         lambda_lj = 0;
1056     }
1057
1058     assert(pme->nnodes > 0);
1059     assert(pme->nnodes == 1 || pme->ndecompdim > 0);
1060
1061     if (pme->nnodes > 1)
1062     {
1063         atc.pd.resize(coordinates.ssize());
1064         for (int d = pme->ndecompdim - 1; d >= 0; d--)
1065         {
1066             PmeAtomComm& atc = pme->atc[d];
1067             atc.maxshift     = (atc.dimind == 0 ? maxshift_x : maxshift_y);
1068         }
1069     }
1070     else
1071     {
1072         GMX_ASSERT(coordinates.ssize() == atc.numAtoms(), "We expect atc.numAtoms() coordinates");
1073         GMX_ASSERT(forces.ssize() >= atc.numAtoms(),
1074                    "We need a force buffer with at least atc.numAtoms() elements");
1075
1076         atc.x = coordinates;
1077         atc.f = forces;
1078     }
1079
1080     matrix scaledBox;
1081     pme->boxScaler->scaleBox(box, scaledBox);
1082
1083     gmx::invertBoxMatrix(scaledBox, pme->recipbox);
1084     bFirst = TRUE;
1085
1086     /* For simplicity, we construct the splines for all particles if
1087      * more than one PME calculations is needed. Some optimization
1088      * could be done by keeping track of which atoms have splines
1089      * constructed, and construct new splines on each pass for atoms
1090      * that don't yet have them.
1091      */
1092
1093     bDoSplines = pme->bFEP || (pme->doCoulomb && pme->doLJ);
1094
1095     /* We need a maximum of four separate PME calculations:
1096      * grid_index=0: Coulomb PME with charges from state A
1097      * grid_index=1: Coulomb PME with charges from state B
1098      * grid_index=2: LJ PME with C6 from state A
1099      * grid_index=3: LJ PME with C6 from state B
1100      * For Lorentz-Berthelot combination rules, a separate loop is used to
1101      * calculate all the terms
1102      */
1103
1104     /* If we are doing LJ-PME with LB, we only do Q here */
1105     max_grid_index = (pme->ljpme_combination_rule == eljpmeLB) ? DO_Q : DO_Q_AND_LJ;
1106
1107     for (grid_index = 0; grid_index < max_grid_index; ++grid_index)
1108     {
1109         /* Check if we should do calculations at this grid_index
1110          * If grid_index is odd we should be doing FEP
1111          * If grid_index < 2 we should be doing electrostatic PME
1112          * If grid_index >= 2 we should be doing LJ-PME
1113          */
1114         if ((grid_index < DO_Q && (!pme->doCoulomb || (grid_index == 1 && !pme->bFEP_q)))
1115             || (grid_index >= DO_Q && (!pme->doLJ || (grid_index == 3 && !pme->bFEP_lj))))
1116         {
1117             continue;
1118         }
1119         /* Unpack structure */
1120         pmegrid    = &pme->pmegrid[grid_index];
1121         fftgrid    = pme->fftgrid[grid_index];
1122         cfftgrid   = pme->cfftgrid[grid_index];
1123         pfft_setup = pme->pfft_setup[grid_index];
1124         switch (grid_index)
1125         {
1126             case 0: coefficient = chargeA; break;
1127             case 1: coefficient = chargeB; break;
1128             case 2: coefficient = c6A; break;
1129             case 3: coefficient = c6B; break;
1130         }
1131
1132         grid = pmegrid->grid.grid;
1133
1134         if (debug)
1135         {
1136             fprintf(debug, "PME: number of ranks = %d, rank = %d\n", cr->nnodes, cr->nodeid);
1137             fprintf(debug, "Grid = %p\n", static_cast<void*>(grid));
1138             if (grid == nullptr)
1139             {
1140                 gmx_fatal(FARGS, "No grid!");
1141             }
1142         }
1143
1144         if (pme->nnodes == 1)
1145         {
1146             atc.coefficient = gmx::arrayRefFromArray(coefficient, coordinates.size());
1147         }
1148         else
1149         {
1150             wallcycle_start(wcycle, ewcPME_REDISTXF);
1151             do_redist_pos_coeffs(pme, cr, bFirst, coordinates, coefficient);
1152
1153             wallcycle_stop(wcycle, ewcPME_REDISTXF);
1154         }
1155
1156         if (debug)
1157         {
1158             fprintf(debug, "Rank= %6d, pme local particles=%6d\n", cr->nodeid, atc.numAtoms());
1159         }
1160
1161         wallcycle_start(wcycle, ewcPME_SPREAD);
1162
1163         /* Spread the coefficients on a grid */
1164         spread_on_grid(pme, &atc, pmegrid, bFirst, TRUE, fftgrid, bDoSplines, grid_index);
1165
1166         if (bFirst)
1167         {
1168             inc_nrnb(nrnb, eNR_WEIGHTS, DIM * atc.numAtoms());
1169         }
1170         inc_nrnb(nrnb, eNR_SPREADBSP, pme->pme_order * pme->pme_order * pme->pme_order * atc.numAtoms());
1171
1172         if (!pme->bUseThreads)
1173         {
1174             wrap_periodic_pmegrid(pme, grid);
1175
1176             /* sum contributions to local grid from other nodes */
1177             if (pme->nnodes > 1)
1178             {
1179                 gmx_sum_qgrid_dd(pme, grid, GMX_SUM_GRID_FORWARD);
1180             }
1181
1182             copy_pmegrid_to_fftgrid(pme, grid, fftgrid, grid_index);
1183         }
1184
1185         wallcycle_stop(wcycle, ewcPME_SPREAD);
1186
1187         /* TODO If the OpenMP and single-threaded implementations
1188            converge, then spread_on_grid() and
1189            copy_pmegrid_to_fftgrid() will perhaps live in the same
1190            source file.
1191         */
1192
1193         /* Here we start a large thread parallel region */
1194 #pragma omp parallel num_threads(pme->nthread) private(thread)
1195         {
1196             try
1197             {
1198                 thread = gmx_omp_get_thread_num();
1199                 int loop_count;
1200
1201                 /* do 3d-fft */
1202                 if (thread == 0)
1203                 {
1204                     wallcycle_start(wcycle, ewcPME_FFT);
1205                 }
1206                 gmx_parallel_3dfft_execute(pfft_setup, GMX_FFT_REAL_TO_COMPLEX, thread, wcycle);
1207                 if (thread == 0)
1208                 {
1209                     wallcycle_stop(wcycle, ewcPME_FFT);
1210                 }
1211
1212                 /* solve in k-space for our local cells */
1213                 if (thread == 0)
1214                 {
1215                     wallcycle_start(wcycle, (grid_index < DO_Q ? ewcPME_SOLVE : ewcLJPME));
1216                 }
1217                 if (grid_index < DO_Q)
1218                 {
1219                     loop_count = solve_pme_yzx(
1220                             pme, cfftgrid, scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ],
1221                             computeEnergyAndVirial, pme->nthread, thread);
1222                 }
1223                 else
1224                 {
1225                     loop_count =
1226                             solve_pme_lj_yzx(pme, &cfftgrid, FALSE,
1227                                              scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ],
1228                                              computeEnergyAndVirial, pme->nthread, thread);
1229                 }
1230
1231                 if (thread == 0)
1232                 {
1233                     wallcycle_stop(wcycle, (grid_index < DO_Q ? ewcPME_SOLVE : ewcLJPME));
1234                     inc_nrnb(nrnb, eNR_SOLVEPME, loop_count);
1235                 }
1236
1237                 /* do 3d-invfft */
1238                 if (thread == 0)
1239                 {
1240                     wallcycle_start(wcycle, ewcPME_FFT);
1241                 }
1242                 gmx_parallel_3dfft_execute(pfft_setup, GMX_FFT_COMPLEX_TO_REAL, thread, wcycle);
1243                 if (thread == 0)
1244                 {
1245                     wallcycle_stop(wcycle, ewcPME_FFT);
1246
1247
1248                     if (pme->nodeid == 0)
1249                     {
1250                         real ntot = pme->nkx * pme->nky * pme->nkz;
1251                         npme      = static_cast<int>(ntot * std::log(ntot) / std::log(2.0));
1252                         inc_nrnb(nrnb, eNR_FFT, 2 * npme);
1253                     }
1254
1255                     /* Note: this wallcycle region is closed below
1256                        outside an OpenMP region, so take care if
1257                        refactoring code here. */
1258                     wallcycle_start(wcycle, ewcPME_GATHER);
1259                 }
1260
1261                 copy_fftgrid_to_pmegrid(pme, fftgrid, grid, grid_index, pme->nthread, thread);
1262             }
1263             GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1264         }
1265         /* End of thread parallel section.
1266          * With MPI we have to synchronize here before gmx_sum_qgrid_dd.
1267          */
1268
1269         /* distribute local grid to all nodes */
1270         if (pme->nnodes > 1)
1271         {
1272             gmx_sum_qgrid_dd(pme, grid, GMX_SUM_GRID_BACKWARD);
1273         }
1274
1275         unwrap_periodic_pmegrid(pme, grid);
1276
1277         if (stepWork.computeForces)
1278         {
1279             /* interpolate forces for our local atoms */
1280
1281
1282             /* If we are running without parallelization,
1283              * atc->f is the actual force array, not a buffer,
1284              * therefore we should not clear it.
1285              */
1286             lambda  = grid_index < DO_Q ? lambda_q : lambda_lj;
1287             bClearF = (bFirst && PAR(cr));
1288 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
1289             for (thread = 0; thread < pme->nthread; thread++)
1290             {
1291                 try
1292                 {
1293                     gather_f_bsplines(pme, grid, bClearF, &atc, &atc.spline[thread],
1294                                       pme->bFEP ? (grid_index % 2 == 0 ? 1.0 - lambda : lambda) : 1.0);
1295                 }
1296                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1297             }
1298
1299
1300             inc_nrnb(nrnb, eNR_GATHERFBSP,
1301                      pme->pme_order * pme->pme_order * pme->pme_order * atc.numAtoms());
1302             /* Note: this wallcycle region is opened above inside an OpenMP
1303                region, so take care if refactoring code here. */
1304             wallcycle_stop(wcycle, ewcPME_GATHER);
1305         }
1306
1307         if (computeEnergyAndVirial)
1308         {
1309             /* This should only be called on the master thread
1310              * and after the threads have synchronized.
1311              */
1312             if (grid_index < 2)
1313             {
1314                 get_pme_ener_vir_q(pme->solve_work, pme->nthread, &output[grid_index % 2]);
1315             }
1316             else
1317             {
1318                 get_pme_ener_vir_lj(pme->solve_work, pme->nthread, &output[grid_index % 2]);
1319             }
1320         }
1321         bFirst = FALSE;
1322     } /* of grid_index-loop */
1323
1324     /* For Lorentz-Berthelot combination rules in LJ-PME, we need to calculate
1325      * seven terms. */
1326
1327     if (pme->doLJ && pme->ljpme_combination_rule == eljpmeLB)
1328     {
1329         /* Loop over A- and B-state if we are doing FEP */
1330         for (fep_state = 0; fep_state < fep_states_lj; ++fep_state)
1331         {
1332             real *local_c6 = nullptr, *local_sigma = nullptr, *RedistC6 = nullptr, *RedistSigma = nullptr;
1333             gmx::ArrayRef<real> coefficientBuffer;
1334             if (pme->nnodes == 1)
1335             {
1336                 pme->lb_buf1.resize(atc.numAtoms());
1337                 coefficientBuffer = pme->lb_buf1;
1338                 switch (fep_state)
1339                 {
1340                     case 0:
1341                         local_c6    = c6A;
1342                         local_sigma = sigmaA;
1343                         break;
1344                     case 1:
1345                         local_c6    = c6B;
1346                         local_sigma = sigmaB;
1347                         break;
1348                     default: gmx_incons("Trying to access wrong FEP-state in LJ-PME routine");
1349                 }
1350             }
1351             else
1352             {
1353                 coefficientBuffer = atc.coefficientBuffer;
1354                 switch (fep_state)
1355                 {
1356                     case 0:
1357                         RedistC6    = c6A;
1358                         RedistSigma = sigmaA;
1359                         break;
1360                     case 1:
1361                         RedistC6    = c6B;
1362                         RedistSigma = sigmaB;
1363                         break;
1364                     default: gmx_incons("Trying to access wrong FEP-state in LJ-PME routine");
1365                 }
1366                 wallcycle_start(wcycle, ewcPME_REDISTXF);
1367
1368                 do_redist_pos_coeffs(pme, cr, bFirst, coordinates, RedistC6);
1369                 pme->lb_buf1.resize(atc.numAtoms());
1370                 pme->lb_buf2.resize(atc.numAtoms());
1371                 local_c6 = pme->lb_buf1.data();
1372                 for (int i = 0; i < atc.numAtoms(); ++i)
1373                 {
1374                     local_c6[i] = atc.coefficient[i];
1375                 }
1376
1377                 do_redist_pos_coeffs(pme, cr, FALSE, coordinates, RedistSigma);
1378                 local_sigma = pme->lb_buf2.data();
1379                 for (int i = 0; i < atc.numAtoms(); ++i)
1380                 {
1381                     local_sigma[i] = atc.coefficient[i];
1382                 }
1383
1384                 wallcycle_stop(wcycle, ewcPME_REDISTXF);
1385             }
1386             atc.coefficient = coefficientBuffer;
1387             calc_initial_lb_coeffs(coefficientBuffer, local_c6, local_sigma);
1388
1389             /*Seven terms in LJ-PME with LB, grid_index < 2 reserved for electrostatics*/
1390             for (grid_index = 2; grid_index < 9; ++grid_index)
1391             {
1392                 /* Unpack structure */
1393                 pmegrid    = &pme->pmegrid[grid_index];
1394                 fftgrid    = pme->fftgrid[grid_index];
1395                 pfft_setup = pme->pfft_setup[grid_index];
1396                 calc_next_lb_coeffs(coefficientBuffer, local_sigma);
1397                 grid = pmegrid->grid.grid;
1398
1399                 wallcycle_start(wcycle, ewcPME_SPREAD);
1400                 /* Spread the c6 on a grid */
1401                 spread_on_grid(pme, &atc, pmegrid, bFirst, TRUE, fftgrid, bDoSplines, grid_index);
1402
1403                 if (bFirst)
1404                 {
1405                     inc_nrnb(nrnb, eNR_WEIGHTS, DIM * atc.numAtoms());
1406                 }
1407
1408                 inc_nrnb(nrnb, eNR_SPREADBSP,
1409                          pme->pme_order * pme->pme_order * pme->pme_order * atc.numAtoms());
1410                 if (pme->nthread == 1)
1411                 {
1412                     wrap_periodic_pmegrid(pme, grid);
1413                     /* sum contributions to local grid from other nodes */
1414                     if (pme->nnodes > 1)
1415                     {
1416                         gmx_sum_qgrid_dd(pme, grid, GMX_SUM_GRID_FORWARD);
1417                     }
1418                     copy_pmegrid_to_fftgrid(pme, grid, fftgrid, grid_index);
1419                 }
1420                 wallcycle_stop(wcycle, ewcPME_SPREAD);
1421
1422                 /*Here we start a large thread parallel region*/
1423 #pragma omp parallel num_threads(pme->nthread) private(thread)
1424                 {
1425                     try
1426                     {
1427                         thread = gmx_omp_get_thread_num();
1428                         /* do 3d-fft */
1429                         if (thread == 0)
1430                         {
1431                             wallcycle_start(wcycle, ewcPME_FFT);
1432                         }
1433
1434                         gmx_parallel_3dfft_execute(pfft_setup, GMX_FFT_REAL_TO_COMPLEX, thread, wcycle);
1435                         if (thread == 0)
1436                         {
1437                             wallcycle_stop(wcycle, ewcPME_FFT);
1438                         }
1439                     }
1440                     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1441                 }
1442                 bFirst = FALSE;
1443             }
1444             /* solve in k-space for our local cells */
1445 #pragma omp parallel num_threads(pme->nthread) private(thread)
1446             {
1447                 try
1448                 {
1449                     int loop_count;
1450                     thread = gmx_omp_get_thread_num();
1451                     if (thread == 0)
1452                     {
1453                         wallcycle_start(wcycle, ewcLJPME);
1454                     }
1455
1456                     loop_count =
1457                             solve_pme_lj_yzx(pme, &pme->cfftgrid[2], TRUE,
1458                                              scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ],
1459                                              computeEnergyAndVirial, pme->nthread, thread);
1460                     if (thread == 0)
1461                     {
1462                         wallcycle_stop(wcycle, ewcLJPME);
1463                         inc_nrnb(nrnb, eNR_SOLVEPME, loop_count);
1464                     }
1465                 }
1466                 GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1467             }
1468
1469             if (computeEnergyAndVirial)
1470             {
1471                 /* This should only be called on the master thread and
1472                  * after the threads have synchronized.
1473                  */
1474                 get_pme_ener_vir_lj(pme->solve_work, pme->nthread, &output[fep_state]);
1475             }
1476
1477             bFirst = !pme->doCoulomb;
1478             calc_initial_lb_coeffs(coefficientBuffer, local_c6, local_sigma);
1479             for (grid_index = 8; grid_index >= 2; --grid_index)
1480             {
1481                 /* Unpack structure */
1482                 pmegrid    = &pme->pmegrid[grid_index];
1483                 fftgrid    = pme->fftgrid[grid_index];
1484                 pfft_setup = pme->pfft_setup[grid_index];
1485                 grid       = pmegrid->grid.grid;
1486                 calc_next_lb_coeffs(coefficientBuffer, local_sigma);
1487 #pragma omp parallel num_threads(pme->nthread) private(thread)
1488                 {
1489                     try
1490                     {
1491                         thread = gmx_omp_get_thread_num();
1492                         /* do 3d-invfft */
1493                         if (thread == 0)
1494                         {
1495                             wallcycle_start(wcycle, ewcPME_FFT);
1496                         }
1497
1498                         gmx_parallel_3dfft_execute(pfft_setup, GMX_FFT_COMPLEX_TO_REAL, thread, wcycle);
1499                         if (thread == 0)
1500                         {
1501                             wallcycle_stop(wcycle, ewcPME_FFT);
1502
1503
1504                             if (pme->nodeid == 0)
1505                             {
1506                                 real ntot = pme->nkx * pme->nky * pme->nkz;
1507                                 npme      = static_cast<int>(ntot * std::log(ntot) / std::log(2.0));
1508                                 inc_nrnb(nrnb, eNR_FFT, 2 * npme);
1509                             }
1510                             wallcycle_start(wcycle, ewcPME_GATHER);
1511                         }
1512
1513                         copy_fftgrid_to_pmegrid(pme, fftgrid, grid, grid_index, pme->nthread, thread);
1514                     }
1515                     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1516                 } /*#pragma omp parallel*/
1517
1518                 /* distribute local grid to all nodes */
1519                 if (pme->nnodes > 1)
1520                 {
1521                     gmx_sum_qgrid_dd(pme, grid, GMX_SUM_GRID_BACKWARD);
1522                 }
1523
1524                 unwrap_periodic_pmegrid(pme, grid);
1525
1526                 if (stepWork.computeForces)
1527                 {
1528                     /* interpolate forces for our local atoms */
1529                     bClearF = (bFirst && PAR(cr));
1530                     scale   = pme->bFEP ? (fep_state < 1 ? 1.0 - lambda_lj : lambda_lj) : 1.0;
1531                     scale *= lb_scale_factor[grid_index - 2];
1532
1533 #pragma omp parallel for num_threads(pme->nthread) schedule(static)
1534                     for (thread = 0; thread < pme->nthread; thread++)
1535                     {
1536                         try
1537                         {
1538                             gather_f_bsplines(pme, grid, bClearF, &pme->atc[0],
1539                                               &pme->atc[0].spline[thread], scale);
1540                         }
1541                         GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
1542                     }
1543
1544
1545                     inc_nrnb(nrnb, eNR_GATHERFBSP,
1546                              pme->pme_order * pme->pme_order * pme->pme_order * pme->atc[0].numAtoms());
1547                 }
1548                 wallcycle_stop(wcycle, ewcPME_GATHER);
1549
1550                 bFirst = FALSE;
1551             } /* for (grid_index = 8; grid_index >= 2; --grid_index) */
1552         }     /* for (fep_state = 0; fep_state < fep_states_lj; ++fep_state) */
1553     }         /* if (pme->doLJ && pme->ljpme_combination_rule == eljpmeLB) */
1554
1555     if (stepWork.computeForces && pme->nnodes > 1)
1556     {
1557         wallcycle_start(wcycle, ewcPME_REDISTXF);
1558         for (d = 0; d < pme->ndecompdim; d++)
1559         {
1560             gmx::ArrayRef<gmx::RVec> forcesRef;
1561             if (d == pme->ndecompdim - 1)
1562             {
1563                 const size_t numAtoms = coordinates.size();
1564                 GMX_ASSERT(forces.size() >= numAtoms, "Need at least numAtoms forces");
1565                 forcesRef = forces.subArray(0, numAtoms);
1566             }
1567             else
1568             {
1569                 forcesRef = pme->atc[d + 1].f;
1570             }
1571             if (DOMAINDECOMP(cr))
1572             {
1573                 dd_pmeredist_f(pme, &pme->atc[d], forcesRef, d == pme->ndecompdim - 1 && pme->bPPnode);
1574             }
1575         }
1576
1577         wallcycle_stop(wcycle, ewcPME_REDISTXF);
1578     }
1579
1580     if (computeEnergyAndVirial)
1581     {
1582         if (pme->doCoulomb)
1583         {
1584             if (!pme->bFEP_q)
1585             {
1586                 *energy_q = output[0].coulombEnergy_;
1587                 m_add(vir_q, output[0].coulombVirial_, vir_q);
1588             }
1589             else
1590             {
1591                 *energy_q = (1.0 - lambda_q) * output[0].coulombEnergy_ + lambda_q * output[1].coulombEnergy_;
1592                 *dvdlambda_q += output[1].coulombEnergy_ - output[0].coulombEnergy_;
1593                 for (int i = 0; i < DIM; i++)
1594                 {
1595                     for (int j = 0; j < DIM; j++)
1596                     {
1597                         vir_q[i][j] += (1.0 - lambda_q) * output[0].coulombVirial_[i][j]
1598                                        + lambda_q * output[1].coulombVirial_[i][j];
1599                     }
1600                 }
1601             }
1602             if (debug)
1603             {
1604                 fprintf(debug, "Electrostatic PME mesh energy: %g\n", *energy_q);
1605             }
1606         }
1607         else
1608         {
1609             *energy_q = 0;
1610         }
1611
1612         if (pme->doLJ)
1613         {
1614             if (!pme->bFEP_lj)
1615             {
1616                 *energy_lj = output[0].lennardJonesEnergy_;
1617                 m_add(vir_lj, output[0].lennardJonesVirial_, vir_lj);
1618             }
1619             else
1620             {
1621                 *energy_lj = (1.0 - lambda_lj) * output[0].lennardJonesEnergy_
1622                              + lambda_lj * output[1].lennardJonesEnergy_;
1623                 *dvdlambda_lj += output[1].lennardJonesEnergy_ - output[0].lennardJonesEnergy_;
1624                 for (int i = 0; i < DIM; i++)
1625                 {
1626                     for (int j = 0; j < DIM; j++)
1627                     {
1628                         vir_lj[i][j] += (1.0 - lambda_lj) * output[0].lennardJonesVirial_[i][j]
1629                                         + lambda_lj * output[1].lennardJonesVirial_[i][j];
1630                     }
1631                 }
1632             }
1633             if (debug)
1634             {
1635                 fprintf(debug, "Lennard-Jones PME mesh energy: %g\n", *energy_lj);
1636             }
1637         }
1638         else
1639         {
1640             *energy_lj = 0;
1641         }
1642     }
1643     return 0;
1644 }
1645
1646 void gmx_pme_destroy(gmx_pme_t* pme)
1647 {
1648     if (!pme)
1649     {
1650         return;
1651     }
1652
1653     delete pme->boxScaler;
1654
1655     sfree(pme->nnx);
1656     sfree(pme->nny);
1657     sfree(pme->nnz);
1658     sfree(pme->fshx);
1659     sfree(pme->fshy);
1660     sfree(pme->fshz);
1661
1662     for (int i = 0; i < pme->ngrids; ++i)
1663     {
1664         pmegrids_destroy(&pme->pmegrid[i]);
1665     }
1666     if (pme->pfft_setup)
1667     {
1668         for (int i = 0; i < pme->ngrids; ++i)
1669         {
1670             gmx_parallel_3dfft_destroy(pme->pfft_setup[i]);
1671         }
1672     }
1673     sfree(pme->fftgrid);
1674     sfree(pme->cfftgrid);
1675     sfree(pme->pfft_setup);
1676
1677     for (int i = 0; i < DIM; i++)
1678     {
1679         sfree(pme->bsp_mod[i]);
1680     }
1681
1682     sfree(pme->bufv);
1683     sfree(pme->bufr);
1684
1685     if (pme->solve_work)
1686     {
1687         pme_free_all_work(&pme->solve_work, pme->nthread);
1688     }
1689
1690     sfree(pme->sum_qgrid_tmp);
1691     sfree(pme->sum_qgrid_dd_tmp);
1692
1693     destroy_pme_spline_work(pme->spline_work);
1694
1695     if (pme->gpu != nullptr)
1696     {
1697         pme_gpu_destroy(pme->gpu);
1698     }
1699
1700     delete pme;
1701 }
1702
1703 void gmx_pme_reinit_atoms(gmx_pme_t* pme, const int numAtoms, const real* chargesA, const real* chargesB)
1704 {
1705     if (pme->gpu != nullptr)
1706     {
1707         GMX_ASSERT(!(pme->bFEP_q && chargesB == nullptr),
1708                    "B state charges must be specified if running Coulomb FEP on the GPU");
1709         pme_gpu_reinit_atoms(pme->gpu, numAtoms, chargesA, pme->bFEP_q ? chargesB : nullptr);
1710     }
1711     else
1712     {
1713         pme->atc[0].setNumAtoms(numAtoms);
1714         // TODO: set the charges here as well
1715     }
1716 }
1717
1718 bool gmx_pme_grid_matches(const gmx_pme_t& pme, const ivec grid_size)
1719 {
1720     return (pme.nkx == grid_size[XX] && pme.nky == grid_size[YY] && pme.nkz == grid_size[ZZ]);
1721 }