CpuConstantPotentialForce.h 17.1 KB
Newer Older
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#ifndef OPENMM_CPUCONSTANTPOTENTIALFORCE_H_
#define OPENMM_CPUCONSTANTPOTENTIALFORCE_H_

/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
 * Portions copyright (c) 2025 Stanford University and the Authors.           *
 * Authors: Evan Pretti                                                       *
 * Contributors:                                                              *
 *                                                                            *
 * Permission is hereby granted, free of charge, to any person obtaining a    *
 * copy of this software and associated documentation files (the "Software"), *
 * to deal in the Software without restriction, including without limitation  *
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,   *
 * and/or sell copies of the Software, and to permit persons to whom the      *
 * Software is furnished to do so, subject to the following conditions:       *
 *                                                                            *
 * The above copyright notice and this permission notice shall be included in *
 * all copies or substantial portions of the Software.                        *
 *                                                                            *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   *
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    *
 * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,    *
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR      *
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE  *
 * USE OR OTHER DEALINGS IN THE SOFTWARE.                                     *
 * -------------------------------------------------------------------------- */

#include <array>

#include "CpuNeighborList.h"
#include "openmm/Kernel.h"
#include "openmm/kernels.h"
#include "openmm/internal/vectorize.h"
#include "tnt_array2d.h"
#include "jama_cholesky.h"

namespace OpenMM {

class CpuConstantPotentialForce;

/**
 * A generic charge solver for the constant potential method.
 */
class CpuConstantPotentialSolver {
public:
    /**
     * Creates a CpuConstantPotentialSolver.
     * 
     * @param numParticles           the number of particles
     * @param numElectrodeParticles  the number of electrode (fluctuating-charge) particles
     */
    CpuConstantPotentialSolver(int numParticles, int numElectrodeParticles);
    virtual ~CpuConstantPotentialSolver();
    /**
     * Mark precomputed data stored by the solver as invalid due to a change in
     * electrode parameters.
     */
    void invalidate();
    /**
     * Mark any existing solution stored by the solver as invalid due to a
     * change in system parameters.
     */
    void discardSavedSolution();
    /**
     * Solves for charges if needed.
     * 
     * @param conp       CPU constant potential force implementation
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    void solve(CpuConstantPotentialForce& conp, ThreadPool& threads, Kernel& pmeKernel);
    /**
     * Solves for charges.
     * 
     * @param conp       CPU constant potential force implementation
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    virtual void solveImpl(CpuConstantPotentialForce& conp, ThreadPool& threads, Kernel& pmeKernel) = 0;

protected:
    int numParticles, numElectrodeParticles;
    bool valid, hasSavedSolution;
    Vec3 savedBoxVectors[3];
    std::vector<Vec3> savedPositions;
    std::vector<float> savedCharges;
};

/**
 * A constant potential solver using direct inversion of the Coulomb matrix.
 * Suitable only when electrode particle positions are fixed.
 */
class CpuConstantPotentialMatrixSolver : public CpuConstantPotentialSolver {
private:
    Vec3 boxVectors[3];
    std::vector<Vec3> electrodePosData;
    JAMA::Cholesky<float> capacitance;
    std::vector<float> constraintVector;
    TNT::Array1D<float> b;

public:
    /**
     * Creates a CpuConstantPotentialMatrixSolver.
     * 
     * @param numParticles           the number of particles
     * @param numElectrodeParticles  the number of electrode (fluctuating-charge) particles
     */
    CpuConstantPotentialMatrixSolver(int numParticles, int numElectrodeParticles);
    /**
     * Solves for charges.
     * 
     * @param conp       CPU constant potential force implementation
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    void solveImpl(CpuConstantPotentialForce& conp, ThreadPool& threads, Kernel& pmeKernel);

private:
    /**
     * Ensures that precomputed data stored by the solver is valid.
     * 
     * @param conp       CPU constant potential force implementation
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    void ensureValid(CpuConstantPotentialForce& conp, ThreadPool& threads, Kernel& pmeKernel);
};

/**
 * A constant potential solver using the conjugate gradient method.  Suitable
 * for both fixed and variable electrode particle positions.
 */
class CpuConstantPotentialCGSolver : public CpuConstantPotentialSolver {
private:
    Vec3 boxVectors[3];
    bool precondRequested, precondActivated;
    std::vector<double> precondVector;
    std::vector<float> q;
    std::vector<float> grad;
    std::vector<float> projGrad;
    std::vector<float> precGrad;
    std::vector<float> qStep;
    std::vector<float> gradStep;
    std::vector<float> grad0;
    std::vector<float> qLast;

public:
    /**
     * Creates a CpuConstantPotentialCGSolver.
     * 
     * @param numParticles           the number of particles
     * @param numElectrodeParticles  the number of electrode (fluctuating-charge) particles
     * @param precond                whether or not to use a preconditioner
     */
    CpuConstantPotentialCGSolver(int numParticles, int numElectrodeParticles, bool precond);
    /**
     * Solves for charges.
     * 
     * @param conp       CPU constant potential force implementation
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    void solveImpl(CpuConstantPotentialForce& conp, ThreadPool& threads, Kernel& pmeKernel);

private:
    /**
     * Ensures that precomputed data stored by the solver is valid.
     * 
     * @param conp       CPU constant potential force implementation
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    void ensureValid(CpuConstantPotentialForce& conp, ThreadPool& threads, Kernel& pmeKernel);
};

/**
 * Performs energy, force, and charge derivative calculations for the CPU kernel
 * for ConstantPotentialForce.
 */
class CpuConstantPotentialForce {
    friend class CpuConstantPotentialSolver;
    friend class CpuConstantPotentialMatrixSolver;
    friend class CpuConstantPotentialCGSolver;

public:
    CpuConstantPotentialForce();
    virtual ~CpuConstantPotentialForce();

