ReferenceConstantPotential.cpp 30 KB
Newer Older
1
2
3
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
Evan Pretti's avatar
Evan Pretti committed
4
5
 * This is part of the OpenMM molecular simulation toolkit.                   *
 * See https://openmm.org/development.                                        *
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
 *                                                                            *
 * 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 "ReferenceConstantPotential.h"
#include "ReferenceForce.h"
#include "SimTKOpenMMUtilities.h"
#include "openmm/OpenMMException.h"
#include "openmm/internal/MSVC_erfc.h"

using namespace OpenMM;

ReferenceConstantPotentialSolver::ReferenceConstantPotentialSolver() : valid(false) {
}

ReferenceConstantPotentialSolver::~ReferenceConstantPotentialSolver() {
}

void ReferenceConstantPotentialSolver::invalidate() {
    valid = false;
}

ReferenceConstantPotentialMatrixSolver::ReferenceConstantPotentialMatrixSolver(int numElectrodeParticles) : ReferenceConstantPotentialSolver(),
    electrodePosData(numElectrodeParticles), constraintVector(numElectrodeParticles) {
}

void ReferenceConstantPotentialMatrixSolver::update(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    const std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    ReferenceConstantPotential& conp
) {
    // Initializes or updates the precomputed capacitance matrix if this is its
    // first use or electrode parameters have changed since its initialization.

    // Check for changes to box vectors or electrode positions that might
    // invalidate a matrix that is currently marked valid.
    if (valid) {
        if (boxVectors[0] != conp.boxVectors[0] || boxVectors[1] != conp.boxVectors[1] || boxVectors[2] != conp.boxVectors[2]) {
            valid = false;
        }
    }
    if (valid) {
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            if (electrodePosData[ii] != posData[elecToSys[ii]]) {
                valid = false;
                break;
            }
        }
    }
    if (valid) {
        return;
    }

    // Store the current box vectors and electrode positions before updating the
    // capacitance matrix.
    valid = true;
    boxVectors[0] = conp.boxVectors[0];
    boxVectors[1] = conp.boxVectors[1];
    boxVectors[2] = conp.boxVectors[2];
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        electrodePosData[ii] = posData[elecToSys[ii]];
    }

    TNT::Array2D<double> A(numElectrodeParticles, numElectrodeParticles);
    std::vector<double> dUdQ0(numElectrodeParticles);
    std::vector<double> dUdQ(numElectrodeParticles);
    
Peter Eastman's avatar
Peter Eastman committed
99
    ReferencePME pme(conp.ewaldAlpha, numParticles, conp.gridSize, 5, 1);
100
101
102
103
104
105

    // Get derivatives when all electrode charges are zeroed.
    std::vector<double> q(charges);
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        q[elecToSys[ii]] = 0.0;
    }
Peter Eastman's avatar
Peter Eastman committed
106
    conp.getDerivatives(numParticles, numElectrodeParticles, posData, q, exclusions, sysToElec, elecToSys, electrodeParamArray, dUdQ0, pme);
107
108
109
110
111
112

    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        int i = elecToSys[ii];

        // Get derivatives when one electrode charge is set.
        q[i] = 1.0;
Peter Eastman's avatar
Peter Eastman committed
113
        conp.getDerivatives(numParticles, numElectrodeParticles, posData, q, exclusions, sysToElec, elecToSys, electrodeParamArray, dUdQ, pme);
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
        q[i] = 0.0;

        // Set matrix elements, subtracting zero charge derivatives so that the
        // matrix will end up being the (charge-independent) Hessian.
        for (int jj = 0; jj < ii; jj++) {
            A[ii][jj] = A[jj][ii] = dUdQ[jj] - dUdQ0[jj];
        }
        A[ii][ii] = dUdQ[ii] - dUdQ0[ii];
    }

    // Compute Cholesky decomposition representation of the inverse.
    capacitance = JAMA::Cholesky<double>(A);
    if (!capacitance.is_spd()) {
        throw OpenMMException("Electrode matrix not positive definite");
    }

    // Precompute the appropriate scaling vector to enforce constant total
    // charge if requested.  The vector is parallel to one obtained by solving
    // Aq = b for all q_i = 1 (ensuring the constrained charges will actually be
    // the correct constrained minimum of the quadratic form for the energy),
    // and is scaled so that adding it to a vector of charges increases the
    // total charge by 1 (making it easy to calculate the necessary offset).
    if (conp.useChargeConstraint) {
        TNT::Array1D<double> solution = capacitance.solve(TNT::Array1D<double>(numElectrodeParticles, 1.0));
        constraintVector.assign(static_cast<double*>(solution), static_cast<double*>(solution) + numElectrodeParticles);

        double constraintScaleInv = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            constraintScaleInv += constraintVector[ii];
        }
        double constraintScale = 1.0 / constraintScaleInv;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            constraintVector[ii] *= constraintScale;
        }
    }
}

