File: gmxcalculatorcpu.cpp

package info (click to toggle)
gromacs 2026.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 274,304 kB
  • sloc: xml: 3,831,921; cpp: 686,728; ansic: 75,300; python: 21,171; sh: 3,553; perl: 2,246; yacc: 644; fortran: 397; lisp: 265; makefile: 179; lex: 125; awk: 68; csh: 39
file content (370 lines) | stat: -rw-r--r-- 16,678 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
 * This file is part of the GROMACS molecular simulation package.
 *
 * Copyright 2020- The GROMACS Authors
 * and the project initiators Erik Lindahl, Berk Hess and David van der Spoel.
 * Consult the AUTHORS/COPYING files and https://www.gromacs.org for details.
 *
 * GROMACS is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1
 * of the License, or (at your option) any later version.
 *
 * GROMACS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with GROMACS; if not, see
 * https://www.gnu.org/licenses, or write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
 *
 * If you want to redistribute modifications to GROMACS, please
 * consider that scientific software is very special. Version
 * control is crucial - bugs must be traceable. We will be happy to
 * consider code for inclusion in the official distribution, but
 * derived work must not be called official GROMACS. Details are found
 * in the README & COPYING files - if they are missing, get the
 * official version at https://www.gromacs.org.
 *
 * To help us fund GROMACS development, we humbly ask that you cite
 * the research papers on the package. Check out https://www.gromacs.org.
 */
/*! \internal \file
 * \brief Implements a force calculator based on GROMACS data structures.
 *
 * \author Victor Holanda <victor.holanda@cscs.ch>
 * \author Joe Jordan <ejjordan@kth.se>
 * \author Prashanth Kanduri <kanduri@cscs.ch>
 * \author Sebastian Keller <keller@cscs.ch>
 */
#include "nblib/gmxcalculatorcpu.h"

#include <algorithm>
#include <iterator>
#include <type_traits>

#include "gromacs/ewald/ewald_utils.h"
#include "gromacs/mdtypes/enerdata.h"
#include "gromacs/mdtypes/forcerec.h"
#include "gromacs/mdtypes/interaction_const.h"
#include "gromacs/mdtypes/locality.h"
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/mdtypes/simulation_workload.h"
#include "gromacs/nbnxm/atomdata.h"
#include "gromacs/nbnxm/nbnxm.h"
#include "gromacs/nbnxm/pairlistset.h"
#include "gromacs/nbnxm/pairlistsets.h"
#include "gromacs/nbnxm/pairsearch.h"
#include "gromacs/pbcutil/ishift.h"
#include "gromacs/pbcutil/pbc.h"
#include "gromacs/utility/arrayref.h"
#include "gromacs/utility/enumerationhelpers.h"
#include "gromacs/utility/listoflists.h"
#include "gromacs/utility/range.h"
#include "gromacs/utility/vec.h"

#include "nblib/exception.h"
#include "nblib/kerneloptions.h"
#include "nblib/nbnxmsetuphelpers.h"
#include "nblib/topology.h"
#include "nblib/tpr.h"

#include "gmxbackenddata.h"
#include "pbc.hpp"
#include "systemdescription.h"
#include "virials.h"

namespace nblib
{

class GmxNBForceCalculatorCpu::CpuImpl final
{
public:
    CpuImpl(gmx::ArrayRef<int>     particleTypeIdOfAllParticles,
            gmx::ArrayRef<real>    nonBondedParams,
            gmx::ArrayRef<real>    charges,
            gmx::ArrayRef<int32_t> particleInteractionFlags,
            gmx::ArrayRef<int>     exclusionRanges,
            gmx::ArrayRef<int>     exclusionElements,
            const NBKernelOptions& options);

    //! calculates a new pair list based on new coordinates (for every NS step)
    void updatePairlist(gmx::ArrayRef<gmx::RVec> coordinates, const Box& box);

    //! Compute forces and return
    void compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                 const Box&                     box,
                 gmx::ArrayRef<gmx::RVec>       forceOutput);

    //! Compute forces and virial tensor
    void compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                 const Box&                     box,
                 gmx::ArrayRef<gmx::RVec>       forceOutput,
                 gmx::ArrayRef<real>            virialOutput);

    //! Compute forces, virial tensor and potential energies
    void compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                 const Box&                     box,
                 gmx::ArrayRef<gmx::RVec>       forceOutput,
                 gmx::ArrayRef<real>            virialOutput,
                 gmx::ArrayRef<real>            energyOutput);

private:
    //! \brief client-side provided system description data
    SystemDescription system_;

    //! \brief Gmx backend objects, employed for calculating the forces
    GmxBackendData backend_;
};