    /**
     * Initializes CpuConstantPotentialForce with data that cannot vary after
     * context creation, or pointers to data that can vary.
     * 
     * @param numParticles           the total number of particles
     * @param numElectrodeParticles  the number of electrode (fluctuating-charge) particles
     * @param posqIndex              index to identify charges loaded into the posq array
     * @param nonbondedCutoff        direct space cutoff
     * @param ewaldAlpha             Ewald reciprocal Gaussian width parameter
     * @param cgErrorTol             constant potential conjugate gradient error tolerance
     * @param gridSize               Ewald mesh dimensions
     * @param exceptionsArePeriodic  whether or not exceptions use periodic boundary conditions
     * @param useChargeConstraint    whether or not to constrain total charge
     * @param neighborList           neighbor list for direct space calculation
     * @param solver                 charge solver implementation
     * @param exclusions             particle exclusions
     * @param sysToElec              mapping from system particle indices to electrode particle indices
     * @param elecToSys              mapping from electrode particle indices to system particle indices
     * @param sysElec                mapping from system particle indices to electrode indices
     * @param elecElec               mapping from electrode particle indices to electrode indices
     * @param electrodeParams        electrode parameters
     * @param chargeTarget           target sum of charges on electrode particles only
     * @param externalField          electric field vector
     */
    void initialize(int numParticles, int numElectrodeParticles, int posqIndex,
        float nonbondedCutoff, float ewaldAlpha, float cgErrorTol,
        const int* gridSize, bool exceptionsArePeriodic,
        bool useChargeConstraint, const CpuNeighborList& neighborList,
        CpuConstantPotentialSolver* solver,
        const std::vector<std::set<int> >& exclusions,
        const std::vector<int>& sysToElec, const std::vector<int>& elecToSys,
        const std::vector<int>& sysElec, const std::vector<int>& elecElec,
        const std::vector<std::array<double, 3> >& electrodeParams,
        float chargeTarget, const float* externalField);
    /**
     * Updates CpuConstantPotentialForce after data has been modified.
     * 
     * @param chargeTarget    target sum of charges on electrode particles only
     * @param externalField   electric field vector
     * @param firstElectrode  index of the first electrode whose parameters may have been modified
     * @param lastElectrode   index of the last electrode whose parameters may have been modified
     */
    void update(float chargeTarget, const float* externalField,
        int firstElectrode, int lastElectrode);
    /**
     * Solves for charges and computes energies and forces.
     * 
     * @param boxVectors   periodic box vectors
     * @param posData      particle positions
     * @param charges      output particle charges
     * @param posq         wrapped single-precision position and charge array
     * @param threadForce  per-thread force accumulation arrays
     * @param energy       output system energy
     * @param threads      thread pool for parallel evaluation
     * @param pmeKernel    CPU PME solver kernel
     */
    void execute(const Vec3* boxVectors, const std::vector<Vec3>& posData,
        std::vector<float>& charges, float* posq,
        std::vector<AlignedArray<float> >& threadForce, double* energy,
        ThreadPool& threads, Kernel& pmeKernel);
    /**
     * Solves for charges without computing energies and forces.
     * 
     * @param boxVectors   periodic box vectors
     * @param posData      particle positions
     * @param charges      output particle charges
     * @param posq         wrapped single-precision position and charge array
     * @param threadForce  per-thread force accumulation arrays
     * @param threads      thread pool for parallel evaluation
     * @param pmeKernel    CPU PME solver kernel
     */
    void getCharges(const Vec3* boxVectors, const std::vector<Vec3>& posData,
        std::vector<float>& charges, float* posq,
        std::vector<AlignedArray<float> >& threadForce, ThreadPool& threads,
        Kernel& pmeKernel);

protected:
    /**
     * Precomputes values and updates pointers to data accessed by threads.
     * 
     * @param boxVectors   periodic box vectors
     * @param posData      particle positions
     * @param posq         wrapped single-precision position and charge array
     * @param threadForce  per-thread force accumulation arrays
     */
    void setThreadData(const Vec3* boxVectors, const std::vector<Vec3>& posData, float* posq, std::vector<AlignedArray<float> >& threadForce);
    /**
     * Extracts electrode particle charges from posq and places them in the
     * output charge array.
     * 
     * @param charges  output particle charges
     */
    void saveCharges(std::vector<float>& charges);
    /**
     * Computes energies and forces for fixed (solved) charges.
     * 
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     * @param energy     output system energy
     */
    void getEnergyForces(ThreadPool& threads, Kernel& pmeKernel, double* energy);
    /**
     * Thread worker for getEnergyForcesThread().
     * 
     * @param threads      thread pool for parallel evaluation
     * @param threadIndex  index of the thread in the thread pool
     * @param energy       whether or not to compute system energy
     */
    void getEnergyForcesThread(ThreadPool& threads, int threadIndex, bool includeEnergy);
    /**
     * Computes energy derivatives with respect to charges.
     * 
     * @param threads    thread pool for parallel evaluation
     * @param pmeKernel  CPU PME solver kernel
     */
    void getDerivatives(ThreadPool& threads, Kernel& pmeKernel);
    /**
     * Thread worker for getDerivatives().
     * 
     * @param threads      thread pool for parallel evaluation
     * @param threadIndex  index of the thread in the thread pool
     * @param plasmaTerm   precomputed neutralizing plasma term for derivatives
     */
    void getDerivativesThread(ThreadPool& threads, int threadIndex, float plasmaTerm);
    /**
     * Calculates a displacement between a pair of exception particles.
     * 
     * @param posI    the position of the first particle
     * @param posJ    the position of the second particle
     * @param deltaR  the displacement vector from particle I to particle J
     * @param r2      the square magnitude of the displacement vector
     */
    void getExceptionDeltaR(const fvec4& posI, const fvec4& posJ, fvec4& deltaR, float& r2) const;