void ReferenceConstantPotentialMatrixSolver::solve(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    ReferenceConstantPotential& conp,
Peter Eastman's avatar
Peter Eastman committed
161
    ReferencePME& pme
162
163
164
165
166
167
168
169
) {
    // Solves for charges using the matrix method.

    // Zero electrode charges and get derivatives at zero charge.
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        charges[elecToSys[ii]] = 0.0;
    }
    std::vector<double> b(numElectrodeParticles);
Peter Eastman's avatar
Peter Eastman committed
170
    conp.getDerivatives(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, b, pme);
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
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        b[ii] = -b[ii];
    }

    // Solve for electrode charges directly using capacitance matrix and
    // calculated derivatives.
    TNT::Array1D<double> q = capacitance.solve(TNT::Array1D<double>(numElectrodeParticles, b.data()));
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        charges[elecToSys[ii]] = q[ii];
    }

    // Enforce total charge constraint if requested.
    if (conp.useChargeConstraint) {
        double chargeOffset = conp.chargeTarget;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            chargeOffset -= q[ii];
        }
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            charges[elecToSys[ii]] += chargeOffset * constraintVector[ii];
        }
    }
}

ReferenceConstantPotentialCGSolver::ReferenceConstantPotentialCGSolver(int numElectrodeParticles, bool precond) : ReferenceConstantPotentialSolver(),
    precond(precond), precondVector(numElectrodeParticles) {
}

void ReferenceConstantPotentialCGSolver::update(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    const std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    ReferenceConstantPotential& conp
) {
    // Initializes or updates information for a preconditioner for the conjugate
    // gradient method if this is its first use or electrode parameters have
    // changed since its initialization.
    
    const double SQRT_PI = sqrt(PI_M);
    const double SELF_ALPHA_SCALE = 2.0 * ONE_4PI_EPS0 / SQRT_PI;
    const double SELF_ETA_SCALE = SELF_ALPHA_SCALE / sqrt(2.0);
    const double TF_SCALE = 1.0 / EPSILON0;
    const double PLASMA_SCALE = TF_SCALE / 4.0;

    // No action is required if the box vectors have not changed.
    if (valid && boxVectors[0] == conp.boxVectors[0] && boxVectors[1] == conp.boxVectors[1] && boxVectors[2] == conp.boxVectors[2]) {
        return;
    }

    valid = true;
    boxVectors[0] = conp.boxVectors[0];
    boxVectors[1] = conp.boxVectors[1];
    boxVectors[2] = conp.boxVectors[2];

    if (precond) {
        // Perform a reference PME calculation with a single charge at the origin to
        // find the constant offset on the preconditioner diagonal due to the PME
        // calculation.  This will actually vary slightly with position but only due
        // to finite accuracy of the PME splines, so it is fine to assume it will be
        // constant for the preconditioner.
Peter Eastman's avatar
Peter Eastman committed
235
        ReferencePME pme(conp.ewaldAlpha, 1, conp.gridSize, 5, 1);
236
237
238
239
        std::vector<Vec3> pmePosData(1);
        std::vector<double> pmeChargeDerivatives(1);
        std::vector<int> pmeElectrodeIndices(1);
        std::vector<double> pmeCharges(1, 1.0);
Peter Eastman's avatar
Peter Eastman committed
240
        pme.exec_charge_derivatives(pmePosData, pmeChargeDerivatives, pmeElectrodeIndices, pmeCharges, boxVectors);
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

        // The diagonal has a contribution from reciprocal space, Ewald
        // self-interaction, Ewald neutralizing plasma, Gaussian self-interaction,
        // and Thomas-Fermi contributions.
        double volume = boxVectors[0][0] * boxVectors[1][1] * boxVectors[2][2];
        double ewaldTerm = pmeChargeDerivatives[0] - SELF_ALPHA_SCALE * conp.ewaldAlpha - PLASMA_SCALE / (volume * conp.ewaldAlpha * conp.ewaldAlpha);

        double precondScaleInv = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            precondVector[ii] = 1.0 / (SELF_ETA_SCALE / electrodeParamArray[ii][conp.GaussianWidthIndex]
                + TF_SCALE * electrodeParamArray[ii][conp.ThomasFermiScaleIndex] + ewaldTerm);
            precondScaleInv += precondVector[ii];
        }
        double precondScale = 1.0 / precondScaleInv;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            precondVector[ii] *= precondScale;
        }
    }
}