GmxNBForceCalculatorCpu::CpuImpl::CpuImpl(gmx::ArrayRef<int>     particleTypeIdOfAllParticles,
                                          gmx::ArrayRef<real>    nonBondedParams,
                                          gmx::ArrayRef<real>    charges,
                                          gmx::ArrayRef<int32_t> particleInteractionFlags,
                                          gmx::ArrayRef<int>     exclusionRanges,
                                          gmx::ArrayRef<int>     exclusionElements,
                                          const NBKernelOptions& options) :
    system_(SystemDescription(particleTypeIdOfAllParticles, nonBondedParams, charges, particleInteractionFlags)),
    backend_(GmxBackendData(options, findNumEnergyGroups(particleInteractionFlags), exclusionRanges, exclusionElements))
{
    // Set up non-bonded verlet in the backend
    backend_.nbv_ = createNbnxmCPU(system_.numParticleTypes_,
                                   options,
                                   findNumEnergyGroups(particleInteractionFlags),
                                   system_.nonBondedParams_);
}

void GmxNBForceCalculatorCpu::CpuImpl::updatePairlist(gmx::ArrayRef<gmx::RVec> coordinates, const Box& box)
{
    if (coordinates.size() != system_.numParticles_)
    {
        throw InputException(
                "Coordinate array containing different number of entries than particles in the "
                "system");
    }

    const auto* legacyBox = box.legacyMatrix();
    system_.box_          = box;
    updateForcerec(&backend_.forcerec_, box.legacyMatrix());
    if (TRICLINIC(legacyBox))
    {
        throw InputException("Only rectangular unit-cells are supported here");
    }

    const rvec lowerCorner = { 0, 0, 0 };
    const rvec upperCorner = { legacyBox[dimX][dimX], legacyBox[dimY][dimY], legacyBox[dimZ][dimZ] };

    const real particleDensity = static_cast<real>(coordinates.size()) / det(legacyBox);

    // If particles are too far outside the box, the grid setup can fail
    put_atoms_in_box_omp(
            PbcType::Xyz, box.legacyMatrix(), false, nullptr, coordinates, {}, backend_.numThreads_);

    // Put particles on a grid based on bounds specified by the box
    backend_.nbv_->putAtomsOnGrid(legacyBox,
                                  0,
                                  lowerCorner,
                                  upperCorner,
                                  nullptr,
                                  { 0, int(coordinates.size()) },
                                  coordinates.size(),
                                  particleDensity,
                                  system_.particleInfo_,
                                  coordinates,
                                  nullptr);

    backend_.nbv_->constructPairlist(
            gmx::InteractionLocality::Local, backend_.exclusions_, false, 0, &backend_.nrnb_);

    // Set Particle Types and Charges and VdW params
    backend_.nbv_->setAtomProperties(
            system_.particleTypeIdOfAllParticles_, system_.charges_, system_.particleInfo_);
    backend_.updatePairlistCalled = true;
}

void GmxNBForceCalculatorCpu::CpuImpl::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                                               const Box&                     box,
                                               gmx::ArrayRef<gmx::RVec>       forceOutput,
                                               gmx::ArrayRef<real>            virialOutput,
                                               gmx::ArrayRef<real>            energyOutput)
{
    if (coordinateInput.size() != forceOutput.size())
    {
        throw InputException("coordinate array and force buffer size mismatch");
    }

    if (!backend_.updatePairlistCalled)
    {
        throw InputException("compute called without updating pairlist at least once");
    }

    // update the box if changed
    if (!(system_.box_ == box))
    {
        system_.box_ = box;
        updateForcerec(&backend_.forcerec_, box.legacyMatrix());
    }

    bool computeVirial               = !virialOutput.empty();
    bool computeEnergies             = !energyOutput.empty();
    backend_.stepWork_.computeVirial = computeVirial;
    backend_.stepWork_.computeEnergy = computeEnergies;

    // update the coordinates in the backend
    backend_.nbv_->convertCoordinates(gmx::AtomLocality::Local, coordinateInput);

    backend_.nbv_->dispatchNonbondedKernel(
            gmx::InteractionLocality::Local,
            backend_.interactionConst_,
            backend_.stepWork_,
            gmx::enbvClearFYes,
            backend_.forcerec_.shift_vec,
            backend_.enerd_.grpp.energyGroupPairTerms[backend_.forcerec_.haveBuckingham ? NonBondedEnergyTerms::BuckinghamSR
                                                                                        : NonBondedEnergyTerms::LJSR],
            backend_.enerd_.grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR],
            &backend_.nrnb_);

    backend_.nbv_->atomdata_add_nbat_f_to_f(gmx::AtomLocality::All, forceOutput);

    if (computeVirial)
    {
        // calculate shift forces and turn into an array ref
        std::vector<Vec3> shiftForcesVector(gmx::c_numShiftVectors, Vec3(0.0, 0.0, 0.0));
        nbnxn_atomdata_add_nbat_fshift_to_fshift(backend_.nbv_->nbat(), shiftForcesVector);
        auto shiftForcesRef = constArrayRefFromArray(shiftForcesVector.data(), shiftForcesVector.size());

        std::vector<Vec3> shiftVectorsArray(gmx::c_numShiftVectors);

        // copy shift vectors from ForceRec
        std::copy(backend_.forcerec_.shift_vec.begin(),
                  backend_.forcerec_.shift_vec.end(),
                  shiftVectorsArray.begin());

        computeVirialTensor(
                coordinateInput, forceOutput, shiftVectorsArray, shiftForcesRef, box, virialOutput);
    }

    // extract term energies (per interaction type)
    if (computeEnergies)
    {
        int nGroupPairs = backend_.enerd_.grpp.nener;
        if (int(energyOutput.size()) != int(NonBondedEnergyTerms::Count) * nGroupPairs)
        {
            throw InputException("Array size for energy output is wrong\n");
        }

        for (int eg = 0; eg < int(NonBondedEnergyTerms::Count); ++eg)
        {
            std::copy(begin(backend_.enerd_.grpp.energyGroupPairTerms[eg]),
                      end(backend_.enerd_.grpp.energyGroupPairTerms[eg]),
                      energyOutput.begin() + eg * nGroupPairs);
        }
    }
}

