2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
37 * Implements common routines for PME tests.
39 * \author Aleksei Iupinov <a.yupinov@gmail.com>
40 * \ingroup module_ewald
44 #include "pmetestcommon.h"
50 #include "gromacs/domdec/domdec.h"
51 #include "gromacs/ewald/pme_gather.h"
52 #include "gromacs/ewald/pme_gpu_calculate_splines.h"
53 #include "gromacs/ewald/pme_gpu_constants.h"
54 #include "gromacs/ewald/pme_gpu_internal.h"
55 #include "gromacs/ewald/pme_gpu_staging.h"
56 #include "gromacs/ewald/pme_grid.h"
57 #include "gromacs/ewald/pme_internal.h"
58 #include "gromacs/ewald/pme_redistribute.h"
59 #include "gromacs/ewald/pme_solve.h"
60 #include "gromacs/ewald/pme_spread.h"
61 #include "gromacs/fft/parallel_3dfft.h"
62 #include "gromacs/gpu_utils/device_stream_manager.h"
63 #include "gromacs/gpu_utils/gpu_utils.h"
64 #include "gromacs/math/invertmatrix.h"
65 #include "gromacs/mdtypes/commrec.h"
66 #include "gromacs/pbcutil/pbc.h"
67 #include "gromacs/topology/topology.h"
68 #include "gromacs/utility/exceptions.h"
69 #include "gromacs/utility/gmxassert.h"
70 #include "gromacs/utility/logger.h"
71 #include "gromacs/utility/stringutil.h"
73 #include "testutils/testasserts.h"
75 #include "testhardwarecontexts.h"
82 bool pmeSupportsInputForMode(const gmx_hw_info_t& hwinfo, const t_inputrec* inputRec, CodePath mode)
88 case CodePath::CPU: implemented = true; break;
91 implemented = (pme_gpu_supports_build(nullptr) && pme_gpu_supports_hardware(hwinfo, nullptr)
92 && pme_gpu_supports_input(*inputRec, mtop, nullptr));
95 default: GMX_THROW(InternalError("Test not implemented for this mode"));
100 uint64_t getSplineModuliDoublePrecisionUlps(int splineOrder)
102 /* Arbitrary ulp tolerance for sine/cosine implementation. It's
103 * hard to know what to pick without testing lots of
104 * implementations. */
105 const uint64_t sineUlps = 10;
106 return 4 * (splineOrder - 2) + 2 * sineUlps * splineOrder;
109 //! PME initialization
110 PmeSafePointer pmeInitWrapper(const t_inputrec* inputRec,
112 const DeviceContext* deviceContext,
113 const DeviceStream* deviceStream,
114 const PmeGpuProgram* pmeGpuProgram,
115 const Matrix3x3& box,
116 const real ewaldCoeff_q,
117 const real ewaldCoeff_lj)
119 const MDLogger dummyLogger;
120 const auto runMode = (mode == CodePath::CPU) ? PmeRunMode::CPU : PmeRunMode::Mixed;
121 t_commrec dummyCommrec = { 0 };
122 NumPmeDomains numPmeDomains = { 1, 1 };
123 gmx_pme_t* pmeDataRaw = gmx_pme_init(&dummyCommrec, numPmeDomains, inputRec, false, false, true,
124 ewaldCoeff_q, ewaldCoeff_lj, 1, runMode, nullptr,
125 deviceContext, deviceStream, pmeGpuProgram, dummyLogger);
126 PmeSafePointer pme(pmeDataRaw); // taking ownership
128 // TODO get rid of this with proper matrix type
130 for (int i = 0; i < DIM; i++)
132 for (int j = 0; j < DIM; j++)
134 boxTemp[i][j] = box[i * DIM + j];
137 const char* boxError = check_box(PbcType::Unset, boxTemp);
138 GMX_RELEASE_ASSERT(boxError == nullptr, boxError);
142 case CodePath::CPU: invertBoxMatrix(boxTemp, pme->recipbox); break;
145 pme_gpu_set_testing(pme->gpu, true);
146 pme_gpu_update_input_box(pme->gpu, boxTemp);
149 default: GMX_THROW(InternalError("Test not implemented for this mode"));
155 //! Simple PME initialization based on input, no atom data
156 PmeSafePointer pmeInitEmpty(const t_inputrec* inputRec,
158 const DeviceContext* deviceContext,
159 const DeviceStream* deviceStream,
160 const PmeGpuProgram* pmeGpuProgram,
161 const Matrix3x3& box,
162 const real ewaldCoeff_q,
163 const real ewaldCoeff_lj)
165 return pmeInitWrapper(inputRec, mode, deviceContext, deviceStream, pmeGpuProgram, box,
166 ewaldCoeff_q, ewaldCoeff_lj);
167 // hiding the fact that PME actually needs to know the number of atoms in advance
170 PmeSafePointer pmeInitEmpty(const t_inputrec* inputRec)
172 const Matrix3x3 defaultBox = { { 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F } };
173 return pmeInitWrapper(inputRec, CodePath::CPU, nullptr, nullptr, nullptr, defaultBox, 0.0F, 0.0F);
176 //! Make a GPU state-propagator manager
177 std::unique_ptr<StatePropagatorDataGpu> makeStatePropagatorDataGpu(const gmx_pme_t& pme,
178 const DeviceContext* deviceContext,
179 const DeviceStream* deviceStream)
181 // TODO: Pin the host buffer and use async memory copies
182 // TODO: Special constructor for PME-only rank / PME-tests is used here. There should be a mechanism to
183 // restrict one from using other constructor here.
184 return std::make_unique<StatePropagatorDataGpu>(deviceStream, *deviceContext, GpuApiCallBehavior::Sync,
185 pme_gpu_get_block_size(&pme), nullptr);
188 //! PME initialization with atom data
189 void pmeInitAtoms(gmx_pme_t* pme,
190 StatePropagatorDataGpu* stateGpu,
192 const CoordinatesVector& coordinates,
193 const ChargesVector& charges)
195 const index atomCount = coordinates.size();
196 GMX_RELEASE_ASSERT(atomCount == charges.ssize(), "Mismatch in atom data");
197 PmeAtomComm* atc = nullptr;
202 atc = &(pme->atc[0]);
203 atc->x = coordinates;
204 atc->coefficient = charges;
205 gmx_pme_reinit_atoms(pme, atomCount, charges.data());
206 /* With decomposition there would be more boilerplate atc code here, e.g. do_redist_pos_coeffs */
210 // TODO: Avoid use of atc in the GPU code path
211 atc = &(pme->atc[0]);
212 // We need to set atc->n for passing the size in the tests
213 atc->setNumAtoms(atomCount);
214 gmx_pme_reinit_atoms(pme, atomCount, charges.data());
216 stateGpu->reinit(atomCount, atomCount);
217 stateGpu->copyCoordinatesToGpu(arrayRefFromArray(coordinates.data(), coordinates.size()),
218 gmx::AtomLocality::All);
219 pme_gpu_set_kernelparam_coordinates(pme->gpu, stateGpu->getCoordinates());
223 default: GMX_THROW(InternalError("Test not implemented for this mode"));
227 //! Getting local PME real grid pointer for test I/O
228 static real* pmeGetRealGridInternal(const gmx_pme_t* pme)
230 const size_t gridIndex = 0;
231 return pme->fftgrid[gridIndex];
234 //! Getting local PME real grid dimensions
235 static void pmeGetRealGridSizesInternal(const gmx_pme_t* pme,
237 IVec& gridSize, //NOLINT(google-runtime-references)
238 IVec& paddedGridSize) //NOLINT(google-runtime-references)
240 const size_t gridIndex = 0;
241 IVec gridOffsetUnused;
245 gmx_parallel_3dfft_real_limits(pme->pfft_setup[gridIndex], gridSize, gridOffsetUnused,
250 pme_gpu_get_real_grid_sizes(pme->gpu, &gridSize, &paddedGridSize);
253 default: GMX_THROW(InternalError("Test not implemented for this mode"));
257 //! Getting local PME complex grid pointer for test I/O
258 static t_complex* pmeGetComplexGridInternal(const gmx_pme_t* pme)
260 const size_t gridIndex = 0;
261 return pme->cfftgrid[gridIndex];
264 //! Getting local PME complex grid dimensions
265 static void pmeGetComplexGridSizesInternal(const gmx_pme_t* pme,
266 IVec& gridSize, //NOLINT(google-runtime-references)
267 IVec& paddedGridSize) //NOLINT(google-runtime-references)
269 const size_t gridIndex = 0;
270 IVec gridOffsetUnused, complexOrderUnused;
271 gmx_parallel_3dfft_complex_limits(pme->pfft_setup[gridIndex], complexOrderUnused, gridSize,
272 gridOffsetUnused, paddedGridSize); // TODO: what about YZX ordering?
275 //! Getting the PME grid memory buffer and its sizes - template definition
276 template<typename ValueType>
277 static void pmeGetGridAndSizesInternal(const gmx_pme_t* /*unused*/,
279 ValueType*& /*unused*/, //NOLINT(google-runtime-references)
280 IVec& /*unused*/, //NOLINT(google-runtime-references)
281 IVec& /*unused*/) //NOLINT(google-runtime-references)
283 GMX_THROW(InternalError("Deleted function call"));
284 // explicitly deleting general template does not compile in clang/icc, see https://llvm.org/bugs/show_bug.cgi?id=17537
287 //! Getting the PME real grid memory buffer and its sizes
289 void pmeGetGridAndSizesInternal<real>(const gmx_pme_t* pme, CodePath mode, real*& grid, IVec& gridSize, IVec& paddedGridSize)
291 grid = pmeGetRealGridInternal(pme);
292 pmeGetRealGridSizesInternal(pme, mode, gridSize, paddedGridSize);
295 //! Getting the PME complex grid memory buffer and its sizes
297 void pmeGetGridAndSizesInternal<t_complex>(const gmx_pme_t* pme,
301 IVec& paddedGridSize)
303 grid = pmeGetComplexGridInternal(pme);
304 pmeGetComplexGridSizesInternal(pme, gridSize, paddedGridSize);
307 //! PME spline calculation and charge spreading
308 void pmePerformSplineAndSpread(gmx_pme_t* pme,
309 CodePath mode, // TODO const qualifiers elsewhere
313 GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized");
314 PmeAtomComm* atc = &(pme->atc[0]);
315 const size_t gridIndex = 0;
316 const bool computeSplinesForZeroCharges = true;
317 real* fftgrid = spreadCharges ? pme->fftgrid[gridIndex] : nullptr;
318 real* pmegrid = pme->pmegrid[gridIndex].grid.grid;
323 spread_on_grid(pme, atc, &pme->pmegrid[gridIndex], computeSplines, spreadCharges,
324 fftgrid, computeSplinesForZeroCharges, gridIndex);
325 if (spreadCharges && !pme->bUseThreads)
327 wrap_periodic_pmegrid(pme, pmegrid);
328 copy_pmegrid_to_fftgrid(pme, pmegrid, fftgrid, gridIndex);
334 // no synchronization needed as x is transferred in the PME stream
335 GpuEventSynchronizer* xReadyOnDevice = nullptr;
336 pme_gpu_spread(pme->gpu, xReadyOnDevice, gridIndex, fftgrid, computeSplines, spreadCharges);
340 default: GMX_THROW(InternalError("Test not implemented for this mode"));
344 //! Getting the internal spline data buffer pointer
345 static real* pmeGetSplineDataInternal(const gmx_pme_t* pme, PmeSplineDataType type, int dimIndex)
347 GMX_ASSERT((0 <= dimIndex) && (dimIndex < DIM), "Invalid dimension index");
348 const PmeAtomComm* atc = &(pme->atc[0]);
349 const size_t threadIndex = 0;
350 real* splineBuffer = nullptr;
353 case PmeSplineDataType::Values:
354 splineBuffer = atc->spline[threadIndex].theta.coefficients[dimIndex];
357 case PmeSplineDataType::Derivatives:
358 splineBuffer = atc->spline[threadIndex].dtheta.coefficients[dimIndex];
361 default: GMX_THROW(InternalError("Unknown spline data type"));
367 void pmePerformSolve(const gmx_pme_t* pme,
369 PmeSolveAlgorithm method,
371 GridOrdering gridOrdering,
372 bool computeEnergyAndVirial)
374 t_complex* h_grid = pmeGetComplexGridInternal(pme);
375 const bool useLorentzBerthelot = false;
376 const size_t threadIndex = 0;
380 if (gridOrdering != GridOrdering::YZX)
382 GMX_THROW(InternalError("Test not implemented for this mode"));
386 case PmeSolveAlgorithm::Coulomb:
387 solve_pme_yzx(pme, h_grid, cellVolume, computeEnergyAndVirial, pme->nthread, threadIndex);
390 case PmeSolveAlgorithm::LennardJones:
391 solve_pme_lj_yzx(pme, &h_grid, useLorentzBerthelot, cellVolume,
392 computeEnergyAndVirial, pme->nthread, threadIndex);
395 default: GMX_THROW(InternalError("Test not implemented for this mode"));
402 case PmeSolveAlgorithm::Coulomb:
403 pme_gpu_solve(pme->gpu, h_grid, gridOrdering, computeEnergyAndVirial);
406 default: GMX_THROW(InternalError("Test not implemented for this mode"));
410 default: GMX_THROW(InternalError("Test not implemented for this mode"));
414 //! PME force gathering
415 void pmePerformGather(gmx_pme_t* pme, CodePath mode, ForcesVector& forces)
417 PmeAtomComm* atc = &(pme->atc[0]);
418 const index atomCount = atc->numAtoms();
419 GMX_RELEASE_ASSERT(forces.ssize() == atomCount, "Invalid force buffer size");
420 const real scale = 1.0;
421 const size_t threadIndex = 0;
422 const size_t gridIndex = 0;
423 real* pmegrid = pme->pmegrid[gridIndex].grid.grid;
424 real* fftgrid = pme->fftgrid[gridIndex];
430 if (atc->nthread == 1)
432 // something which is normally done in serial spline computation (make_thread_local_ind())
433 atc->spline[threadIndex].n = atomCount;
435 copy_fftgrid_to_pmegrid(pme, fftgrid, pmegrid, gridIndex, pme->nthread, threadIndex);
436 unwrap_periodic_pmegrid(pme, pmegrid);
437 gather_f_bsplines(pme, pmegrid, true, atc, &atc->spline[threadIndex], scale);
442 // Variable initialization needs a non-switch scope
443 const bool computeEnergyAndVirial = false;
444 PmeOutput output = pme_gpu_getOutput(*pme, computeEnergyAndVirial);
445 GMX_ASSERT(forces.size() == output.forces_.size(),
446 "Size of force buffers did not match");
447 pme_gpu_gather(pme->gpu, reinterpret_cast<float*>(fftgrid));
448 std::copy(std::begin(output.forces_), std::end(output.forces_), std::begin(forces));
452 default: GMX_THROW(InternalError("Test not implemented for this mode"));
456 //! PME test finalization before fetching the outputs
457 void pmeFinalizeTest(const gmx_pme_t* pme, CodePath mode)
461 case CodePath::CPU: break;
463 case CodePath::GPU: pme_gpu_synchronize(pme->gpu); break;
465 default: GMX_THROW(InternalError("Test not implemented for this mode"));
469 //! A binary enum for spline data layout transformation
470 enum class PmeLayoutTransform
476 /*! \brief Gets a unique index to an element in a spline parameter buffer.
478 * These theta/dtheta buffers are laid out for GPU spread/gather
479 * kernels. The index is wrt the execution block, in range(0,
480 * atomsPerBlock * order * DIM).
482 * This is a wrapper, only used in unit tests.
483 * \param[in] order PME order
484 * \param[in] splineIndex Spline contribution index (from 0 to \p order - 1)
485 * \param[in] dimIndex Dimension index (from 0 to 2)
486 * \param[in] atomIndex Atom index wrt the block.
487 * \param[in] atomsPerWarp Number of atoms processed by a warp.
489 * \returns Index into theta or dtheta array using GPU layout.
491 static int getSplineParamFullIndex(int order, int splineIndex, int dimIndex, int atomIndex, int atomsPerWarp)
493 if (order != c_pmeGpuOrder)
497 constexpr int fixedOrder = c_pmeGpuOrder;
498 GMX_UNUSED_VALUE(fixedOrder);
500 const int atomWarpIndex = atomIndex % atomsPerWarp;
501 const int warpIndex = atomIndex / atomsPerWarp;
502 int indexBase, result;
503 switch (atomsPerWarp)
506 indexBase = getSplineParamIndexBase<fixedOrder, 1>(warpIndex, atomWarpIndex);
507 result = getSplineParamIndex<fixedOrder, 1>(indexBase, dimIndex, splineIndex);
511 indexBase = getSplineParamIndexBase<fixedOrder, 2>(warpIndex, atomWarpIndex);
512 result = getSplineParamIndex<fixedOrder, 2>(indexBase, dimIndex, splineIndex);
516 indexBase = getSplineParamIndexBase<fixedOrder, 4>(warpIndex, atomWarpIndex);
517 result = getSplineParamIndex<fixedOrder, 4>(indexBase, dimIndex, splineIndex);
521 indexBase = getSplineParamIndexBase<fixedOrder, 8>(warpIndex, atomWarpIndex);
522 result = getSplineParamIndex<fixedOrder, 8>(indexBase, dimIndex, splineIndex);
526 GMX_THROW(NotImplementedError(
527 formatString("Test function call not unrolled for atomsPerWarp = %d in "
528 "getSplineParamFullIndex",
534 /*!\brief Return the number of atoms per warp */
535 static int pme_gpu_get_atoms_per_warp(const PmeGpu* pmeGpu)
537 const int order = pmeGpu->common->pme_order;
538 const int threadsPerAtom =
539 (pmeGpu->settings.threadsPerAtom == ThreadsPerAtom::Order ? order : order * order);
540 return pmeGpu->programHandle_->warpSize() / threadsPerAtom;
543 /*! \brief Rearranges the atom spline data between the GPU and host layouts.
544 * Only used for test purposes so far, likely to be horribly slow.
546 * \param[in] pmeGpu The PME GPU structure.
547 * \param[out] atc The PME CPU atom data structure (with a single-threaded layout).
548 * \param[in] type The spline data type (values or derivatives).
549 * \param[in] dimIndex Dimension index.
550 * \param[in] transform Layout transform type
552 static void pme_gpu_transform_spline_atom_data(const PmeGpu* pmeGpu,
553 const PmeAtomComm* atc,
554 PmeSplineDataType type,
556 PmeLayoutTransform transform)
558 // The GPU atom spline data is laid out in a different way currently than the CPU one.
559 // This function converts the data from GPU to CPU layout (in the host memory).
560 // It is only intended for testing purposes so far.
561 // Ideally we should use similar layouts on CPU and GPU if we care about mixed modes and their
562 // performance (e.g. spreading on GPU, gathering on CPU).
563 GMX_RELEASE_ASSERT(atc->nthread == 1, "Only the serial PME data layout is supported");
564 const uintmax_t threadIndex = 0;
565 const auto atomCount = atc->numAtoms();
566 const auto atomsPerWarp = pme_gpu_get_atoms_per_warp(pmeGpu);
567 const auto pmeOrder = pmeGpu->common->pme_order;
568 GMX_ASSERT(pmeOrder == c_pmeGpuOrder, "Only PME order 4 is implemented");
570 real* cpuSplineBuffer;
571 float* h_splineBuffer;
574 case PmeSplineDataType::Values:
575 cpuSplineBuffer = atc->spline[threadIndex].theta.coefficients[dimIndex];
576 h_splineBuffer = pmeGpu->staging.h_theta;
579 case PmeSplineDataType::Derivatives:
580 cpuSplineBuffer = atc->spline[threadIndex].dtheta.coefficients[dimIndex];
581 h_splineBuffer = pmeGpu->staging.h_dtheta;
584 default: GMX_THROW(InternalError("Unknown spline data type"));
587 for (auto atomIndex = 0; atomIndex < atomCount; atomIndex++)
589 for (auto orderIndex = 0; orderIndex < pmeOrder; orderIndex++)
591 const auto gpuValueIndex =
592 getSplineParamFullIndex(pmeOrder, orderIndex, dimIndex, atomIndex, atomsPerWarp);
593 const auto cpuValueIndex = atomIndex * pmeOrder + orderIndex;
594 GMX_ASSERT(cpuValueIndex < atomCount * pmeOrder,
595 "Atom spline data index out of bounds (while transforming GPU data layout "
599 case PmeLayoutTransform::GpuToHost:
600 cpuSplineBuffer[cpuValueIndex] = h_splineBuffer[gpuValueIndex];
603 case PmeLayoutTransform::HostToGpu:
604 h_splineBuffer[gpuValueIndex] = cpuSplineBuffer[cpuValueIndex];
607 default: GMX_THROW(InternalError("Unknown layout transform"));
613 //! Setting atom spline values/derivatives to be used in spread/gather
614 void pmeSetSplineData(const gmx_pme_t* pme,
616 const SplineParamsDimVector& splineValues,
617 PmeSplineDataType type,
620 const PmeAtomComm* atc = &(pme->atc[0]);
621 const index atomCount = atc->numAtoms();
622 const index pmeOrder = pme->pme_order;
623 const index dimSize = pmeOrder * atomCount;
624 GMX_RELEASE_ASSERT(dimSize == splineValues.ssize(), "Mismatch in spline data");
625 real* splineBuffer = pmeGetSplineDataInternal(pme, type, dimIndex);
630 std::copy(splineValues.begin(), splineValues.end(), splineBuffer);
634 std::copy(splineValues.begin(), splineValues.end(), splineBuffer);
635 pme_gpu_transform_spline_atom_data(pme->gpu, atc, type, dimIndex, PmeLayoutTransform::HostToGpu);
638 default: GMX_THROW(InternalError("Test not implemented for this mode"));
642 //! Setting gridline indices to be used in spread/gather
643 void pmeSetGridLineIndices(gmx_pme_t* pme, CodePath mode, const GridLineIndicesVector& gridLineIndices)
645 PmeAtomComm* atc = &(pme->atc[0]);
646 const index atomCount = atc->numAtoms();
647 GMX_RELEASE_ASSERT(atomCount == gridLineIndices.ssize(), "Mismatch in gridline indices size");
649 IVec paddedGridSizeUnused, gridSize(0, 0, 0);
650 pmeGetRealGridSizesInternal(pme, mode, gridSize, paddedGridSizeUnused);
652 for (const auto& index : gridLineIndices)
654 for (int i = 0; i < DIM; i++)
656 GMX_RELEASE_ASSERT((0 <= index[i]) && (index[i] < gridSize[i]),
657 "Invalid gridline index");
664 memcpy(pme_gpu_staging(pme->gpu).h_gridlineIndices, gridLineIndices.data(),
665 atomCount * sizeof(gridLineIndices[0]));
669 atc->idx.resize(gridLineIndices.size());
670 std::copy(gridLineIndices.begin(), gridLineIndices.end(), atc->idx.begin());
672 default: GMX_THROW(InternalError("Test not implemented for this mode"));
676 //! Getting plain index into the complex 3d grid
677 inline size_t pmeGetGridPlainIndexInternal(const IVec& index, const IVec& paddedGridSize, GridOrdering gridOrdering)
680 switch (gridOrdering)
682 case GridOrdering::YZX:
683 result = (index[YY] * paddedGridSize[ZZ] + index[ZZ]) * paddedGridSize[XX] + index[XX];
686 case GridOrdering::XYZ:
687 result = (index[XX] * paddedGridSize[YY] + index[YY]) * paddedGridSize[ZZ] + index[ZZ];
690 default: GMX_THROW(InternalError("Test not implemented for this mode"));
695 //! Setting real or complex grid
696 template<typename ValueType>
697 static void pmeSetGridInternal(const gmx_pme_t* pme,
699 GridOrdering gridOrdering,
700 const SparseGridValuesInput<ValueType>& gridValues)
702 IVec gridSize(0, 0, 0), paddedGridSize(0, 0, 0);
704 pmeGetGridAndSizesInternal<ValueType>(pme, mode, grid, gridSize, paddedGridSize);
708 case CodePath::GPU: // intentional absence of break, the grid will be copied from the host buffer in testing mode
711 paddedGridSize[XX] * paddedGridSize[YY] * paddedGridSize[ZZ] * sizeof(ValueType));
712 for (const auto& gridValue : gridValues)
714 for (int i = 0; i < DIM; i++)
716 GMX_RELEASE_ASSERT((0 <= gridValue.first[i]) && (gridValue.first[i] < gridSize[i]),
717 "Invalid grid value index");
719 const size_t gridValueIndex =
720 pmeGetGridPlainIndexInternal(gridValue.first, paddedGridSize, gridOrdering);
721 grid[gridValueIndex] = gridValue.second;
725 default: GMX_THROW(InternalError("Test not implemented for this mode"));
729 //! Setting real grid to be used in gather
730 void pmeSetRealGrid(const gmx_pme_t* pme, CodePath mode, const SparseRealGridValuesInput& gridValues)
732 pmeSetGridInternal<real>(pme, mode, GridOrdering::XYZ, gridValues);
735 //! Setting complex grid to be used in solve
736 void pmeSetComplexGrid(const gmx_pme_t* pme,
738 GridOrdering gridOrdering,
739 const SparseComplexGridValuesInput& gridValues)
741 pmeSetGridInternal<t_complex>(pme, mode, gridOrdering, gridValues);
744 //! Getting the single dimension's spline values or derivatives
745 SplineParamsDimVector pmeGetSplineData(const gmx_pme_t* pme, CodePath mode, PmeSplineDataType type, int dimIndex)
747 GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized");
748 const PmeAtomComm* atc = &(pme->atc[0]);
749 const size_t atomCount = atc->numAtoms();
750 const size_t pmeOrder = pme->pme_order;
751 const size_t dimSize = pmeOrder * atomCount;
753 real* sourceBuffer = pmeGetSplineDataInternal(pme, type, dimIndex);
754 SplineParamsDimVector result;
758 pme_gpu_transform_spline_atom_data(pme->gpu, atc, type, dimIndex, PmeLayoutTransform::GpuToHost);
759 result = arrayRefFromArray(sourceBuffer, dimSize);
762 case CodePath::CPU: result = arrayRefFromArray(sourceBuffer, dimSize); break;
764 default: GMX_THROW(InternalError("Test not implemented for this mode"));
769 //! Getting the gridline indices
770 GridLineIndicesVector pmeGetGridlineIndices(const gmx_pme_t* pme, CodePath mode)
772 GMX_RELEASE_ASSERT(pme != nullptr, "PME data is not initialized");
773 const PmeAtomComm* atc = &(pme->atc[0]);
774 const size_t atomCount = atc->numAtoms();
776 GridLineIndicesVector gridLineIndices;
780 gridLineIndices = arrayRefFromArray(
781 reinterpret_cast<IVec*>(pme_gpu_staging(pme->gpu).h_gridlineIndices), atomCount);
784 case CodePath::CPU: gridLineIndices = atc->idx; break;
786 default: GMX_THROW(InternalError("Test not implemented for this mode"));
788 return gridLineIndices;
791 //! Getting real or complex grid - only non zero values
792 template<typename ValueType>
793 static SparseGridValuesOutput<ValueType> pmeGetGridInternal(const gmx_pme_t* pme,
795 GridOrdering gridOrdering)
797 IVec gridSize(0, 0, 0), paddedGridSize(0, 0, 0);
799 pmeGetGridAndSizesInternal<ValueType>(pme, mode, grid, gridSize, paddedGridSize);
800 SparseGridValuesOutput<ValueType> gridValues;
803 case CodePath::GPU: // intentional absence of break
806 for (int ix = 0; ix < gridSize[XX]; ix++)
808 for (int iy = 0; iy < gridSize[YY]; iy++)
810 for (int iz = 0; iz < gridSize[ZZ]; iz++)
812 IVec temp(ix, iy, iz);
813 const size_t gridValueIndex =
814 pmeGetGridPlainIndexInternal(temp, paddedGridSize, gridOrdering);
815 const ValueType value = grid[gridValueIndex];
816 if (value != ValueType{})
818 auto key = formatString("Cell %d %d %d", ix, iy, iz);
819 gridValues[key] = value;
826 default: GMX_THROW(InternalError("Test not implemented for this mode"));
831 //! Getting the real grid (spreading output of pmePerformSplineAndSpread())
832 SparseRealGridValuesOutput pmeGetRealGrid(const gmx_pme_t* pme, CodePath mode)
834 return pmeGetGridInternal<real>(pme, mode, GridOrdering::XYZ);
837 //! Getting the complex grid output of pmePerformSolve()
838 SparseComplexGridValuesOutput pmeGetComplexGrid(const gmx_pme_t* pme, CodePath mode, GridOrdering gridOrdering)
840 return pmeGetGridInternal<t_complex>(pme, mode, gridOrdering);
843 //! Getting the reciprocal energy and virial
844 PmeOutput pmeGetReciprocalEnergyAndVirial(const gmx_pme_t* pme, CodePath mode, PmeSolveAlgorithm method)
852 case PmeSolveAlgorithm::Coulomb:
853 get_pme_ener_vir_q(pme->solve_work, pme->nthread, &output);
856 case PmeSolveAlgorithm::LennardJones:
857 get_pme_ener_vir_lj(pme->solve_work, pme->nthread, &output);
860 default: GMX_THROW(InternalError("Test not implemented for this mode"));
866 case PmeSolveAlgorithm::Coulomb: pme_gpu_getEnergyAndVirial(*pme, &output); break;
868 default: GMX_THROW(InternalError("Test not implemented for this mode"));
872 default: GMX_THROW(InternalError("Test not implemented for this mode"));