void ReferenceConstantPotentialCGSolver::solve(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    ReferenceConstantPotential& conp,
Peter Eastman's avatar
Peter Eastman committed
271
    ReferencePME& pme
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
) {
    // Solves for charges using the conjugate gradient method.
    
    std::vector<double> q(numElectrodeParticles);
    std::vector<double> grad(numElectrodeParticles);
    std::vector<double> projGrad(numElectrodeParticles);
    std::vector<double> precGrad(numElectrodeParticles);
    std::vector<double> qStep(numElectrodeParticles);
    std::vector<double> gradStep(numElectrodeParticles);
    std::vector<double> grad0(numElectrodeParticles);
    double offset, error, paramScale, alpha, beta;

    const double errorTarget = conp.cgErrorTol * conp.cgErrorTol * numElectrodeParticles;

    // Ensure that initial guess charges satisfy the constraint.
    if (conp.useChargeConstraint) {
        offset = conp.chargeTarget;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            offset -= charges[elecToSys[ii]];
        }
        offset /= numElectrodeParticles;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            charges[elecToSys[ii]] += offset;
        }
    }

    // Evaluate the initial gradient Aq - b.
Peter Eastman's avatar
Peter Eastman committed
299
    conp.getDerivatives(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, grad, pme);
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

    // Project the initial gradient without preconditioning.
    offset = 0.0;
    if (conp.useChargeConstraint) {
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            offset += grad[ii];
        }
        offset /= numElectrodeParticles;
    }
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        projGrad[ii] = grad[ii] - offset;
    }

    // Check for convergence at the initial guess charges.
    error = 0.0;
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        error += projGrad[ii] * projGrad[ii];
    }
    if (error <= errorTarget) {
        return;
    }

    // Save the current charges, then evaluate the gradient with zero
    // charges (-b) so that we can later compute Ap as (Ap - b) - (-b).
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        int i = elecToSys[ii];
        q[ii] = charges[i];
        charges[i] = 0.0;
    }
Peter Eastman's avatar
Peter Eastman committed
329
    conp.getDerivatives(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, grad0, pme);
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

    // Project the initial gradient with preconditioning.
    if (precond) {
        offset = 0.0;
        if (conp.useChargeConstraint) {
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                offset += precondVector[ii] * grad[ii];
            }
        }
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            precGrad[ii] = precondVector[ii] * (grad[ii] - offset);
        }
    }
    else {
        precGrad.assign(projGrad.begin(), projGrad.end());
    }

    // Initialize step vector for conjugate gradient iterations.
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        qStep[ii] = -precGrad[ii];
    }

    // Perform conjugate gradient iterations.
    bool converged = false;
    for (int iter = 0; iter <= numElectrodeParticles; iter++) {
        // Evaluate the matrix-vector product A qStep.
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            charges[elecToSys[ii]] = qStep[ii];
        }
Peter Eastman's avatar
Peter Eastman committed
359
        conp.getDerivatives(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, gradStep, pme);
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
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            gradStep[ii] -= grad0[ii];
        }

        // If A qStep is small enough, stop to prevent, e.g., division by
        // zero in the calculation of alpha, or too large step sizes.
        error = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            error += gradStep[ii] * gradStep[ii];
        }
        if (error <= errorTarget) {
            converged = true;
            break;
        }
        
        // Evaluate the scalar 1 / (qStep^T A qStep).
        paramScale = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            paramScale += qStep[ii] * gradStep[ii];
        }
        paramScale = 1.0 / paramScale;

        // Evaluate the conjugate gradient parameter alpha.
        alpha = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            alpha -= qStep[ii] * grad[ii];
        }
        alpha *= paramScale;

        // Update the charge vector.
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            q[ii] += alpha * qStep[ii];
        }

        if (conp.useChargeConstraint) {
            // Remove any accumulated drift from the charge vector.  This
            // would be zero in exact arithmetic, but error can accumulate
            // over time in finite precision.
            offset = conp.chargeTarget;
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                offset -= q[ii];
            }
            offset /= numElectrodeParticles;
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                q[ii] += offset;
            }
        }

        // Update the gradient vector (but periodically recompute it instead
        // of updating to reduce the accumulation of roundoff error).
        if (iter != 0 && iter % 32 == 0) {
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                charges[elecToSys[ii]] = q[ii];
            }