    /**
     * Computes the direct space contribution to energies and forces for one
     * block of particles.
     * 
     * @param blockIndex  the index of the block
     * @param forces      output forces
     * @param energy      output energy
     */
    virtual void getEnergyForcesBlock(int blockIndex, float* forces, double* energy) = 0;
    /**
     * Computes the direct space contribution to charge derivatives for one
     * block of particles.
     * 
     * @param blockIndex   the index of the block
     * @param derivatives  output derivatives
     */
    virtual void getDerivativesBlock(int blockIndex, float* derivatives) = 0;
private:
    /**
     * Initializes energy and force lookup tables for a pair of electrodes.
     * 
     * @param ie  the index of the first electrode
     * @param je  the index of the second electrode
     */
    void initializeLookupTables(int ie, int je);

protected:
    static const int PotentialIndex;
    static const int GaussianWidthIndex;
    static const int ThomasFermiScaleIndex;

    static const int NUM_TABLE_POINTS;

    static const double TWO_OVER_SQRT_PI;
    static const double SELF_ALPHA_SCALE;
    static const double SELF_ETA_SCALE;
    static const double SELF_TF_SCALE;

    int numParticles, numElectrodeParticles, numElectrodes, posqIndex;
    float nonbondedCutoff, ewaldAlpha, cgErrorTol;
    int gridSize[3];
    bool exceptionsArePeriodic, useChargeConstraint;
    const CpuNeighborList* neighborList;
    CpuConstantPotentialSolver* solver;

    const std::set<int>* exclusions;
    const int* sysToElec;
    const int* elecToSys;
    const int* sysElec;
    const int* elecElec;
    const std::array<double, 3>* electrodeParams;

    std::vector<float> electrodePotentials;
    std::vector<float> electrodeSelfScales;

    float chargeTarget;
    fvec4 externalField;

    Vec3 boxVectors[3];
    AlignedArray<fvec4> boxVectorsVec4;
    fvec4 boxSize;
    fvec4 recipBoxSize;
    bool triclinic;
    float plasmaScale;

    const Vec3* posData;
    float* posq;
    std::vector<double> threadEnergy;
    std::vector<AlignedArray<float> >* threadForce;
    std::vector<float> chargeDerivatives;
    std::vector<float> energyLookupTable;
    std::vector<float> forceLookupTable;
    float tableScale;

    std::atomic<int> atomicBlockCounter, atomicParticleCounter;
};

class CpuConstantPotentialPmeIO : public CalcPmeReciprocalForceKernel::IO {
public:
    CpuConstantPotentialPmeIO(float* posq, float* force, float* chargeDerivatives, int numParticles, int numElectrodeParticles);
    float* getPosq();
    void setForce(float* f);
    void setChargeDerivatives(float* derivatives);
private:
    float* posq;
    float* force;
    float* chargeDerivatives;
    int numParticles;
    int numElectrodeParticles;
};

} // namespace OpenMM

#endif // OPENMM_CPUCONSTANTPOTENTIALFORCE_H_