void GmxNBForceCalculatorCpu::CpuImpl::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                                               const Box&                     box,
                                               gmx::ArrayRef<gmx::RVec>       forceOutput)
{
    // compute forces and fill in force buffer
    compute(coordinateInput, box, forceOutput, gmx::ArrayRef<real>{}, gmx::ArrayRef<real>{});
}

void GmxNBForceCalculatorCpu::CpuImpl::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                                               const Box&                     box,
                                               gmx::ArrayRef<gmx::RVec>       forceOutput,
                                               gmx::ArrayRef<real>            virialOutput)
{
    // compute forces and fill in force buffer
    compute(coordinateInput, box, forceOutput, virialOutput, gmx::ArrayRef<real>{});
}

GmxNBForceCalculatorCpu::GmxNBForceCalculatorCpu(gmx::ArrayRef<int>  particleTypeIdOfAllParticles,
                                                 gmx::ArrayRef<real> nonBondedParams,
                                                 gmx::ArrayRef<real> charges,
                                                 gmx::ArrayRef<int32_t> particleInteractionFlags,
                                                 gmx::ArrayRef<int>     exclusionRanges,
                                                 gmx::ArrayRef<int>     exclusionElements,
                                                 const NBKernelOptions& options)
{
    if (options.useGpu)
    {
        throw InputException("Use GmxNBForceCalculatorGpu for GPU support");
    }

    impl_ = std::make_unique<CpuImpl>(particleTypeIdOfAllParticles,
                                      nonBondedParams,
                                      charges,
                                      particleInteractionFlags,
                                      exclusionRanges,
                                      exclusionElements,
                                      options);
}

GmxNBForceCalculatorCpu::~GmxNBForceCalculatorCpu() = default;

//! calculates a new pair list based on new coordinates (for every NS step)
void GmxNBForceCalculatorCpu::updatePairlist(gmx::ArrayRef<gmx::RVec> coordinates, const Box& box)
{
    impl_->updatePairlist(coordinates, box);
}

//! Compute forces and return
void GmxNBForceCalculatorCpu::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                                      const Box&                     box,
                                      gmx::ArrayRef<gmx::RVec>       forceOutput)
{
    impl_->compute(coordinateInput, box, forceOutput);
}

//! Compute forces and virial tensor
void GmxNBForceCalculatorCpu::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                                      const Box&                     box,
                                      gmx::ArrayRef<gmx::RVec>       forceOutput,
                                      gmx::ArrayRef<real>            virialOutput)
{
    impl_->compute(coordinateInput, box, forceOutput, virialOutput);
}

//! Compute forces, virial tensor and potential energies
void GmxNBForceCalculatorCpu::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput,
                                      const Box&                     box,
                                      gmx::ArrayRef<gmx::RVec>       forceOutput,
                                      gmx::ArrayRef<real>            virialOutput,
                                      gmx::ArrayRef<real>            energyOutput)
{
    impl_->compute(coordinateInput, box, forceOutput, virialOutput, energyOutput);
}

std::unique_ptr<GmxNBForceCalculatorCpu> setupGmxForceCalculatorCpu(const Topology&        topology,
                                                                    const NBKernelOptions& options)
{
    std::vector<real> nonBondedParameters = createNonBondedParameters(
            topology.getParticleTypes(), topology.getNonBondedInteractionMap());

    std::vector<int32_t> particleInteractionFlags = createParticleInfoAllVdw(topology.numParticles());

    return std::make_unique<GmxNBForceCalculatorCpu>(topology.getParticleTypeIdOfAllParticles(),
                                                     nonBondedParameters,
                                                     topology.getCharges(),
                                                     particleInteractionFlags,
                                                     topology.exclusionLists().ListRanges,
                                                     topology.exclusionLists().ListElements,
                                                     options);
}

std::unique_ptr<GmxNBForceCalculatorCpu> setupGmxForceCalculatorCpu(TprReader& tprReader,
                                                                    const NBKernelOptions& options)
{
    return std::make_unique<GmxNBForceCalculatorCpu>(tprReader.particleTypeIdOfAllParticles_,
                                                     tprReader.nonbondedParameters_,
                                                     tprReader.charges_,
                                                     tprReader.particleInteractionFlags_,
                                                     tprReader.exclusionListRanges_,
                                                     tprReader.exclusionListElements_,
                                                     options);
}

} // namespace nblib