Peter Eastman's avatar
Peter Eastman committed
414
            conp.getDerivatives(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, grad, pme);
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
        }
        else {
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                grad[ii] += alpha * gradStep[ii];
            }
        }

        // Project the current gradient without preconditioning.
        offset = 0.0;
        if (conp.useChargeConstraint) {
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                offset += grad[ii];
            }
            offset /= numElectrodeParticles;
        }
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            projGrad[ii] = grad[ii] - offset;
        }

        // Check for convergence.
        error = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            error += projGrad[ii] * projGrad[ii];
        }
        if (error <= errorTarget) {
            converged = true;
            break;
        }

        // Project the current gradient with preconditioning.
        if (precond) {
            offset = 0.0;
            if (conp.useChargeConstraint) {
                for (int ii = 0; ii < numElectrodeParticles; ii++) {
                    offset += precondVector[ii] * grad[ii];
                }
            }
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                precGrad[ii] = precondVector[ii] * (grad[ii] - offset);
            }
        }
        else {
            precGrad.assign(projGrad.begin(), projGrad.end());
        }

        // Evaluate the conjugate gradient parameter beta.
        beta = 0.0;
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            beta += precGrad[ii] * gradStep[ii];
        }
        beta *= paramScale;

        // Update the step vector.
        for (int ii = 0; ii < numElectrodeParticles; ii++) {
            qStep[ii] = beta * qStep[ii] - precGrad[ii];
        }

        if (conp.useChargeConstraint) {
            // Project out any deviation off of the constraint plane from
            // the step vector.  This would be zero in exact arithmetic, but
            // error can accumulate over time in finite precision.
            offset = 0.0;
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                offset += qStep[ii];
            }
            offset /= numElectrodeParticles;
            for (int ii = 0; ii < numElectrodeParticles; ii++) {
                qStep[ii] -= offset;
            }
        }
    }

    if (!converged) {
        throw OpenMMException("Constant potential conjugate gradient iterations not converged");
    }

    // Store the final charges.
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        charges[elecToSys[ii]] = q[ii];
    }
}

ReferenceConstantPotential::ReferenceConstantPotential(
    double nonbondedCutoff,
    const NeighborList* neighborList,
    const Vec3* boxVectors,
    bool exceptionsArePeriodic,
    double ewaldAlpha,
    const int* gridSize,
    double cgErrorTol,
    bool useChargeConstraint,
    double chargeTarget,
    Vec3 externalField
) : nonbondedCutoff(nonbondedCutoff),
    neighborList(neighborList),
    exceptionsArePeriodic(exceptionsArePeriodic),
    ewaldAlpha(ewaldAlpha),
    cgErrorTol(cgErrorTol),
    useChargeConstraint(useChargeConstraint),
    chargeTarget(chargeTarget),
    externalField(externalField)
{
    this->boxVectors[0] = boxVectors[0];
    this->boxVectors[1] = boxVectors[1];
    this->boxVectors[2] = boxVectors[2];
    this->gridSize[0] = gridSize[0];
    this->gridSize[1] = gridSize[1];
    this->gridSize[2] = gridSize[2];
}


void ReferenceConstantPotential::execute(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    std::vector<Vec3>& forceData,
    std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    double* energy,
    ReferenceConstantPotentialSolver* solver
) {
Peter Eastman's avatar
Peter Eastman committed
539
540
541
    ReferencePME pme(ewaldAlpha, numParticles, gridSize, 5, 1);
    solver->solve(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, *this, pme);
    getEnergyForces(numParticles, numElectrodeParticles, posData, forceData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, energy, pme);
542
543
544
545
546
547
548
549
550
551
552
553
554
}

void ReferenceConstantPotential::getCharges(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    ReferenceConstantPotentialSolver* solver
) {
Peter Eastman's avatar
Peter Eastman committed
555
556
    ReferencePME pme(ewaldAlpha, numParticles, gridSize, 5, 1);
    solver->solve(numParticles, numElectrodeParticles, posData, charges, exclusions, sysToElec, elecToSys, electrodeParamArray, *this, pme);
557
558
559
560
561
562
563
564
565
566
567
568
569
}

