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