void ReferenceConstantPotential::getEnergyForces(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    std::vector<Vec3>& forceData,
    std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    double* energy,
Peter Eastman's avatar
Peter Eastman committed
570
    ReferencePME& pme
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
) {
    const double SQRT_PI = sqrt(PI_M);
    const double TWO_OVER_SQRT_PI = 2.0 / SQRT_PI;
    const double SELF_ALPHA_SCALE = ONE_4PI_EPS0 / SQRT_PI;
    const double SELF_ETA_SCALE = SELF_ALPHA_SCALE / sqrt(2.0);
    const double TF_SCALE = 1.0 / (2.0 * EPSILON0);
    const double PLASMA_SCALE = TF_SCALE / 4.0;

    double energyAccum = 0.0;

    // Direct space.
    for (auto& pair : *neighborList) {
        int i = pair.first;
        int j = pair.second;
        int ii = sysToElec[i];
        int jj = sysToElec[j];

        double iWidth = ii == -1 ? 0.0 : electrodeParamArray[ii][GaussianWidthIndex];
        double jWidth = jj == -1 ? 0.0 : electrodeParamArray[jj][GaussianWidthIndex];
        double width = sqrt(iWidth * iWidth + jWidth * jWidth);

        double deltaR[ReferenceForce::LastDeltaRIndex];
        ReferenceForce::getDeltaRPeriodic(posData[i], posData[j], boxVectors, deltaR);
        double r = deltaR[ReferenceForce::RIndex];
        double inverseR = 1.0 / r;

        double alphaR = ewaldAlpha * r;
        double erfcAlphaR = erfc(alphaR);

        double etaR = 0.0;
        double erfcEtaR = 0.0;
        double expEtaRTerm = 0.0;
        if (width != 0.0) {
            etaR = r / width;
            erfcEtaR = erfc(etaR);
            expEtaRTerm = etaR * exp(-etaR * etaR);
        }

        double qqFactor = ONE_4PI_EPS0 * charges[i] * charges[j];
        double forceFactor = qqFactor * inverseR * inverseR * inverseR * (erfcAlphaR - erfcEtaR + TWO_OVER_SQRT_PI * (alphaR * exp(-alphaR * alphaR) - expEtaRTerm));
        for (int k = 0; k < 3; k++) {
            double force = forceFactor * deltaR[k];
            forceData[i][k] -= force;
            forceData[j][k] += force;
        }

        energyAccum += qqFactor * inverseR * (erfcAlphaR - erfcEtaR);
    }

    // Exceptions.
    for (int i = 0; i < numParticles; i++) {
        for (int j : exclusions[i]) {
            if (j <= i) {
                continue;
            }

            double deltaR[ReferenceForce::LastDeltaRIndex];
            if (exceptionsArePeriodic) {
                ReferenceForce::getDeltaRPeriodic(posData[i], posData[j], boxVectors, deltaR);
            }
            else {
                ReferenceForce::getDeltaR(posData[i], posData[j], deltaR);
            }
            double r = deltaR[ReferenceForce::RIndex];
            double inverseR = 1.0 / r;

            double qqFactor = ONE_4PI_EPS0 * charges[i] * charges[j];
            double alphaR = ewaldAlpha * r;

            if (alphaR > 1e-6) {
                double erfAlphaR = erf(alphaR);

                double forceFactor = qqFactor * inverseR * inverseR * inverseR * (erfAlphaR - TWO_OVER_SQRT_PI * alphaR * exp(-alphaR * alphaR));
                for (int k = 0; k < 3; k++) {
                    double force = forceFactor * deltaR[k];
                    forceData[i][k] += force;
                    forceData[j][k] -= force;
                }

                energyAccum -= qqFactor * inverseR * erfAlphaR;
            }
            else {
                energyAccum -= qqFactor * TWO_OVER_SQRT_PI * ewaldAlpha;
            }
        }
    }
    
    // Reciprocal space.
    double pmeEnergy = 0.0;
Peter Eastman's avatar
Peter Eastman committed
660
    pme.exec(posData, forceData, charges, boxVectors, pmeEnergy);
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
    energyAccum += pmeEnergy;

    // Ewald self-interaction and external field contributions (all particles).
    double qTotal = 0.0;
    for (int i = 0; i < numParticles; i++) {
        double q = charges[i];
        qTotal += q;
        energyAccum -= q * (SELF_ALPHA_SCALE * q * ewaldAlpha + posData[i].dot(externalField));
        forceData[i] += q * externalField;
    }

    // Ewald neutralizing plasma.
    double volume = boxVectors[0][0] * boxVectors[1][1] * boxVectors[2][2];
    energyAccum -= PLASMA_SCALE * qTotal * qTotal / (volume * ewaldAlpha * ewaldAlpha);

    // Gaussian self-interaction, potential, and Thomas-Fermi contributions
    // (electrode particles only).
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        int i = elecToSys[ii];
        double q = charges[i];
        energyAccum += q * (q * (SELF_ETA_SCALE / electrodeParamArray[ii][GaussianWidthIndex] + TF_SCALE * electrodeParamArray[ii][ThomasFermiScaleIndex]) - electrodeParamArray[ii][PotentialIndex]);
    }

    if (energy) {
        *energy += energyAccum;
    }
}

void ReferenceConstantPotential::getDerivatives(
    int numParticles,
    int numElectrodeParticles,
    const std::vector<Vec3>& posData,
    std::vector<double>& charges,
    const std::vector<std::set<int>>& exclusions,
    const std::vector<int>& sysToElec,
    const std::vector<int>& elecToSys,
    const std::vector<std::array<double, 3> >& electrodeParamArray,
    std::vector<double>& chargeDerivatives,
Peter Eastman's avatar
Peter Eastman committed
699
    ReferencePME& pme
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
) {
    const double SQRT_PI = sqrt(PI_M);
    const double SELF_ALPHA_SCALE = 2.0 * ONE_4PI_EPS0 / SQRT_PI;
    const double SELF_ETA_SCALE = SELF_ALPHA_SCALE / sqrt(2.0);
    const double TF_SCALE = 1.0 / EPSILON0;
    const double PLASMA_SCALE = TF_SCALE / 4.0;

    // chargeDerivatives is to be overwritten by this function, not incremented,
    // so zero all derivatives initially.
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        chargeDerivatives[ii] = 0.0;
    }

    // Direct space (both particles in each exception will be non-electrode, so
    // we do not need to loop over exceptions when computing derivatives with
    // respect to electrode charges).
    for (auto& pair : *neighborList) {
        int i = pair.first;
        int j = pair.second;
        int ii = sysToElec[i];
        int jj = sysToElec[j];

        if (ii == -1 && jj == -1) {
            continue;
        }

        double iWidth = ii == -1 ? 0.0 : electrodeParamArray[ii][GaussianWidthIndex];
        double jWidth = jj == -1 ? 0.0 : electrodeParamArray[jj][GaussianWidthIndex];
        double width = sqrt(iWidth * iWidth + jWidth * jWidth);

        double deltaR[ReferenceForce::LastDeltaRIndex];
        ReferenceForce::getDeltaRPeriodic(posData[i], posData[j], boxVectors, deltaR);
        double r = deltaR[ReferenceForce::RIndex];

        double erfcEtaR = width == 0.0 ? 0.0 : erfc(r / width);
        double factor = ONE_4PI_EPS0 * (erfc(ewaldAlpha * r) - erfcEtaR) / r;

        if (ii != -1) {
            chargeDerivatives[ii] += charges[j] * factor;
        }
        if (jj != -1) {
            chargeDerivatives[jj] += charges[i] * factor;
        }
    }

    // Reciprocal space.
Peter Eastman's avatar
Peter Eastman committed
746
    pme.exec_charge_derivatives(posData, chargeDerivatives, elecToSys, charges, boxVectors);
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765

    // Ewald neutralizing plasma precalculation.
    double qTotal = 0.0;
    for (int i = 0; i < numParticles; i++) {
        qTotal += charges[i];
    }
    double volume = boxVectors[0][0] * boxVectors[1][1] * boxVectors[2][2];
    double plasmaTerm = PLASMA_SCALE * qTotal / (volume * ewaldAlpha * ewaldAlpha);

    // Ewald self-interaction, Ewald neutralizing plasma, Gaussian
    // self-interaction, potential, external field, and Thomas-Fermi
    // contributions.
    for (int ii = 0; ii < numElectrodeParticles; ii++) {
        int i = elecToSys[ii];
        double q = charges[i];
        chargeDerivatives[ii] += q * (SELF_ETA_SCALE / electrodeParamArray[ii][GaussianWidthIndex] - SELF_ALPHA_SCALE * ewaldAlpha + TF_SCALE * electrodeParamArray[ii][ThomasFermiScaleIndex])
            - plasmaTerm - electrodeParamArray[ii][PotentialIndex] - posData[i].dot(externalField);
    }
}